blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
132
path
stringlengths
2
382
src_encoding
stringclasses
34 values
length_bytes
int64
9
3.8M
score
float64
1.5
4.94
int_score
int64
2
5
detected_licenses
listlengths
0
142
license_type
stringclasses
2 values
text
stringlengths
9
3.8M
download_success
bool
1 class
63f71170f6267e8f8d6f41253aad7ec2f8b88b1b
Java
decc/national-household-model-core-components
/core-projects/nhm-reportengine/src/main/java/uk/org/cse/nhm/reporting/standard/explain/ExplainJSONOutput.java
UTF-8
5,670
2.171875
2
[]
no_license
package uk.org.cse.nhm.reporting.standard.explain; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.SortedSet; import org.joda.time.DateTime; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.ImmutableSortedSet.Builder; import com.google.common.collect.SortedSetMultimap; import com.google.common.collect.TreeMultimap; import uk.org.cse.nhm.logging.logentry.ExplainArrow; import uk.org.cse.nhm.logging.logentry.ExplainLogEntry; import uk.org.cse.nhm.reporting.report.IReportOutput; import uk.org.cse.nhm.reporting.report.SizeRecordingReportOutput; import uk.org.cse.nhm.reporting.standard.explain.model.Edge; import uk.org.cse.nhm.reporting.standard.explain.model.FromOutsideNode; import uk.org.cse.nhm.reporting.standard.explain.model.Node; import uk.org.cse.nhm.reporting.standard.explain.model.NodesAndLinks; import uk.org.cse.nhm.reporting.standard.explain.model.OriginNode; import uk.org.cse.nhm.reporting.standard.explain.model.ToOutsideNode; import uk.org.cse.nhm.reporting.standard.jsonp.JSONPOutputUtility; /** * @since 3.1.1 * @author glenns */ public class ExplainJSONOutput extends SizeRecordingReportOutput { protected final Node fromOutside = new FromOutsideNode(); protected final Node toOutside = new ToOutsideNode(); protected final List<Node> nodes = new ArrayList<Node>(); protected final List<Edge> edges = new ArrayList<Edge>(); protected final SortedSet<ExplainLogEntry> logs; protected final String path; protected Map<String, Node> originNodes = new HashMap<String, Node>(); protected int step = 0; public ExplainJSONOutput(String reportName, SortedSet<ExplainLogEntry> logs) { this.path = String.format("explain-%s.jsonp", reportName); AfterElimination afterElimination = tryEliminateStockCreator(logs); nodes.addAll(afterElimination.originNodes); for (Node origin : afterElimination.originNodes) { originNodes.put(origin.getName(), origin); } this.logs = afterElimination.remainingLogs; } @Override public String getPath() { return IReportOutput.DATA + path; } @Override public void doWriteContent(OutputStream outputStream) throws IOException { JSONPOutputUtility.writeAsJSONP(this, buildReport(), outputStream); } @Override public String getTemplate() { return IReportOutput.GENERIC_TEMPLATE; } @Override public Type getType() { return Type.Data; } public NodesAndLinks buildReport() { buildReportSteps(logs); connectUnconnectedNodes(); for (Edge edge : edges) { edge.setNodeSearchSource(nodes); } if (fromOutside.getTotalSize() > 0) { nodes.add(fromOutside); } if (toOutside.getTotalSize() > 0) { nodes.add(toOutside); } return new NodesAndLinks(nodes, edges); } /** * Because we remove the stock creation step, nodes may be left unconnected if there are no subsequent changes made to them. * This method adds an edge to indicate that this group was unchanged during the scenario. */ private void connectUnconnectedNodes() { List<Node> generatedEndpoints = new ArrayList<Node>(); for(Node node : nodes) { if(node.isUnconnected()) { Node endPoint = new Node(node.getName()); generatedEndpoints.add(endPoint); Edge unchanged = new Edge(node, endPoint, node.calcRemainingSizeToAllocateToChildren(), "unchanged"); edges.add(unchanged); } } nodes.addAll(generatedEndpoints); } protected void buildReportSteps(SortedSet<ExplainLogEntry> logs) { SortedSetMultimap<DateTime, ExplainLogEntry> logsByDate = getEntriesGroupsByDateAndSortedBySequenceNumber(logs); for (DateTime date : logsByDate.keySet()) { ExplainStep step = new ExplainStep(logsByDate.get(date), originNodes, fromOutside, toOutside); originNodes = step.getNewOriginNodes(); nodes.addAll(step.getNewNodes()); edges.addAll(step.getNewEdges()); } } private AfterElimination tryEliminateStockCreator(Collection<ExplainLogEntry> entriesToAdd) { ImmutableList.Builder<Node> createdOriginNodes = ImmutableList.builder(); Builder<ExplainLogEntry> filteredLogs = ImmutableSortedSet.naturalOrder(); for (ExplainLogEntry entry : entriesToAdd) { if (entry.isFromStockCreator()) { for (ExplainArrow arrow : entry.getArrows()) { if (arrow.getCount() > 0) { createdOriginNodes.add(new OriginNode(arrow.getTo(), 0, arrow.getCount())); } } } else { filteredLogs.add(entry); } } return new AfterElimination(filteredLogs.build(), createdOriginNodes.build()); } static class AfterElimination { SortedSet<ExplainLogEntry> remainingLogs; List<Node> originNodes; AfterElimination(SortedSet<ExplainLogEntry> remainingLogs, List<Node> originNodes) { this.remainingLogs = remainingLogs; this.originNodes = originNodes; } } private SortedSetMultimap<DateTime, ExplainLogEntry> getEntriesGroupsByDateAndSortedBySequenceNumber(Collection<ExplainLogEntry> logs) { SortedSetMultimap<DateTime, ExplainLogEntry> logsByDate = TreeMultimap.<DateTime, ExplainLogEntry> create(new Comparator<DateTime>() { @Override public int compare(DateTime o1, DateTime o2) { return o1.compareTo(o2); } }, new Comparator<ExplainLogEntry>() { @Override public int compare(ExplainLogEntry o1, ExplainLogEntry o2) { return o1.getSequenceNumber().compareTo(o2.getSequenceNumber()); } }); for (ExplainLogEntry log : logs) { logsByDate.put(log.getDate(), log); } return logsByDate; } }
true
53562027ef831ca9c445fa1cde014fcab370fa34
Java
AnkitTechCreator/data-structure-and-algorithm
/DataStructures/src/my/practice/searchingandsorting/SelectionSort.java
UTF-8
477
3.40625
3
[]
no_license
package my.practice.searchingandsorting; public class SelectionSort { public static void main(String[] args) { int arr[] = {10,7,2,6,12}; for (int i = 0; i < arr.length-1; i++) { int min = i; for (int j = i+1; j < arr.length; j++) { if(arr[j]<arr[min]){ min = j; } } int temp = arr[i]; arr[i] = arr[min]; arr[min] = temp; } for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } } }
true
b2751c44b4e16d9b9fc8d6757428d96e490112b2
Java
passion1014/metaworks_framework
/core/broadleaf-framework/src/main/java/org/broadleafcommerce/core/pricing/service/workflow/AutoBundleActivity.java
UTF-8
17,558
1.960938
2
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
/* * #%L * BroadleafCommerce Framework * %% * Copyright (C) 2009 - 2013 Broadleaf Commerce * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package org.broadleafcommerce.core.pricing.service.workflow; import org.broadleafcommerce.core.catalog.domain.ProductBundle; import org.broadleafcommerce.core.catalog.domain.SkuBundleItem; import org.broadleafcommerce.core.catalog.service.CatalogService; import org.broadleafcommerce.core.order.dao.FulfillmentGroupItemDao; import org.broadleafcommerce.core.order.dao.OrderItemDao; import org.broadleafcommerce.core.order.domain.BundleOrderItem; import org.broadleafcommerce.core.order.domain.DiscreteOrderItem; import org.broadleafcommerce.core.order.domain.FulfillmentGroup; import org.broadleafcommerce.core.order.domain.FulfillmentGroupItem; import org.broadleafcommerce.core.order.domain.Order; import org.broadleafcommerce.core.order.domain.OrderItem; import org.broadleafcommerce.core.order.service.OrderService; import org.broadleafcommerce.core.order.service.exception.ItemNotFoundException; import org.broadleafcommerce.core.order.service.exception.RemoveFromCartException; import org.broadleafcommerce.core.order.service.type.OrderItemType; import org.broadleafcommerce.core.pricing.service.exception.PricingException; import org.broadleafcommerce.core.workflow.BaseActivity; import org.broadleafcommerce.core.workflow.ProcessContext; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Resource; /** * This pricing workflow step will automatically bundle items in the cart. * * For example, if a ProductBundle exists of two items and the user has * one of the items in their cart. If they then add the second item, * this activity will replace the two items with the ProductBundle. * * This only occurs if the ProductBundle is set to "automatically" bundle. * */ public class AutoBundleActivity extends BaseActivity<ProcessContext<Order>> { @Resource(name="blCatalogService") protected CatalogService catalogService; @Resource(name="blOrderService") protected OrderService orderService; @Resource(name="blOrderItemDao") protected OrderItemDao orderItemDao; @Resource(name="blFulfillmentGroupItemDao") protected FulfillmentGroupItemDao fulfillmentGroupItemDao; public ProcessContext<Order> execute(ProcessContext<Order> context) throws Exception { Order order = context.getSeedData(); order = handleAutomaticBundling(order); context.setSeedData(order); return context; } public Order handleAutomaticBundling(Order order) throws PricingException, RemoveFromCartException { boolean itemsHaveBeenUnbundled = false; List<DiscreteOrderItem> unbundledItems = null; List<ProductBundle> productBundles = catalogService.findAutomaticProductBundles(); Set<Long> processedBundleIds = new HashSet<Long>(); for (ProductBundle productBundle : productBundles) { int existingUses = countExistingUsesOfBundle(order, productBundle); Integer maxApplications = null; for (SkuBundleItem skuBundleItem : productBundle.getSkuBundleItems()) { int maxSkuApplications = countMaximumApplications(order, skuBundleItem, processedBundleIds); if (maxApplications == null || maxApplications > maxSkuApplications) { maxApplications = maxSkuApplications; } } processedBundleIds.add(productBundle.getId()); if (maxApplications != existingUses) { if (! itemsHaveBeenUnbundled) { // Store the discrete items that were part of automatic bundles unbundledItems = unBundleItems(order); order = removeAutomaticBundles(order); itemsHaveBeenUnbundled = true; } // Create a new bundle with maxApplication occurrences order = bundleItems(order, productBundle, maxApplications, unbundledItems); } } return order; } /** * Removes all automatic bundles from the order and replaces with DiscreteOrderItems. * * @param order * @throws PricingException */ private Order removeAutomaticBundles(Order order) throws PricingException { List<BundleOrderItem> bundlesToRemove = new ArrayList<BundleOrderItem>(); for (OrderItem orderItem : order.getOrderItems()) { if (orderItem instanceof BundleOrderItem) { BundleOrderItem bundleOrderItem = (BundleOrderItem) orderItem; if (bundleOrderItem.getProductBundle() != null && bundleOrderItem.getProductBundle().getAutoBundle()) { bundlesToRemove.add(bundleOrderItem); } } } for (BundleOrderItem bundleOrderItem : bundlesToRemove) { try { order = orderService.removeItem(order.getId(), bundleOrderItem.getId(), false); } catch (RemoveFromCartException e) { throw new PricingException("Could not remove item", e); } } return order; } /** * Removes all automatic bundles from the order and replaces with DiscreteOrderItems. * * @param order */ private List<DiscreteOrderItem> unBundleItems(Order order) throws PricingException{ List<DiscreteOrderItem> unbundledItems = null; for (OrderItem orderItem : order.getOrderItems()) { if (orderItem instanceof BundleOrderItem) { BundleOrderItem bundleOrderItem = (BundleOrderItem) orderItem; if (bundleOrderItem.getProductBundle() != null && bundleOrderItem.getProductBundle().getAutoBundle()) { if (unbundledItems == null) { unbundledItems = new ArrayList<DiscreteOrderItem>(); } for(DiscreteOrderItem item : bundleOrderItem.getDiscreteOrderItems()) { DiscreteOrderItem newOrderItem = (DiscreteOrderItem) item.clone(); newOrderItem.setQuantity(item.getQuantity() * bundleOrderItem.getQuantity()); newOrderItem.setSkuBundleItem(null); newOrderItem.setBundleOrderItem(null); newOrderItem.updateSaleAndRetailPrices(); newOrderItem.setOrder(order); unbundledItems.add(newOrderItem); } } } } return unbundledItems; } /** * Builds a BundleOrderItem based on the passed in productBundle. Creates new DiscreteOrderItems. * Removes the existing matching DiscreteOrderItems or modifies the quantity if needed. * * @param order * @param productBundle * @param numApplications * @throws PricingException * @throws ItemNotFoundException */ private Order bundleItems(Order order, ProductBundle productBundle, Integer numApplications, List<DiscreteOrderItem> unbundledItems) throws PricingException, RemoveFromCartException { BundleOrderItem bundleOrderItem = (BundleOrderItem) orderItemDao.create(OrderItemType.BUNDLE); bundleOrderItem.setQuantity(numApplications); bundleOrderItem.setCategory(productBundle.getDefaultCategory()); bundleOrderItem.setSku(productBundle.getDefaultSku()); bundleOrderItem.setName(productBundle.getName()); bundleOrderItem.setProductBundle(productBundle); bundleOrderItem.setOrder(order); // make a copy of the fulfillment group items since they will be deleted when the order items are removed Map<Long, FulfillmentGroupItem> skuIdFulfillmentGroupMap = new HashMap<Long, FulfillmentGroupItem>(); for (FulfillmentGroup fulfillmentGroup : order.getFulfillmentGroups()) { for (FulfillmentGroupItem fulfillmentGroupItem : fulfillmentGroup.getFulfillmentGroupItems()) { if (fulfillmentGroupItem.getOrderItem() instanceof DiscreteOrderItem) { DiscreteOrderItem discreteOrderItem = (DiscreteOrderItem) fulfillmentGroupItem.getOrderItem(); skuIdFulfillmentGroupMap.put(discreteOrderItem.getSku().getId(), fulfillmentGroupItem); } } } for (SkuBundleItem skuBundleItem : productBundle.getSkuBundleItems()) { List<DiscreteOrderItem> itemMatches = new ArrayList<DiscreteOrderItem>(); int skuMatches = populateItemMatchesForSku(itemMatches, order, unbundledItems, skuBundleItem.getSku().getId()); int skusRequired = skuBundleItem.getQuantity()* numApplications; if (skuMatches < skusRequired) { throw new IllegalArgumentException("Something went wrong creating automatic bundles. Not enough skus to fulfill bundle requirements for sku id: " + skuBundleItem.getSku().getId()); } // remove-all-items from order // this call also deletes any fulfillment group items that are associated with that order item for (DiscreteOrderItem item : itemMatches) { order = orderService.removeItem(order.getId(), item.getId(), false); } DiscreteOrderItem baseItem = null; if (itemMatches.size() > 0) { baseItem = itemMatches.get(0); } else { for (DiscreteOrderItem discreteOrderItem : unbundledItems) { if (discreteOrderItem.getSku().getId().equals(skuBundleItem.getSku().getId())) { baseItem = discreteOrderItem; } } } // Add item to the skuBundle DiscreteOrderItem newSkuBundleItem = (DiscreteOrderItem) baseItem.clone(); newSkuBundleItem.setSkuBundleItem(skuBundleItem); newSkuBundleItem.setBundleOrderItem(bundleOrderItem); newSkuBundleItem.setQuantity(skuBundleItem.getQuantity()); newSkuBundleItem.setOrder(null); bundleOrderItem.getDiscreteOrderItems().add(newSkuBundleItem); if (skuMatches > skusRequired) { // Add a non-bundled item to the order with the remaining sku count. DiscreteOrderItem newOrderItem = (DiscreteOrderItem) baseItem.clone(); newOrderItem.setBundleOrderItem(null); newOrderItem.setSkuBundleItem(null); newOrderItem.setQuantity(skuMatches - skusRequired); newOrderItem = (DiscreteOrderItem) orderItemDao.save(newOrderItem); newOrderItem.setOrder(order); newOrderItem.updateSaleAndRetailPrices(); // Re-associate fulfillment group item to newOrderItem FulfillmentGroupItem fulfillmentGroupItem = skuIdFulfillmentGroupMap.get(newSkuBundleItem.getSku().getId()); if (fulfillmentGroupItem != null) { FulfillmentGroupItem newFulfillmentGroupItem = fulfillmentGroupItem.clone(); newFulfillmentGroupItem.setOrderItem(newOrderItem); newFulfillmentGroupItem.setQuantity(newOrderItem.getQuantity()); newFulfillmentGroupItem = fulfillmentGroupItemDao.save(newFulfillmentGroupItem); //In case this activity is run inside a transaction, we need to set the relationships on the order directly //these associations may have not been committed yet. This order is used in other activities and will not be reloaded if in a transaction. for (FulfillmentGroup fg : order.getFulfillmentGroups()) { if (newFulfillmentGroupItem.getFulfillmentGroup() != null && fg.getId().equals(newFulfillmentGroupItem.getFulfillmentGroup().getId())) { fg.addFulfillmentGroupItem(newFulfillmentGroupItem); } } } order.getOrderItems().add(newOrderItem); } } bundleOrderItem.updateSaleAndRetailPrices(); order.getOrderItems().add(bundleOrderItem); order = orderService.save(order, false); for (OrderItem orderItem : order.getOrderItems()) { if (orderItem instanceof BundleOrderItem) { BundleOrderItem bundleItem = (BundleOrderItem) orderItem; for (DiscreteOrderItem discreteOrderItem : bundleItem.getDiscreteOrderItems()) { // Re-associate fulfillment group item to newly created skuBundles FulfillmentGroupItem fulfillmentGroupItem = skuIdFulfillmentGroupMap.get(discreteOrderItem.getSku().getId()); if (fulfillmentGroupItem != null) { FulfillmentGroupItem newFulfillmentGroupItem = fulfillmentGroupItem.clone(); newFulfillmentGroupItem.setOrderItem(discreteOrderItem); newFulfillmentGroupItem.setQuantity(discreteOrderItem.getQuantity()); //In case this activity is run inside a transaction, we need to set the relationships on the order directly //these associations may have not been committed yet. This order is used in other activities and will not be reloaded if in a transaction. for (FulfillmentGroup fg : order.getFulfillmentGroups()) { if (newFulfillmentGroupItem.getFulfillmentGroup() != null && fg.getId().equals(newFulfillmentGroupItem.getFulfillmentGroup().getId())) { fg.addFulfillmentGroupItem(newFulfillmentGroupItem); } } } } } } //reload order with new fulfillment group items order = orderService.save(order, false); return order; } protected int countExistingUsesOfBundle(Order order, ProductBundle bundle) { int existingUses=0; for (OrderItem orderItem : order.getOrderItems()) { if (orderItem instanceof BundleOrderItem) { BundleOrderItem bundleOrderItem = (BundleOrderItem) orderItem; if (bundleOrderItem.getProductBundle() != null) { if (bundleOrderItem.getProductBundle().getId().equals(bundle.getId())) { existingUses = existingUses+1; } } } } return existingUses; } protected int populateItemMatchesForSku(List<DiscreteOrderItem> matchingItems, Order order, List<DiscreteOrderItem> unbundledItems, Long skuId) { int skuMatches = 0; for (OrderItem orderItem : order.getOrderItems()) { if (orderItem instanceof DiscreteOrderItem) { DiscreteOrderItem item = (DiscreteOrderItem) orderItem; if (skuId.equals(item.getSku().getId())) { matchingItems.add(item); skuMatches = skuMatches + item.getQuantity(); } } } if (unbundledItems != null) { for (DiscreteOrderItem discreteOrderItem : unbundledItems) { if (skuId.equals(discreteOrderItem.getSku().getId())) { skuMatches = skuMatches + discreteOrderItem.getQuantity(); } } } return skuMatches; } protected int countMaximumApplications(Order order, SkuBundleItem skuBundleItem, Set<Long> processedBundles) { int skuMatches = 0; Long skuId = skuBundleItem.getSku().getId(); for (OrderItem orderItem : order.getOrderItems()) { if (orderItem instanceof DiscreteOrderItem) { DiscreteOrderItem item = (DiscreteOrderItem) orderItem; if (skuId.equals(item.getSku().getId())) { skuMatches = skuMatches + item.getQuantity(); } } else if (orderItem instanceof BundleOrderItem) { BundleOrderItem bundleItem = (BundleOrderItem) orderItem; if (bundleItem.getProductBundle() != null && bundleItem.getProductBundle().getAutoBundle()) { if (! processedBundles.contains(bundleItem.getId())) { for(DiscreteOrderItem discreteItem : bundleItem.getDiscreteOrderItems()) { if (skuId.equals(discreteItem.getSku().getId())) { skuMatches = skuMatches + (discreteItem.getQuantity() * bundleItem.getQuantity()); } } } } } } return skuMatches / skuBundleItem.getQuantity(); } }
true
5b1d1cc4fef6b4f51db0bde3e34ecc99e020b98a
Java
ferustigris/animals-buzzle
/app/src/main/java/ferus/tigris/buzzles/views/CommonStatisticView.java
UTF-8
1,135
2.421875
2
[]
no_license
package ferus.tigris.buzzles.views; import ferus.tigris.buzzles.GameManager; import ferus.tigris.buzzles.Builders.ImagesPool; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Point; public class CommonStatisticView implements AbstractView { private GameManager gameManager; Bitmap progress; Bitmap progress_back; public CommonStatisticView(GameManager gameManager) { this.gameManager = gameManager; progress = ImagesPool.instance(gameManager.view()).getCloud(); progress_back = ImagesPool.instance(gameManager.view()).getTransporentCloud(); } public void draw(Canvas canvas) { int width = gameManager.view().getWidth(); int x = 0; while(x + progress_back.getWidth() < width) { canvas.drawBitmap(progress_back, x, 0, null); x += progress_back.getWidth(); } x = 0; while(x < width*getScaleFactor()) { canvas.drawBitmap(progress, x, 0, null); x += progress.getWidth(); } } protected double getScaleFactor() { return gameManager.levelScope(); } public void setPosition(Point position) {} public void setRealSpriteWidth(int px) {} }
true
ef053199a96e5cd95ce29c1389ae5e17f8242a6a
Java
Abdullah1299/BudgetSmart
/app/src/main/java/com/heather/eagle/budgetsmart/MainActivity.java
UTF-8
15,469
1.882813
2
[]
no_license
package com.heather.eagle.budgetsmart; import android.animation.ValueAnimator; import android.content.ClipData; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.preference.PreferenceManager; import android.support.design.widget.NavigationView; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import org.apache.commons.lang3.ArrayUtils; public class MainActivity extends AppCompatActivity { public static final String MYPREFS = "myprefs"; private static final String LOG_TAG = "budgetSmart"; public static int initBudget = 500; public static int budgetEverSetChecker = 1; public static TextView budgetCounter; public static String name; public static String cost; // later may want to deal with as double? public static String status; private ListView mDrawerList; private ArrayAdapter<String> mAdapter; private ActionBarDrawerToggle mDrawerToggle; private DrawerLayout mDrawerLayout; private String mActivityTitle; NavigationView navigation; AppInfo appInfo; ListView lv; private MyAdapter aa; final static ArrayList<ListElement> itemList = new ArrayList<ListElement>(); private class ListElement { ListElement() {}; ListElement(String name, String cost, String status, String category) { this.name = name; this.cost = cost; this.status = status; this.category = category; } public String name; public String cost; public String status; public String category; public String getName() { return name; } public String getCost() { return cost; } public String getStatus() { return status; } public String getCateg() { return category; } } private class MyAdapter extends ArrayAdapter<ListElement> { int resource; Context context; public MyAdapter(Context _context, int _resource, List<ListElement> items) { super(_context, _resource, items); resource = _resource; context = _context; } @Override public View getView(int position, View convertView, ViewGroup parent) { LinearLayout newView; ListElement w = getItem(position); // Inflate a new view if necessary. if (convertView == null) { newView = new LinearLayout(getContext()); LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); vi.inflate(resource, newView, true); } else { newView = (LinearLayout) convertView; } // Fills in the view. TextView tn = (TextView) newView.findViewById(R.id.itemName); TextView tc = (TextView) newView.findViewById(R.id.itemCost); Button deleteBtn = (Button) newView.findViewById(R.id.btn_del); tn.setText(w.name); tc.setText("$" + w.cost); // Remove item from list when delete button pressed deleteBtn.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v){ Log.d(LOG_TAG, "delete btn pressed"); final int position = lv.getPositionForView((View) v.getParent()); Log.d(LOG_TAG, "position: " + position); removeElement(position); //decrementCounter(position); //refreshCtr(); notifyDataSetChanged(); } }); return newView; } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); appInfo = AppInfo.getInstance(this); // Set initial budget if(budgetEverSetChecker == 1) { Bundle bundle = getIntent().getExtras(); int budget = Integer.parseInt(bundle.getString("initBudget")); SharedPreferences sp = getSharedPreferences(MYPREFS, 0); SharedPreferences.Editor editor = sp.edit(); //editor.putInt("budget", initBudget); //Log.d(LOG_TAG, "initial budget: " + initBudget); editor.putInt("budget", budget); Log.d(LOG_TAG, "initial budget: " + budget); editor.commit(); budgetEverSetChecker = 0; } // Set and configure navigation drawer mDrawerList = (ListView)findViewById(R.id.navList); mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout); mActivityTitle = getTitle().toString(); addDrawerItems(); setupDrawer(); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); //navigation = (NavigationView) findViewById(R.id.navigation_view); budgetCounter = (TextView) findViewById(R.id.budgetCurrent); lv = (ListView) findViewById(R.id.listView); refreshCtr(); aa = new MyAdapter(this, R.layout.list_element, itemList); //loadPreferences(); lv.setAdapter(aa); aa.notifyDataSetChanged(); } private void addDrawerItems(){ String[] osArray = { "Overview", "Receipts" }; mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, osArray); mDrawerList.setAdapter(mAdapter); mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //Toast.makeText(MainActivity.this, "You're a budgeting star!", Toast.LENGTH_SHORT).show(); Log.d(LOG_TAG, "setOnItemClickListener: position: " + position); switch(position){ case 0: Intent intent = new Intent(MainActivity.this, PieChartActivity.class); startActivity(intent); break; default: break; } } }); } private void setupDrawer(){ mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) { public void onDrawerOpened(View drawerView) { super.onDrawerOpened(drawerView); getSupportActionBar().setTitle("Navigation"); invalidateOptionsMenu(); } public void onDrawerClosed(View view) { super.onDrawerClosed(view); getSupportActionBar().setTitle(mActivityTitle); invalidateOptionsMenu(); } }; mDrawerToggle.setDrawerIndicatorEnabled(true); mDrawerLayout.setDrawerListener(mDrawerToggle); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mDrawerToggle.onConfigurationChanged(newConfig); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); Log.d(LOG_TAG, "nav item id: " + id); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } // Activate the navigation drawer toggle if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } return super.onOptionsItemSelected(item); } @Override protected void onResume(){ super.onResume(); loadPreferences(); } public void getNewItemData() { //intent.putExtra("new item", ); //ArrayList<String> test = getIntent().getStringArrayListExtra("test"); // Irrelevant now since we're using SharedPrefs /* Bundle extras = getIntent().getExtras(); if (getIntent().getStringExtra("Name") != null && getIntent().getStringExtra("Cost") != null){ name = extras.getString("Name"); cost = extras.getString("Cost"); itemList.add(new ListElement(name, cost)); Log.d(LOG_TAG, "getNewItemData: name and cost added from form activity: " + name + cost); for (ListElement item : itemList){ Log.d(LOG_TAG, "item in list: " + item.name + " " + item.cost); } } */ } public void onClickAdd(View v) { // Intent to go to form activity Intent intent = new Intent(this, ItemFormActivity.class); startActivity(intent); } // Refresh budget counter public void refreshCtr() { SharedPreferences sp = getSharedPreferences(MYPREFS, 0); String currentBudget = "$" + sp.getInt("budget", 0); ((TextView)findViewById(R.id.budgetCurrent)).setText(currentBudget); } public void animateCtr(int initVal, int finVal, final TextView tv){ ValueAnimator valAnim = ValueAnimator.ofInt(initVal, finVal); valAnim.setDuration(900); valAnim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener(){ @Override public void onAnimationUpdate(ValueAnimator valAnim){ tv.setText("$" + valAnim.getAnimatedValue().toString()); } }); valAnim.start(); } // Remove from list and memory public void removeElement(int pos){ itemList.remove(pos); SharedPreferences sp = getSharedPreferences(MYPREFS, 0); SharedPreferences.Editor editor = sp.edit(); // Get strings from memory and parse String[] nameWords = sp.getString("name", null).split(","); String[] costWords = sp.getString("cost", null).split(","); String[] statusWords = sp.getString("status", null).split(","); String[] categWords = sp.getString("category", null).split(","); if(nameWords!=null && nameWords.length>0) { // Update budget (increase) int budget = sp.getInt("budget", 0); int budgetNew = budget + Integer.parseInt(costWords[pos]); animateCtr(budget, budgetNew, (TextView)findViewById(R.id.budgetCurrent)); // if(budget < 0){ } Log.d(LOG_TAG, "new budget: " + budgetNew); // Remove chosen item at index pos from array, then reconstruct new string String[] nameNew = ArrayUtils.remove(nameWords, pos); String[] costNew = ArrayUtils.remove(costWords, pos); String[] statusNew = ArrayUtils.remove(statusWords, pos); String[] categNew = ArrayUtils.remove(categWords, pos); Log.d(LOG_TAG, "new arrays: " + Arrays.toString(nameNew) + "\n" + Arrays.toString(costNew) + "\n" + Arrays.toString(statusNew) + "\n" + Arrays.toString(categNew)); StringBuilder bName = new StringBuilder(); StringBuilder bCost = new StringBuilder(); StringBuilder bStatus = new StringBuilder(); StringBuilder bCateg = new StringBuilder(); for (int i = 0; i < nameNew.length; i++) { bName = bName.append(nameNew[i]).append(","); bCost = bCost.append(costNew[i]).append(","); bStatus = bStatus.append(statusNew[i]).append(","); bCateg = bCateg.append(categNew[i]).append(","); } Log.d(LOG_TAG, "stringbuilder test:" + bName.toString() + " " + bCost.toString() + " " + bStatus.toString() + " " + bCateg.toString()); // Update to memory editor.clear(); editor.putString("name", bName.toString()); editor.putString("cost", bCost.toString()); editor.putString("status", bStatus.toString()); editor.putString("category", bCateg.toString()); editor.putInt("old_budget", budget); editor.putInt("budget", budgetNew); editor.commit(); } //decrementCounter(pos); } // Repopulate list protected void loadPreferences(){ itemList.clear(); SharedPreferences sp = getSharedPreferences(MYPREFS, 0); //TextView tv = (TextView)findViewById(R.id.budgetCurrent); String listData = sp.getString("name", null); String listData2 = sp.getString("cost", null); String listData3 = sp.getString("status", null); String listData4 = sp.getString("category", null); Log.d(LOG_TAG, "loadPrefs: listData listData2: " + listData + " " + listData2 + " " + listData3); Log.d(LOG_TAG, "loadPrefs: listData4: " + listData4); refreshCtr(); // Parse strings if(listData !=null && listData2 != null && listData3 != null && listData4 != null){ //animateCtr(sp.getInt("old_budget", 0), sp.getInt("budget", 0), tv); String[] nameWords = listData.split(","); String[] costWords = listData2.split(","); String[] statusWords = listData3.split(","); String[] categWords = listData4.split(","); // Split returns at least one element so need to prevent showing empty string if(nameWords[0].equals("")) return; for (int k=0; k<nameWords.length; k++){ Log.d(LOG_TAG, "item/cost array: " + nameWords[k] + " " + costWords[k] ); } // Add item to list for(int i=0; i<nameWords.length; i++){ aa.add(new ListElement(nameWords[i], costWords[i], statusWords[i], categWords[i])); } for (ListElement item : itemList){ Log.d(LOG_TAG, "inCurrentList: " + item.name + " " + item.cost + " " + item.status + " " + item.category); Log.d(LOG_TAG, "itemList size: " + itemList.size()); } } aa.notifyDataSetChanged(); } }
true
4c6058f6ef4d4c50a619373f392402c7ecc5dd2c
Java
fansmigo/cloud-demo
/cloud-consumer/src/test/java/com/cloud/cloudconsumer/hystrix/MyCommand.java
UTF-8
811
2.515625
3
[]
no_license
package com.cloud.cloudconsumer.hystrix; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; /** * 共用命令类,用于测试线程隔离与信号量隔离两个策略 */ public class MyCommand extends HystrixCommand<String> { int index; private String key; public MyCommand(int index){ super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("ExampleGroup"))); } @Override protected String run() throws Exception { Thread.sleep(500); System.out.println("执行方法,当前索引:" + index); return ""; } @Override protected String getFallback(){ System.out.println("执行 fallback ,当前索引:" + index); return ""; } @Override protected String getCacheKey(){ return this.key; } }
true
a447e32da1beccf11655cdaecd4265673c96a182
Java
Mi-Walkie-Talkie-by-Darkhorse/Mi-Walkie-Talkie-Plus
/original-java/com/ifengyu/intercom/ui/map/GoogleMapDownloadDefinitionActivity.java
UTF-8
11,894
1.546875
2
[]
no_license
package com.ifengyu.intercom.ui.map; import android.content.Context; import android.content.DialogInterface; import android.os.Bundle; import android.os.Parcelable; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.view.View.OnClickListener; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import com.google.devtools.build.android.desugar.runtime.ThrowableExtension; import com.google.zxing.common.StringUtils; import com.ifengyu.intercom.R; import com.ifengyu.intercom.b.ad; import com.ifengyu.intercom.b.v; import com.ifengyu.intercom.greendao.dao.a.C0024a; import com.ifengyu.intercom.greendao.dao.b; import com.ifengyu.intercom.ui.baseui.BaseActivity; import com.ifengyu.intercom.ui.map.d.a.a; import com.ifengyu.intercom.ui.widget.dialog.d; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Iterator; import org.osmdroid.util.GeoPoint; public class GoogleMapDownloadDefinitionActivity extends BaseActivity implements OnClickListener { /* access modifiers changed from: private */ public int[] A = new int[3]; /* access modifiers changed from: private */ public String[] B = new String[3]; private ArrayList<String> C; /* access modifiers changed from: private */ public View D; /* access modifiers changed from: private */ public String E; /* access modifiers changed from: private */ public int F = 30; /* access modifiers changed from: private */ public EditText a; private TextView b; private TextView c; /* access modifiers changed from: private */ public GeoPoint[] d; private CheckBox[] q = new CheckBox[3]; /* access modifiers changed from: private */ public C0024a r; /* access modifiers changed from: private */ public b s; private final int t = 0; private final int u = 1; private final int v = 2; private final int w = 18; private final int x = 17; private final int y = 16; /* access modifiers changed from: private */ public int z = 1; /* access modifiers changed from: protected */ public void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView((int) R.layout.activity_map_download_select); c(); this.a = (EditText) c(R.id.offmap_name); this.a.setSelection(this.a.getText().length()); this.q[0] = (CheckBox) c(R.id.high_check); this.q[1] = (CheckBox) c(R.id.medium_check); this.q[2] = (CheckBox) c(R.id.low_check); Parcelable[] parcelableArrayExtra = getIntent().getParcelableArrayExtra("intent_init_points"); this.C = getIntent().getStringArrayListExtra("off_map_downloaded_names"); this.d = new GeoPoint[parcelableArrayExtra.length]; if (this.d != null) { for (int i = 0; i < this.d.length; i++) { this.d[i] = (GeoPoint) parcelableArrayExtra[i]; } d(); this.D = findViewById(R.id.delete_text_btn); this.D.setOnClickListener(this); if (this.a.getText().toString().trim().length() == 0) { this.D.setVisibility(8); } else { this.D.setVisibility(0); } this.a.addTextChangedListener(new TextWatcher() { private CharSequence b; private int c; private int d; public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { this.b = charSequence; } public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { } public void afterTextChanged(Editable editable) { try { if (GoogleMapDownloadDefinitionActivity.this.a.getText().toString().trim().length() == 0) { GoogleMapDownloadDefinitionActivity.this.D.setVisibility(8); } else { GoogleMapDownloadDefinitionActivity.this.D.setVisibility(0); } this.c = GoogleMapDownloadDefinitionActivity.this.a.getSelectionStart(); this.d = GoogleMapDownloadDefinitionActivity.this.a.getSelectionEnd(); if (GoogleMapDownloadDefinitionActivity.this.a.getText().toString().length() > 0 && this.b.toString().getBytes(StringUtils.GB2312).length > GoogleMapDownloadDefinitionActivity.this.F) { editable.delete(this.c - 1, this.d); GoogleMapDownloadDefinitionActivity.this.a.setText(editable); GoogleMapDownloadDefinitionActivity.this.a.setSelection(editable.length()); } } catch (UnsupportedEncodingException e) { ThrowableExtension.printStackTrace(e); } } }); findViewById(R.id.low_click).setOnClickListener(this); findViewById(R.id.medium_click).setOnClickListener(this); findViewById(R.id.high_click).setOnClickListener(this); for (CheckBox onClickListener : this.q) { onClickListener.setOnClickListener(this); } ((TextView) c(R.id.high_size)).setText(this.B[0]); ((TextView) c(R.id.medium_size)).setText(this.B[1]); ((TextView) c(R.id.low_size)).setText(this.B[2]); } } private void c() { c_(); this.b = (TextView) c(R.id.title_bar_title); this.c = (TextView) c(R.id.title_bar_confirm); this.b.setText(getText(R.string.selcte_download_map)); this.c.setVisibility(0); this.c.setOnClickListener(this); } private void d() { for (int i = 18; i >= 12; i--) { int[] iArr = this.A; iArr[0] = iArr[0] + a.a(this.d[0], this.d[1], i).length; } for (int i2 = 17; i2 >= 12; i2--) { int[] iArr2 = this.A; iArr2[1] = iArr2[1] + a.a(this.d[0], this.d[1], i2).length; } for (int i3 = 16; i3 >= 12; i3--) { int[] iArr3 = this.A; iArr3[2] = iArr3[2] + a.a(this.d[0], this.d[1], i3).length; } this.B[0] = MapDataProvider.a().b(this.A[0]); this.B[1] = MapDataProvider.a().b(this.A[1]); this.B[2] = MapDataProvider.a().b(this.A[2]); } public void onClick(View view) { switch (view.getId()) { case R.id.delete_text_btn /*2131755259*/: this.a.setText(""); return; case R.id.high_click /*2131755260*/: case R.id.high_check /*2131755261*/: this.z = 0; a(this.q[0]); return; case R.id.medium_click /*2131755263*/: case R.id.medium_check /*2131755264*/: this.z = 1; a(this.q[1]); return; case R.id.low_click /*2131755266*/: case R.id.low_check /*2131755267*/: this.z = 2; a(this.q[2]); return; case R.id.title_bar_confirm /*2131755836*/: if (!v.a((Context) this)) { v.a((CharSequence) getString(R.string.net_error_please_check), false); return; } this.E = this.a.getText().toString().trim(); if (this.E.length() == 0) { v.a(getResources().getText(R.string.please_complete_info), false); return; } Iterator it = this.C.iterator(); while (it.hasNext()) { if (this.E.equals((String) it.next())) { v.a((CharSequence) ad.a((int) R.string.toast_the_name_is_duplicate), false); return; } } if (!v.h(this.E)) { v.a((CharSequence) ad.a((int) R.string.toast_contains_invalid_characters), false); return; } this.r = new C0024a(this, "mitalki_db", null); this.s = new com.ifengyu.intercom.greendao.dao.a(this.r.getWritableDatabase()).newSession(); if (v.b((Context) this)) { Double valueOf = Double.valueOf(this.d[0].getLatitude()); Double valueOf2 = Double.valueOf(this.d[0].getLongitude()); Double valueOf3 = Double.valueOf(this.d[1].getLatitude()); Double valueOf4 = Double.valueOf(this.d[1].getLongitude()); int i = this.z == 0 ? 18 : this.z == 2 ? 16 : 17; this.s.b().insert(new com.ifengyu.intercom.greendao.bean.a(null, valueOf, valueOf2, valueOf3, valueOf4, Integer.valueOf(i), Integer.valueOf(this.A[this.z]), Integer.valueOf(0), Integer.valueOf(0), this.B[this.z], this.E, Integer.valueOf(0), Boolean.valueOf(true))); this.s.a(); this.r.close(); setResult(1); finish(); return; } new d(this).b((CharSequence) ad.a((int) R.string.dialog_network_note)).a((int) R.string.common_cancel, (DialogInterface.OnClickListener) null).b((int) R.string.sure, (DialogInterface.OnClickListener) new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialogInterface, int i) { Double valueOf = Double.valueOf(GoogleMapDownloadDefinitionActivity.this.d[0].getLatitude()); Double valueOf2 = Double.valueOf(GoogleMapDownloadDefinitionActivity.this.d[0].getLongitude()); Double valueOf3 = Double.valueOf(GoogleMapDownloadDefinitionActivity.this.d[1].getLatitude()); Double valueOf4 = Double.valueOf(GoogleMapDownloadDefinitionActivity.this.d[1].getLongitude()); int i2 = GoogleMapDownloadDefinitionActivity.this.z == 0 ? 18 : GoogleMapDownloadDefinitionActivity.this.z == 2 ? 16 : 17; GoogleMapDownloadDefinitionActivity.this.s.b().insert(new com.ifengyu.intercom.greendao.bean.a(null, valueOf, valueOf2, valueOf3, valueOf4, Integer.valueOf(i2), Integer.valueOf(GoogleMapDownloadDefinitionActivity.this.A[GoogleMapDownloadDefinitionActivity.this.z]), Integer.valueOf(0), Integer.valueOf(0), GoogleMapDownloadDefinitionActivity.this.B[GoogleMapDownloadDefinitionActivity.this.z], GoogleMapDownloadDefinitionActivity.this.E, Integer.valueOf(0), Boolean.valueOf(true))); GoogleMapDownloadDefinitionActivity.this.s.a(); GoogleMapDownloadDefinitionActivity.this.r.close(); GoogleMapDownloadDefinitionActivity.this.setResult(1); GoogleMapDownloadDefinitionActivity.this.finish(); } }).b().c(); return; default: return; } } /* access modifiers changed from: protected */ public void onDestroy() { super.onDestroy(); } private void a(CheckBox checkBox) { CheckBox[] checkBoxArr; for (CheckBox checkBox2 : this.q) { checkBox2.setChecked(checkBox.equals(checkBox2)); } } /* access modifiers changed from: protected */ public void c_() { this.g = (ImageView) c(R.id.title_bar_left); this.g.setOnClickListener(new OnClickListener() { public void onClick(View view) { GoogleMapDownloadDefinitionActivity.this.finish(); } }); } }
true
9f17fbda1e2f88330bb1a906873dd66ed284b984
Java
ArgDS/ge
/impl/common-impl/src/main/java/ru/argds/app/test/FileMessage.java
UTF-8
1,637
2.96875
3
[]
no_license
package ru.argds.app.test; import java.util.Objects; public class FileMessage implements Comparable<FileMessage>{ private int priority; private long order; private String pathFileName; public static FileMessage createInstance(int priority, long order, String pathFileName){ return new FileMessage(priority, order, pathFileName); } private FileMessage(int priority, long order, String pathFileName) { this.priority = priority; this.order = order; this.pathFileName = pathFileName; } @Override public int compareTo(FileMessage o) { return this.priority == o.priority ? Long.compare(this.order, o.order) : Integer.compare(o.priority, this.priority); } public int getPriority() { return priority; } public long getOrder() { return order; } public String getPathFileName() { return pathFileName; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FileMessage that = (FileMessage) o; return priority == that.priority && order == that.order && Objects.equals(pathFileName, that.pathFileName); } @Override public int hashCode() { return Objects.hash(priority, order, pathFileName); } @Override public String toString() { return "FileMessage{" + "priority=" + priority + ", order=" + order + ", pathFileName='" + pathFileName + '\'' + '}'; } }
true
8a18ae4ac528de4237ee39a8046b6617e676490e
Java
yearsyan/Harmony-OS-Java-class-library
/src/main/java/ohos/media/camera/params/FaceLandmark.java
UTF-8
1,210
2.703125
3
[]
no_license
package ohos.media.camera.params; import java.util.Objects; import ohos.agp.utils.Point; public final class FaceLandmark { private final Point position; private final int type; public @interface FaceLandmarkType { public static final int LEFT_EYE = 0; public static final int MOUTH_CENTER = 2; public static final int RIGHT_EYE = 1; public static final int TYPE_UNKNOWN = -1; } public FaceLandmark(@FaceLandmarkType int i, Point point) { this.type = i; this.position = point; } @FaceLandmarkType public int getType() { return this.type; } public Point getPosition() { return this.position; } public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof FaceLandmark)) { return false; } FaceLandmark faceLandmark = (FaceLandmark) obj; return this.type == faceLandmark.type && Objects.equals(this.position, faceLandmark.position); } public int hashCode() { return Objects.hash(Integer.valueOf(this.type), this.position); } }
true
639514d6bd192e9b049dbbd8faf4ab3c765edf59
Java
JavaGeoKa/rtempo
/src/main/java/com/geo/bot/DataStarter.java
UTF-8
880
2.28125
2
[]
no_license
package com.geo.bot; import com.geo.dao.PersonRepositoty; import com.geo.model.Person; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @Component public class DataStarter implements CommandLineRunner { // final static Logger log = Logger.getLogger(DataStarter.class); @Autowired PersonRepositoty personRepositoty; public static Map<Long, Person> mapPersons = new ConcurrentHashMap<>(); @Override public void run(String... args) throws Exception { // prepare Persons personRepositoty.findAll().stream().forEach(p -> { mapPersons.put(p.getId(), p); }); System.out.println("Persons in base -> " + mapPersons.size()); } }
true
fe9009b1cdfb028a9a5cfd44fe8d8a1710b58a04
Java
tapson12/Vulgadata
/src/main/java/bf/agriculture/VulgaData/DTO/TypeFormationDTO.java
UTF-8
1,141
2.3125
2
[]
no_license
package bf.agriculture.VulgaData.DTO; import java.util.List; public class TypeFormationDTO { private List<FormationDTO>formationsdto; private int id_formation; private String intitule_formationType; public TypeFormationDTO() { super(); // TODO Auto-generated constructor stub } public TypeFormationDTO(List<FormationDTO> formationsdto, int id_formation, String intitule_formationType) { super(); this.formationsdto = formationsdto; this.id_formation = id_formation; this.intitule_formationType = intitule_formationType; } public List<FormationDTO> getFormationsdto() { return formationsdto; } public void setFormationsdto(List<FormationDTO> formationsdto) { this.formationsdto = formationsdto; } public int getId_formation() { return id_formation; } public void setId_formation(int id_formation) { this.id_formation = id_formation; } public String getIntitule_formationType() { return intitule_formationType; } public void setIntitule_formationType(String intitule_formationType) { this.intitule_formationType = intitule_formationType; } }
true
25ddd8d05e26f67461e00fc51a1bf317d2406e7a
Java
opedisu/CustomerSorter
/src/test/java/CustomerRecordTest.java
UTF-8
830
2.515625
3
[]
no_license
package com.demo.ope; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class CustomerRecordTest { private static CustomerRecord customerRecord; @BeforeClass public static void init() { customerRecord = new CustomerRecord(1, "John Doe", 50.1234, -10.12345); } @Test public void getLatitudeTest() { assertTrue(customerRecord.getLatitude() == 50.1234); } @Test public void getUserIDTest() { assertEquals(customerRecord.getUserID(), 1); } @Test public void getNameTest() { assertEquals(customerRecord.getName(), "John Doe"); } @Test public void getLongitudeTest() { assertTrue(customerRecord.getLongitude() == -10.12345); } }
true
5baa5ad42a3ce41178d282188afea555ae763d4b
Java
LinQingWei/SoundRecorder
/app/src/main/java/cn/way/soundrecorder/ext/IRecordingTimeCalculationExt.java
UTF-8
1,744
2.359375
2
[]
no_license
package cn.way.soundrecorder.ext; import android.media.MediaRecorder; import android.os.Bundle; import android.os.storage.StorageManager; import cn.way.soundrecorder.RemainingTimeCalculator; import cn.way.soundrecorder.service.SoundRecorderService; /** * <pre> * author: Way Lin * date : 2018.04.15 * desc : The Interface to support the customization of recording time calculation. * </pre> */ public interface IRecordingTimeCalculationExt { /** * Called when host app, succeed to init from intent. * Host app need to pass the extras of the intent to this method. * * @param extras the extra of the intent to start SoundRecorder activity. */ public void setExtras(Bundle extras); /** * Called when host app need to create a MediaRecorder object. * The default implementation will just new a MediaRecorder. * The plugin implementation may set extra attribute for this MediaRecorder. * * @return an instance of MediaRecorder object. */ public MediaRecorder getMediaRecorder(); /** * Called when host app need to create a RemainingTimeCalculator object. * The default implementation will just new a RemainingTimeCalculator. * The plugin implementation may return a subclass of RemainingTimeCalculator * to change the behavior of RemainingTimeCalculator * * @param storageManager the reference of StorageManager. * @param service the reference of SoundRecorderService. * @return an instance of RemainingTimeCalculator or its subclass object. */ public RemainingTimeCalculator getRemainingTimeCalculator( StorageManager storageManager, SoundRecorderService service); }
true
50c184e3b3123699678625bafb6d6457055914b9
Java
gitabtion/factory-manager
/app/src/main/java/net/hrsoft/transparent_factory_manager/order/adapter/OrderPagerAdapter.java
UTF-8
2,106
2.421875
2
[]
no_license
package net.hrsoft.transparent_factory_manager.order.adapter; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentPagerAdapter; import net.hrsoft.transparent_factory_manager.order.fragments.OrderContentFragment; /** * @author abtion. * @since 17/8/27 10:17. * email caiheng@hrsoft.net */ public class OrderPagerAdapter extends FragmentPagerAdapter { private String[] mTitles = new String[]{"进行中","未开始","已完成"}; private OrderContentFragment processingOrderFragment; private OrderContentFragment toBeStartOrderFragment; private OrderContentFragment endedOrderFragment; private OrderContentFragment mCurrentFragment; public OrderPagerAdapter(FragmentManager fm) { super(fm); initVariable(); } @Override public Fragment getItem(int position) { switch (position){ case OrderContentFragment.PROCESSING: mCurrentFragment = processingOrderFragment; break; case OrderContentFragment.TO_BE_START: mCurrentFragment = toBeStartOrderFragment; break; case OrderContentFragment.ENDED: mCurrentFragment =endedOrderFragment; break; default: break; } return mCurrentFragment; } @Override public int getCount() { return 3; } /** * 初始化fragment页面 */ private void initVariable(){ if (processingOrderFragment == null){ processingOrderFragment = OrderContentFragment.setType(OrderContentFragment.PROCESSING); } if (toBeStartOrderFragment == null){ toBeStartOrderFragment = OrderContentFragment.setType(OrderContentFragment.TO_BE_START); } if (endedOrderFragment == null){ endedOrderFragment = OrderContentFragment.setType(OrderContentFragment.ENDED); } } @Override public CharSequence getPageTitle(int position) { return mTitles[position]; } }
true
e1359331a8a4950e0b0d8faca3dad894c8982543
Java
hangnew/android_lessons
/mobile74/main/java/com/app/mobile74/MainActivity2.java
UTF-8
3,435
2.3125
2
[]
no_license
package com.app.mobile74; import androidx.annotation.NonNull; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.os.SystemClock; import android.view.View; import android.widget.Button; import android.widget.CalendarView; import android.widget.Chronometer; import android.widget.TimePicker; public class MainActivity2 extends AppCompatActivity { Chronometer chrono; TimePicker timePicker; CalendarView calView; Button b1, b2, b3, b4, b5; String time, date; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main2); chrono = findViewById(R.id.m2Chrono); timePicker = findViewById(R.id.m2Time); timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() { @Override public void onTimeChanged(TimePicker timePicker, int hour, int minute) { time = hour + "시 " + minute + "분"; } }); calView = findViewById(R.id.m2Cal); calView.setOnDateChangeListener(new CalendarView.OnDateChangeListener() { @Override public void onSelectedDayChange(@NonNull CalendarView calendarView, int year, int month, int day) { date = year + "년 " + (month + 1) + "월 " + day + "일"; } }); b1 = findViewById(R.id.m2Button1); b1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { chrono.setBase(SystemClock.elapsedRealtime()); chrono.start(); } }); b2 = findViewById(R.id.m2Button2); b2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { chrono.stop(); chrono.setTextColor(Color.RED); } }); b3 = findViewById(R.id.m2Button3); b3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity2.this); alert.setTitle("선택한 날짜"); alert.setMessage(date); alert.setPositiveButton("닫기", null); alert.show(); } }); b4 = findViewById(R.id.m2Button4); b4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity2.this); alert.setTitle("선택한 시간"); alert.setMessage(time); alert.setPositiveButton("닫기", null); alert.show(); } }); b5 = findViewById(R.id.m2Button5); b5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity2.this, MainActivity3.class); intent.putExtra("time", time); intent.putExtra("date", date); startActivity(intent); } }); } }
true
1c329f90b1ee4c0aa218ffa5e9988cee6d5cd203
Java
YCLlong/spring
/src/main/java/cn/ycl/study/aop/bean/AopBean.java
UTF-8
692
2.5625
3
[]
no_license
package cn.ycl.study.aop.bean; import org.aspectj.lang.annotation.*; import org.springframework.stereotype.Component; @Aspect @Component public class AopBean { private long t; @Pointcut("execution(public void cn.ycl.study.aop.bean.TestAopTarget.sayHello())") public void say(){ } @Before("say()") public void before(){ t = System.currentTimeMillis(); System.out.println("before:" + t); } @After("say()") public void after(){ Long end = System.currentTimeMillis(); t = end - t; System.out.println("after,end =" + end + "间隔:" + t); } @AfterThrowing("say()") public void afterError(){ } }
true
d8991738d588df1d66e4d26e313255577e7c4dd9
Java
game-platform-awaresome/game-sdk
/src/model/CpSettle.java
UTF-8
3,449
1.929688
2
[]
no_license
package model; public class CpSettle implements java.io.Serializable{ /** * cp扣量表 * */ private static final long serialVersionUID = -2040420780977305004L; public Integer id; public String game_id; public String BusinessNo; public String channel; public String packet_id; public String date; public Integer pay; public Integer settlePay; public Integer activateNum; public Integer settleActivateNum; public Integer loginNum; public Integer settleLoginNum; public Integer day1Pay; public Integer settleDay1Pay; public Integer day7Pay; public Integer settleDay7Pay; public Integer dayAllPayAcount; public Integer dayAllAcount; public Integer feeNum; public Integer reqOkNum; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getDayAllAcount() { return dayAllAcount; } public void setDayAllAcount(Integer dayAllAcount) { this.dayAllAcount = dayAllAcount; } public Integer getDayAllPayAcount() { return dayAllPayAcount; } public void setDayAllPayAcount(Integer dayAllPayAcount) { this.dayAllPayAcount = dayAllPayAcount; } public Integer getFeeNum() { return feeNum; } public void setFeeNum(Integer feeNum) { this.feeNum = feeNum; } public Integer getReqOkNum() { return reqOkNum; } public void setReqOkNum(Integer reqOkNum) { this.reqOkNum = reqOkNum; } public String getGameId() { return game_id; } public void setGameId(String game_id) { this.game_id = game_id; } public String getBusinessNo() { return BusinessNo; } public void setBusinessNo(String businessNo) { BusinessNo = businessNo; } public String getChannel() { return channel; } public void setChannel(String channel) { this.channel = channel; } public String getPacketId() { return packet_id; } public void setPacketId(String packet_id) { this.packet_id = packet_id; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public Integer getPay() { return pay; } public void setPay(Integer pay) { this.pay = pay; } public Integer getSettlePay() { return settlePay; } public void setSettlePay(Integer settlePay) { this.settlePay = settlePay; } public Integer getActivateNum() { return activateNum; } public void setActivateNum(Integer activateNum) { this.activateNum = activateNum; } public Integer getSettleActivateNum() { return settleActivateNum; } public void setSettleActivateNum(Integer settleActivateNum) { this.settleActivateNum = settleActivateNum; } public Integer getLoginNum() { return loginNum; } public void setLoginNum(Integer loginNum) { this.loginNum = loginNum; } public Integer getSettleLoginNum() { return settleLoginNum; } public void setSettleLoginNum(Integer settleLoginNum) { this.settleLoginNum = settleLoginNum; } public Integer getDay1Pay() { return day1Pay; } public void setDay1Pay(Integer day1Pay) { this.day1Pay = day1Pay; } public Integer getSettleDay1Pay() { return settleDay1Pay; } public void setSettleDay1Pay(Integer settleDay1Pay) { this.settleDay1Pay = settleDay1Pay; } public Integer getDay7Pay() { return day7Pay; } public void setDay7Pay(Integer day7Pay) { this.day7Pay = day7Pay; } public Integer getSettleDay7Pay() { return settleDay7Pay; } public void setSettleDay7Pay(Integer settleDay7Pay) { this.settleDay7Pay = settleDay7Pay; } }
true
cb052d6a8c5f28ecf8f1666a3f9313aac52feb0d
Java
guihuoliuying/stars
/src/main/java/com/stars/modules/tool/packet/ServerExchangeGift.java
UTF-8
1,034
2.171875
2
[]
no_license
package com.stars.modules.tool.packet; import com.stars.core.player.Player; import com.stars.core.player.PlayerPacket; import com.stars.modules.demologin.packet.ClientText; import com.stars.modules.tool.ToolPacketSet; import com.stars.network.server.buffer.NewByteBuffer; import com.stars.network.server.packet.PacketManager; /** * Created by liuyuheng on 2017/2/10. */ public class ServerExchangeGift extends PlayerPacket { private String activateCode;// 激活码 public static int LENGTH_LIMIT = 13; @Override public void execPacket(Player player) { if(activateCode == null || activateCode.length() < LENGTH_LIMIT){ PacketManager.send(getSession(), new ClientText("请输入正确的兑换码")); return; } } @Override public short getType() { return ToolPacketSet.S_EXCHANGE_GIFT; } @Override public void readFromBuffer(NewByteBuffer buff) { this.activateCode = buff.readString(); } }
true
cbbd953c9902952df0e8b03b4475d8b49d9b5415
Java
zhongxingyu/Seer
/Diff-Raw-Data/9/9_eeb202cc1fde885c5f6e6b898d4953b255450dd0/ResourceProvider/9_eeb202cc1fde885c5f6e6b898d4953b255450dd0_ResourceProvider_s.java
UTF-8
2,272
1.671875
2
[]
no_license
/******************************************************************************* * Copyright (c) 2011 BestSolution.at * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Tom Schindl <tom.schindl@bestsolution.at> - initial API and implementation *******************************************************************************/ package org.eclipse.e4.tools.emf.ui.script.js; import org.eclipse.e4.tools.services.BasicResourceProvider; public class ResourceProvider extends BasicResourceProvider { public static String JAVA_KEYWORD = "COLOR_org.eclipse.e4.tools.emf.ui.script.js.java_keyword"; //$NON-NLS-1$ public static String JAVA_DEFAULT = "COLOR_org.eclipse.e4.tools.emf.ui.script.js.java_default"; //$NON-NLS-1$ public static String JAVA_KEYWORD_RETURN = "COLOR_org.eclipse.e4.tools.emf.ui.script.js.java_keyword_return"; //$NON-NLS-1$ public static String JAVA_OPERATOR = "COLOR_org.eclipse.e4.tools.emf.ui.script.js.java_operator"; //$NON-NLS-1$ public static String JAVA_BRACKET = "COLOR_org.eclipse.e4.tools.emf.ui.script.js.java_bracket"; //$NON-NLS-1$ public static String TASK_TAG = "COLOR_org.eclipse.e4.tools.emf.ui.script.js.java_comment_task_tag"; //$NON-NLS-1$ public static String JAVA_MULTI_LINE_COMMENT = "COLOR_org.eclipse.e4.tools.emf.ui.script.js.java_multi_line_comment"; //$NON-NLS-1$ public static String JAVA_SINGLE_LINE_COMMENT = "COLOR_org.eclipse.e4.tools.emf.ui.script.js.java_single_line_comment"; //$NON-NLS-1$ public static String JAVA_STRING = "COLOR_org.eclipse.e4.tools.emf.ui.script.js.java_string"; //$NON-NLS-1$ public static String JAVADOC_KEYWORD = "COLOR_org.eclipse.e4.tools.emf.ui.script.js.java_doc_keyword"; //$NON-NLS-1$ public static String JAVADOC_TAG = "COLOR_org.eclipse.e4.tools.emf.ui.script.js.java_doc_tag"; //$NON-NLS-1$ public static String JAVADOC_LINK = "COLOR_org.eclipse.e4.tools.emf.ui.script.js.java_doc_link"; //$NON-NLS-1$ public static String JAVADOC_DEFAULT = "COLOR_org.eclipse.e4.tools.emf.ui.script.js.java_doc_default"; //$NON-NLS-1$ }
true
e67ab280ee8f568e1624696ede721a72880bf174
Java
taosut/clean-air-zones-api
/taxi-phv-data/src/it/java/uk/gov/caz/taxiregister/service/CsvTaxiPhvLicenceObjectMapperTestIT.java
UTF-8
9,605
2
2
[]
no_license
package uk.gov.caz.taxiregister.service; import static org.assertj.core.api.BDDAssertions.then; import com.google.common.base.Charsets; import com.google.common.base.Strings; import com.opencsv.ICSVParser; import java.io.ByteArrayInputStream; import java.io.IOException; import org.assertj.core.api.iterable.Extractor; import org.assertj.core.util.Arrays; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import uk.gov.caz.csv.CsvParseExceptionResolver; import uk.gov.caz.csv.model.CsvParseResult; import uk.gov.caz.csv.model.CsvValidationError; import uk.gov.caz.taxiregister.annotation.IntegrationTest; import uk.gov.caz.taxiregister.dto.VehicleDto; import uk.gov.caz.taxiregister.model.registerjob.RegisterJobTrigger; @IntegrationTest class CsvTaxiPhvLicenceObjectMapperTestIT { @Value("${application.validation.max-errors-count}") private int maxErrorsCount; @Autowired private ICSVParser parser; @Autowired private CsvParseExceptionResolver exceptionResolver; private CsvTaxiPhvLicenceObjectMapper csvObjectMapper; @BeforeEach public void setUp() { csvObjectMapper = new CsvTaxiPhvLicenceObjectMapper(parser, exceptionResolver, maxErrorsCount); } @Nested class MaximumErrorCount { @Nested class WhenErrorsCountHasReachedMaxAllowedValue { @Nested class WhenFileHasBeenFullyParsed { @ParameterizedTest @ValueSource(strings = { // error, ok, error "ZC12OMB,2019-04-15,2019-05-17,PHV,abc,def,true$\n" + "ZC22OMB,2019-04-15,2019-05-17,PHV,abc,def,true\n" + "ZC32OMB,2019-04-15,2019-05-17,PHV,abc,def,true$", // error, error "ZC32OMB,2019-04-15,2019-05-17,PHV,abc,def,true$" + "\nZC52OMB,2019-04-15,2019-05-17,PHV,abc,def,true$" }) public void shouldStopParsing(String input) throws IOException { // given int localMaxErrorCount = 2; csvObjectMapper = new CsvTaxiPhvLicenceObjectMapper(parser, exceptionResolver, localMaxErrorCount); // when CsvParseResult<VehicleDto> result = csvObjectMapper.read(toInputStream(input)); // then then(result.getValidationErrors()).hasSize(localMaxErrorCount); } } @Nested class WhenFileHasNotBeenFullyParsed { @ParameterizedTest @ValueSource(strings = { // error, ok, error, ok "ZC12OMB,2019-04-15,2019-05-17,PHV,abc,def,true$\n" + "ZC22OMB,2019-04-15,2019-05-17,PHV,abc,def,true\n" + "ZC32OMB,2019-04-15,2019-05-17,PHV,abc,def,true$\n" + "ZC42OMB,2019-04-15,2019-05-17,PHV,abc,def,true\r\n", // error, error, ok "ZC32OMB,2019-04-15,2019-05-17,PHV,abc,def,true$\n" + "ZC52OMB,2019-04-15,2019-05-17,PHV,abc,def,true$\n" + "ZC42OMB,2019-04-15,2019-05-17,PHV,abc,def,true$\n" }) public void shouldNotIncludeTrailingRowInfoWhenFileHasNotBeenFullyParsed(String input) throws IOException { // given int localMaxErrorCount = 2; csvObjectMapper = new CsvTaxiPhvLicenceObjectMapper(parser, exceptionResolver, localMaxErrorCount); // when CsvParseResult<VehicleDto> result = csvObjectMapper.read(toInputStream(input)); // then then(result.getValidationErrors()) .extracting((Extractor<CsvValidationError, String>) CsvValidationError::getDetail) .noneMatch(detail -> detail.endsWith("Empty row detected")); } } } } @Test public void shouldReadValidCsvData() throws IOException { // given String csvLine = "ZC62OMB,2019-04-15,2019-05-17,PHV,InmxgozMZS,beBCC,true"; // when CsvParseResult<VehicleDto> result = csvObjectMapper.read(toInputStream(csvLine)); // then then(result.getObjects()).containsOnly( VehicleDto.builder() .vrm("ZC62OMB") .start("2019-04-15") .end("2019-05-17") .description("PHV") .licensingAuthorityName("InmxgozMZS") .licensePlateNumber("beBCC") .wheelchairAccessibleVehicle(true) .lineNumber(1) .registerJobTrigger(RegisterJobTrigger.CSV_FROM_S3) .build() ); } @Test public void shouldIgnoreLinesWithExtraValues() throws IOException { // given String csvLine = "ZC62OMB,2019-04-15,2019-05-17,PHV,InmxgozMZS,beBCC,false,extraValue1,extraValue2"; // when CsvParseResult<VehicleDto> result = csvObjectMapper.read(toInputStream(csvLine)); // then then(result.getObjects()).isEmpty(); } @Test public void shouldIgnoreTooLongLines() throws IOException { // given String csvLine = "ZC62OMB,2019-04-15,2019-05-17,PHV,InmxgozMZS" + Strings.repeat("ab", 100); // when CsvParseResult result = csvObjectMapper.read(toInputStream(csvLine)); // then then(result.getObjects()).isEmpty(); } @ParameterizedTest @ValueSource(strings = {" \t", " ", "\t"}) public void shouldIgnoreLinesWithWhitespaces(String csvLine) throws IOException { // when CsvParseResult result = csvObjectMapper.read(toInputStream(csvLine)); // then then(result.getObjects()).isEmpty(); then(result.getValidationErrors()).hasSize(1); } @Test public void shouldIgnoreLinesWithUnacceptedCharacters() throws IOException { // given // contains '$' and '#' String csvLine = "line with error\n" + "$ZC62OMB,#2019-04-15,2019-05-17,PHV,InmxgozMZS,beBCC,false\n" + "ND84VSX,2019-04-14,2019-06-13,taxi,FBVoeKJGZF,Oretr,true"; // when CsvParseResult<VehicleDto> result = csvObjectMapper.read(toInputStream(csvLine)); // then then(result.getObjects()).containsExactly( VehicleDto.builder() .vrm("ND84VSX") .start("2019-04-14") .end("2019-06-13") .description("taxi") .licensingAuthorityName("FBVoeKJGZF") .licensePlateNumber("Oretr") .wheelchairAccessibleVehicle(true) .lineNumber(3) .registerJobTrigger(RegisterJobTrigger.CSV_FROM_S3) .build() ); then(result.getValidationErrors()).contains( CsvValidationError.with("Record doesn't match the data rule specifications", 1) ); } @Test public void shouldIgnoreLineWithWrongBooleanFlag() throws IOException { // given String csvLine = "line with error\n" + "ZC62OMB,2019-04-15,2019-05-17,PHV,InmxgozMZS,beBCC,1"; // when CsvParseResult<VehicleDto> result = csvObjectMapper.read(toInputStream(csvLine)); // then then(result.getObjects()).isEmpty(); then(result.getValidationErrors()).contains( CsvValidationError.with("Invalid wheelchair accessible value. Can only be True or False", 2) ); } @Test public void shouldAcceptOptionalWheelchairValue() throws IOException { // given String csvLine = "ZC62OMB,2019-04-15,2019-05-17,PHV,InmxgozMZS,beBCC,"; // when CsvParseResult<VehicleDto> result = csvObjectMapper.read(toInputStream(csvLine)); // then then(result.getObjects()).containsOnly( VehicleDto.builder() .vrm("ZC62OMB") .start("2019-04-15") .end("2019-05-17") .description("PHV") .licensingAuthorityName("InmxgozMZS") .licensePlateNumber("beBCC") .wheelchairAccessibleVehicle(null) .lineNumber(1) .registerJobTrigger(RegisterJobTrigger.CSV_FROM_S3) .build() ); } @Test public void shouldIgnoreLinesWithTooFewAttributes() throws IOException { // given String csvLine = "ZC62OMB,2019-04-15,2019-05-17,PHV,InmxgozMZS,beBCC,false\n" + "DL76MWX,2019-04-11\n" + "ND84VSX,2019-04-14,2019-06-13,taxi,FBVoeKJGZF,Oretr,true"; // when CsvParseResult<VehicleDto> result = csvObjectMapper.read(toInputStream(csvLine)); // then VehicleDto[] expected = Arrays.array( VehicleDto.builder() .vrm("ZC62OMB") .start("2019-04-15") .end("2019-05-17") .description("PHV") .licensingAuthorityName("InmxgozMZS") .licensePlateNumber("beBCC") .wheelchairAccessibleVehicle(false) .lineNumber(1) .registerJobTrigger(RegisterJobTrigger.CSV_FROM_S3) .build(), VehicleDto.builder() .vrm("ND84VSX") .start("2019-04-14") .end("2019-06-13") .description("taxi") .licensingAuthorityName("FBVoeKJGZF") .licensePlateNumber("Oretr") .wheelchairAccessibleVehicle(true) .lineNumber(3) .registerJobTrigger(RegisterJobTrigger.CSV_FROM_S3) .build() ); then(result.getObjects()).containsOnly(expected); then(result.getValidationErrors()).hasOnlyOneElementSatisfying( validationError -> then(validationError.getDetail()) .startsWith("Record doesn't match the data rule specifications") ); } private ByteArrayInputStream toInputStream(String csvLine) { return new ByteArrayInputStream(csvLine.getBytes(Charsets.UTF_8)); } }
true
b5a72636e09d3c73df48d4c0e914348cd4747968
Java
yukunkun/Gaia
/app/src/main/java/com/gaiamount/module_im/message_center/MessageTypeAdapter.java
UTF-8
3,739
1.960938
2
[]
no_license
package com.gaiamount.module_im.message_center; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.gaiamount.R; import com.hyphenate.chat.EMClient; /** * Created by haiyang-lu on 16-5-13. */ public class MessageTypeAdapter extends BaseAdapter { private static final int TYPE_EMPTY = 0; private static final int TYPE_NORMAL = 1; String[] typeListStr; int[] typeListIcon; private final LayoutInflater mInflater; private int[] messageCountList; public MessageTypeAdapter(Context context, int[] messageCountList) { this.messageCountList = messageCountList; typeListStr = context.getResources().getStringArray(R.array.message_type_list); typeListIcon = new int[]{R.mipmap.message_list_chat,R.mipmap.message_list_focusu,R.mipmap.message_list_focusm,/*R.mipmap.message_list_notice,*/ R.mipmap.message_list_comment, R.mipmap.message_list_newfriend,R.mipmap.message_list_groupnews,R.mipmap.message_list_apply}; mInflater = LayoutInflater.from(context); } public void setOfficialMessageLocList(int[] messageCountList) { this.messageCountList = messageCountList; } @Override public int getCount() { return 4;// // return typeListStr.length; } // @Override // public int getViewTypeCount() { // return 2; // } // // @Override // public int getItemViewType(int position) { // if (position == 2 || position == 6) { // return TYPE_EMPTY; // } else { // return TYPE_NORMAL; // } // } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return 0; } @Override public View getView(final int position, View convertView, ViewGroup parent) { // if (getItemViewType(position) == TYPE_EMPTY) { // return mInflater.inflate(R.layout.item_list_divider_8dp, parent, false); // } else // { View view = mInflater.inflate(R.layout.item_messge_type, parent, false); ImageView icon = (ImageView) view.findViewById(R.id.message_type_icon); TextView title = (TextView) view.findViewById(R.id.message_type_title); final TextView count = (TextView) view.findViewById(R.id.message_type_count); RelativeLayout layout= (RelativeLayout) view.findViewById(R.id.empty); View viewCon = view.findViewById(R.id.item_root); viewCon.setVisibility(View.VISIBLE); icon.setBackgroundResource(typeListIcon[position]); if (position==1||position==5||position==3) { layout.setVisibility(View.VISIBLE); } //标题 title.setText(typeListStr[position]); //官方通知消息数量 int num = messageCountList[position]; if (num != 0) { count.setText(num+""); count.setVisibility(View.VISIBLE); } else { count.setText(""); count.setVisibility(View.GONE); } count.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(position==0){ //第一个小红点.所有消息清零 EMClient.getInstance().chatManager().markAllConversationsAsRead();//清空聊天 count.setVisibility(View.GONE); } } }); return view; } }
true
5246ce306205ea3b94d0c08b1812d937dad041e8
Java
senka97/literary-association-es
/literary-association-es/src/main/java/team16/literaryassociation/services/SendEmailToMainEditorService.java
UTF-8
1,792
2.5
2
[]
no_license
package team16.literaryassociation.services; import org.camunda.bpm.engine.delegate.BpmnError; import org.camunda.bpm.engine.delegate.DelegateExecution; import org.camunda.bpm.engine.delegate.JavaDelegate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import team16.literaryassociation.model.User; import team16.literaryassociation.services.impl.EmailService; import team16.literaryassociation.services.interfaces.UserService; @Service public class SendEmailToMainEditorService implements JavaDelegate { @Autowired private EmailService emailService; @Autowired private UserService userService; @Override public void execute(DelegateExecution execution) throws Exception { System.out.println("Uslo u SendEmailToMainEditorService"); String username = (String) execution.getVariable("mainEditor"); System.out.println("Main editor: " + username); User user = userService.findByUsername(username); if (user == null) { System.out.println("Nije nasao main editora"); throw new BpmnError("SENDING_EMAIL_FAILED", "Sending email to main editor failed."); } String text = "Hello " + user.getFirstName() + " " + user.getLastName() + ",\n\nBoard members didn't agree whether book is plagiat or not, " + "so you will again have to choose editors for review of the book." + "\n\nBest regards,\nLiterary association"; String subject = "Plagiarism detection."; try { emailService.sendEmail(user.getEmail(), subject, text); } catch (Exception e) { throw new BpmnError("SENDING_EMAIL_FAILED", "Sending email to main editor failed."); } } }
true
c5ce59b5f569d9e997498ce0eb54bbb58e35e148
Java
scizeron/mmc
/mmc-api/src/test/java/com/stfciz/mmc/web/api/ApiControllerTests.java
UTF-8
5,833
2.1875
2
[]
no_license
package com.stfciz.mmc.web.api; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import org.hamcrest.CoreMatchers; import org.junit.Assert; import org.junit.Test; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MvcResult; import com.fasterxml.jackson.databind.ObjectMapper; import com.stfciz.mmc.web.AbstractWebApplicationTests; /** * * @author ByTel * */ public class ApiControllerTests extends AbstractWebApplicationTests { private ObjectMapper mapper = new ObjectMapper(); /** * * @throws Exception */ @Test public void findLastModifiedDocuments() throws Exception { // when MvcResult result = this.mockMvc.perform(get("/music").accept(MediaType.ALL_VALUE)) .andDo(print()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(status().is2xxSuccessful()).andReturn(); // then FindResponse response = this.mapper.readValue(result.getResponse().getContentAsString(), FindResponse.class); Assert.assertThat(response.getItems().get(0).getLastModified().after(response.getItems().get(1).getLastModified()) || response.getItems().get(0).getLastModified().equals(response.getItems().get(1).getLastModified()) , CoreMatchers.is(true)); } /** * * @throws Exception */ @Test public void findSomeMusic() throws Exception { // when MvcResult result = this.mockMvc.perform(get("/music").param("q", "wall").accept(MediaType.ALL_VALUE)) .andDo(print()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(status().is2xxSuccessful()).andReturn(); // then FindResponse response = this.mapper.readValue(result.getResponse().getContentAsString(), FindResponse.class); Assert.assertThat(response.getItems().size() > 0, CoreMatchers.is(true)); for (FindItemResponse doc : response.getItems()) { Assert.assertThat(doc.getTitle().toLowerCase().contains("wall"), CoreMatchers.is(true)); LOGGER.debug(this.mapper.writeValueAsString(doc)); Assert.assertThat(doc.getType(), CoreMatchers.is("music")); } } /** * * @throws Exception */ @Test public void getMusic() throws Exception { // when MvcResult result = this.mockMvc.perform(get("/music/1").accept(MediaType.ALL_VALUE)) .andDo(print()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(status().is2xxSuccessful()).andReturn(); // then com.stfciz.mmc.web.api.music.GetResponse response = this.mapper.readValue(result.getResponse().getContentAsString(), com.stfciz.mmc.web.api.music.GetResponse.class); Assert.assertThat(response.getId(), CoreMatchers.is("1")); } /** * * @throws Exception */ @Test public void findOneMusicsPageWihNoCriteria() throws Exception { // when MvcResult result = this.mockMvc.perform(get("/music").accept(MediaType.ALL_VALUE)) .andDo(print()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(status().is2xxSuccessful()).andReturn(); // then FindResponse response = this.mapper.readValue(result.getResponse().getContentAsString(), FindResponse.class); Assert.assertThat(response.getItems().size(), CoreMatchers.is(6)); for (FindItemResponse doc : response.getItems()) { LOGGER.debug(this.mapper.writeValueAsString(doc)); Assert.assertThat(doc.getType(), CoreMatchers.is("music")); } } /** * * @throws Exception */ @Test public void findSomeBooks() throws Exception { // when MvcResult result = this.mockMvc.perform(get("/book").param("q", "more").accept(MediaType.ALL_VALUE)) .andDo(print()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(status().is2xxSuccessful()).andReturn(); // then FindResponse response = this.mapper.readValue(result.getResponse().getContentAsString(), FindResponse.class); Assert.assertThat(response.getItems().size() > 0, CoreMatchers.is(true)); for (FindItemResponse doc : response.getItems()) { Assert.assertThat(doc.getTitle().contains("More"), CoreMatchers.is(true)); Assert.assertThat(doc.getType(), CoreMatchers.is("book")); } } /** * * @throws Exception */ @Test public void findOneBooksPageWihNoCriteria() throws Exception { // when MvcResult result = this.mockMvc.perform(get("/book").accept(MediaType.ALL_VALUE)) .andDo(print()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(status().is2xxSuccessful()).andReturn(); // then FindResponse response = this.mapper.readValue(result.getResponse().getContentAsString(), FindResponse.class); Assert.assertThat(response.getItems().size() > 0, CoreMatchers.is(true)); for (FindItemResponse doc : response.getItems()) { Assert.assertThat(doc.getType(), CoreMatchers.is("book")); } } /** * * @throws Exception */ @Test public void findMisc() throws Exception { // when MvcResult result = this.mockMvc.perform(get("/misc").accept(MediaType.ALL_VALUE)) .andDo(print()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(status().is2xxSuccessful()).andReturn(); // then FindResponse response = this.mapper.readValue(result.getResponse().getContentAsString(), FindResponse.class); for (FindItemResponse doc : response.getItems()) { Assert.assertThat(doc.getType(), CoreMatchers.is("misc")); } } }
true
8546e004a0a77c31c6219bb55f9b90f264062954
Java
neow3j/neow3j
/devpack/src/main/java/io/neow3j/devpack/annotations/Struct.java
UTF-8
563
2.53125
3
[ "Apache-2.0" ]
permissive
package io.neow3j.devpack.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Target; /** * This annotation indicates that a class will be used as a NeoVM Struct. * <p> * Every custom Java class you intend to use as a NeoVM Struct in your smart contract class must be annotated with * {code @Struct} in order for the compilation to be successful. This is because instances of Java classes are simple * structs on the NeoVM. There is no notion of an object on NeoVM. */ @Target(ElementType.TYPE) public @interface Struct { }
true
bbb5f886d23d11e0dfc858a7435250dca85ddfe9
Java
chicken-noodle/android-labs-2019
/students/soft1714080902319/Soft1714080902319/java/edu/hzuapps/androidlabs/soft1714080902319/Soft1714080902319.java
UTF-8
1,272
2.046875
2
[]
no_license
package edu.hzuapps.androidlabs.soft1714080902319; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; public class Soft1714080902319 extends AppCompatActivity { private Button button1; private Button button2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.soft1714080902319); button1 = (Button) findViewById(R.id.button1); button1.setOnClickListener(listener); button2 = (Button) findViewById(R.id.button2); button2.setOnClickListener(listener2); } Button.OnClickListener listener = new Button.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(Soft1714080902319.this, Soft1714080902319_2.class); startActivity(intent); } }; Button.OnClickListener listener2 = new Button.OnClickListener() { public void onClick(View v) { Intent intent = new Intent(Soft1714080902319.this, Soft1714080902319_3.class); startActivity(intent); } }; }
true
b8f478e15cc0c5b96257a3322e70c92e422e6954
Java
ceacatlvs/prueba-baalam
/src/main/java/com/baalam/model/histclinica/iays/IAySMuscEsqueletico.java
UTF-8
2,133
2.140625
2
[]
no_license
package com.baalam.model.histclinica.iays; import java.io.Serializable; import javax.persistence.*; import javax.validation.constraints.Size; import com.baalam.model.paciente.Paciente; /** * Entity implementation class for Entity: IAySMuscEsqueletico * */ @Entity @Table( name = "iays_musculo_esqueletico", uniqueConstraints = @UniqueConstraint(columnNames = "idPaciente")) public class IAySMuscEsqueletico implements Serializable { private static final long serialVersionUID = 1L; @Id @OneToOne @JoinColumn(name="idPaciente") private Paciente paciente; @Column(name = "negativo", columnDefinition="BIT(1)") private Boolean negativo; @Column(name = "dolorMuscular", columnDefinition="BIT(1)") private Boolean dolorMuscular; @Column(name = "dolorArticular", columnDefinition="BIT(1)") private Boolean dolorArticular; @Column(name = "debilidadMusc", columnDefinition="BIT(1)") private Boolean debilidadMusc; @Size(min = 0, max = 500) @Column(name = "otro") private String otro; @Size(min = 0, max = 500) @Column(name = "observaciones") private String observaciones; public Paciente getPaciente() { return paciente; } public void setPaciente(Paciente paciente) { this.paciente = paciente; } public Boolean getNegativo() { return negativo; } public void setNegativo(Boolean negativo) { this.negativo = negativo; } public Boolean getDolorMuscular() { return dolorMuscular; } public void setDolorMuscular(Boolean dolorMuscular) { this.dolorMuscular = dolorMuscular; } public Boolean getDolorArticular() { return dolorArticular; } public void setDolorArticular(Boolean dolorArticular) { this.dolorArticular = dolorArticular; } public Boolean getDebilidadMusc() { return debilidadMusc; } public void setDebilidadMusc(Boolean debilidadMusc) { this.debilidadMusc = debilidadMusc; } public String getOtro() { return otro; } public void setOtro(String otro) { this.otro = otro; } public String getObservaciones() { return observaciones; } public void setObservaciones(String observaciones) { this.observaciones = observaciones; } }
true
4564391c35eb5871637daefeb45e9d45613b7b58
Java
Ohtake200505/webjava_3
/src/main/java/jp/co/systena/tigerscave/rpgwithdb/model/Dragon.java
UTF-8
196
2.109375
2
[]
no_license
package jp.co.systena.tigerscave.rpgwithdb.model; public class Dragon implements MonsterType { @Override public String attack() { return "ドラゴンは炎を吐いた!"; } }
true
b7ab8b91e5b3a2f87732d4e50dc328e65650b369
Java
healingtjx/tjx
/tjx-serve-cms/src/main/java/com/healing/tjx/cms/service/UserBaseCacheService.java
UTF-8
867
2.0625
2
[]
no_license
package com.healing.tjx.cms.service; import com.healing.tjx.datasource.entity.UserBase; /** * @Author: 作者 * @Description: 描述 * @Date: 创建于22:44 2021-06-02 **/ public interface UserBaseCacheService { /** * 用户登陆后缓存用户信息(24小时) * * @param userBase */ void setUser(UserBase userBase); /** * 根据userId查询缓存 * * @param userId * @return */ UserBase getUser(String userId); /** * 删除缓存 * * @param userId */ void delUser(String userId); /** * 根据code 获取 SessionKey * * @param code * @return */ String getSessionKey(String code); /** * 设置 SessionKey * * @param code * @param sessionKey */ void setSessionKey(String code, String sessionKey); }
true
6da8d9b6fd0feb741b985a98dfdc0d5621566c12
Java
frkr/poc-eureka
/poc-client/src/main/java/poc/data/Primeiro.java
UTF-8
840
2.046875
2
[]
no_license
package poc.data; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.netflix.ribbon.RibbonClient; import org.springframework.context.annotation.Bean; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @RestController @RibbonClient(name = "poc-data") public class Primeiro { @LoadBalanced @Bean RestTemplate restTemplate() { return new RestTemplate(); } @Autowired RestTemplate restTemplate; @RequestMapping("/primeiro") public String primeiro() { return restTemplate .getForObject("http://poc-data/cliente/1", String.class); } }
true
b31fd376ecaf2d006e4c55b0f675338ebe3dedae
Java
1goruxa/WebSocketChat
/src/main/java/main/Controllers/UserController.java
UTF-8
1,425
2.296875
2
[]
no_license
package main.Controllers; import main.Services.CheckService; import main.Services.RegisterService; import main.api.Request.RegisterRequest; import main.api.Response.CheckResponse; import main.api.Response.RegisterResponse; import main.repo.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.ArrayList; @RestController public class UserController { @Autowired RegisterService registerService; @Autowired CheckService checkService; @Autowired UserRepository userRepository; @PostMapping("/register") public RegisterResponse register(@RequestBody RegisterRequest data){ return registerService.register(data); } @GetMapping("/check") public CheckResponse check(@RequestParam String name, @RequestParam String password){ return checkService.check(name, password); } @GetMapping("/updateUser") public ArrayList<String> updateOnlineUser(@RequestParam String name, @RequestParam boolean updateUser){ ArrayList<String> users = checkService.updateUserOnlineStatus(name, updateUser); return users; } @GetMapping("/updateUserStomp") public ArrayList<String> updateAllOnlineUser(){ ArrayList<String> users = userRepository.findAllOnline(); return users; } }
true
eddce1de043f2b31264af0c5dd0ca9b8a54b5de4
Java
wanghaoo/freamwork
/src/main/java/com/humandaily/www/common/freamwork/MyBatisConfig.java
UTF-8
1,844
2
2
[]
no_license
package com.humandaily.www.common.freamwork; import org.apache.commons.dbcp.BasicDataSource; import org.mybatis.spring.SqlSessionFactoryBean; import org.mybatis.spring.annotation.MapperScan; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; /** * Created by datadriver on 2017/7/19. */ @Configuration @EnableTransactionManagement @MapperScan(basePackages = "com.humandaily.www.mapper") public class MyBatisConfig { @Bean public BasicDataSource dataSource(){ BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://localhost:3306/invest_ecosystem?useUnicode=true&characterEncoding=utf-8");//防止乱码 dataSource.setUsername("root"); dataSource.setPassword("admin"); dataSource.setInitialSize(5); dataSource.setMaxActive(10); return dataSource; } @Bean public DataSourceTransactionManager transactionManager() { return new DataSourceTransactionManager(dataSource()); } @Bean public SqlSessionFactoryBean sqlSessionFactory() throws Exception { SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(dataSource()); sessionFactory.setTypeAliasesPackage("com.humandaily.www.web"); sessionFactory.setMapperLocations( new PathMatchingResourcePatternResolver().getResources( "classpath:mapper/*.xml")); return sessionFactory; } }
true
313f8ddb93a27e19891d556485910be841d1c9c7
Java
seedtronic/doctalk
/src/java/gui/GuiClientes.java
UTF-8
2,240
2.25
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package gui; import Dao.Dados; import Dao.DaoCliente; import java.io.Serializable; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.enterprise.context.SessionScoped; import javax.inject.Named; import model.Cliente; /** * * @author fjunger */ @Named(value = "guiClientes") @SessionScoped public class GuiClientes implements Serializable{ private List<Cliente> listaDeClientes; private Cliente cliente; private boolean incluindo = false; public String gravarCliente(){ Dados d = new DaoCliente(); if(incluindo){ try { d.gravar(cliente); } catch (Exception ex) { Logger.getLogger(GuiClientes.class.getName()).log(Level.SEVERE, null, ex); } } return "frmlstCliente"; } public String deletarCliente(Cliente c){ Dados d = new DaoCliente(); try { d.excluir(c); } catch (Exception ex) { Logger.getLogger(GuiClientes.class.getName()).log(Level.SEVERE, null, ex); } return "frmlstCliente"; } public String editarCliente(Cliente c){ incluindo = false; cliente = c; return "frmAddCliente"; } public Cliente getCliente() { return cliente; } public void setCliente(Cliente cliente) { this.cliente = cliente; } public String iniciarCliente(){ listaDeClientes = new DaoCliente().getList(); return "frmlstCliente"; } public String novoCliente(){ incluindo = true; cliente = new Cliente(); return "frmAddCliente"; } public List<Cliente> getListaDeClientes() { return listaDeClientes; } public void setListaDeClientes(List<Cliente> listaDeClientes) { this.listaDeClientes = listaDeClientes; } }
true
474cba932ad0d21c16e6fd4821e12d1965938a65
Java
manair/Simple-Shopping-List
/app/src/main/java/com/yondev/shoppinglist/MainActivity.java
UTF-8
6,147
1.90625
2
[]
no_license
package com.yondev.shoppinglist; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import com.facebook.ads.Ad; import com.facebook.ads.AdError; import com.facebook.ads.InterstitialAdListener; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.InterstitialAd; import com.yondev.shoppinglist.adapter.BarangAddAdapter; import com.yondev.shoppinglist.adapter.DaftarAdapter; import com.yondev.shoppinglist.entity.Daftar; import com.yondev.shoppinglist.utils.Shared; import java.util.List; public class MainActivity extends AppCompatActivity implements View.OnClickListener, TextWatcher,InterstitialAdListener { private ListView lv; private TextView txthint; private DaftarAdapter adapter; private boolean isFirstime = true; private com.facebook.ads.InterstitialAd interstitialAd; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Shared.initialize(getBaseContext()); setContentView(R.layout.activity_main); findViewById(R.id.btnTambah).setOnClickListener(this); lv = (ListView)findViewById(R.id.listview); txthint = (TextView)findViewById(R.id.textView2); List<Daftar> daftar = Daftar.findWithQuery(Daftar.class,"SELECT * FROM DAFTAR order by tanggal desc "); adapter = new DaftarAdapter(this,daftar); lv.setAdapter(adapter); if(daftar.size() == 0 ) txthint.setVisibility(View.VISIBLE); else txthint.setVisibility(View.GONE); adapter.setChangeListener(new BarangAddAdapter.changeListener() { @Override public void onChange() { if(adapter.getCount() == 0 ) txthint.setVisibility(View.VISIBLE); else txthint.setVisibility(View.GONE); } }); EditText search = (EditText)findViewById(R.id.editText); search.addTextChangedListener(this); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Daftar data = (Daftar) adapter.getItem(position); Intent intent = new Intent(MainActivity.this, CheckListActivity.class); intent.putExtra("id",data.getId()); startActivityForResult(intent,10002); overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out); } }); TextView title = (TextView)findViewById(R.id.textView); title.setTypeface(Shared.appfontTitle); Button tambah = (Button)findViewById(R.id.btnTambah); tambah.setTypeface(Shared.appfontBold); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btnTambah: Intent intent = new Intent(MainActivity.this, AddDaftarActivity.class); startActivityForResult(intent,10001); overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out); break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(resultCode == RESULT_OK) { if(requestCode == 10001 || requestCode == 10002) { List<Daftar> daftar = Daftar.findWithQuery(Daftar.class,"SELECT * FROM DAFTAR order by tanggal desc "); adapter.set(daftar); if(daftar.size() == 0 ) txthint.setVisibility(View.VISIBLE); else txthint.setVisibility(View.GONE); } } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { List<Daftar> daftar = Daftar.findWithQuery(Daftar.class,"SELECT * FROM DAFTAR WHERE LOWER(nama) like '%"+s.toString().toLowerCase()+"%' order by tanggal desc "); adapter.set(daftar); } @Override public void afterTextChanged(Editable s) { } @Override protected void onResume() { super.onResume(); loadInterstitialAd(); } public void displayInterstitial() { // If Ads are loaded, show Interstitial else show nothing. if (interstitialAd.isAdLoaded()) { interstitialAd.show(); } } private void loadInterstitialAd() { interstitialAd = new com.facebook.ads.InterstitialAd(this, getString(R.string.interstitial_id)); interstitialAd.setAdListener(this); interstitialAd.loadAd(); } @Override public void onError(Ad ad, AdError error) { // Ad failed to load } @Override public void onAdLoaded(Ad ad) { // Ad is loaded and ready to be displayed // You can now display the full screen add using this code: if(isFirstime) { displayInterstitial(); isFirstime = false; } } @Override public void onAdClicked(Ad ad) { } @Override public void onLoggingImpression(Ad ad) { } @Override public void onInterstitialDisplayed(Ad ad) { loadInterstitialAd(); } @Override public void onInterstitialDismissed(Ad ad) { } @Override protected void onDestroy() { super.onDestroy(); displayInterstitial(); } }
true
7194cf2180d05c2a2e8cc2bb048328340ce3c704
Java
unaccepted/OLMS
/src/main/java/com/nrifintech/olmsb/exception/OLMSException.java
UTF-8
3,818
2.46875
2
[]
no_license
/* * +=============================================================================================+ * | | * | Copyright (C) 2013-2018 | * | Nomura Research Institute Financial Technologies India Pvt. Ltd. | * | All Rights Reserved | * | | * | This document is the sole property of Nomura Research Institute Financial Technologies | * | India Pvt. Ltd. No part of this document may be reproduced in any form or by any | * | means - electronic, mechanical, photocopying, recording or otherwise - without the prior | * | written permission of Nomura Research Institute Financial Technologies India Pvt. Ltd. | * | | * | 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. | * | | * +=============================================================================================+ */ package com.nrifintech.olmsb.exception; /** * Root of the checked exception hierarchy in OLMS. All the checked * exceptions of the application shall extend from this class. */ public class OLMSException extends Exception { //~ Class Attributes ------------------------------------------------------- /** * The <code>serialVersionUID</code>. */ private static final long serialVersionUID = -2666265946231745520L; //~ Constructors ----------------------------------------------------------- /** * Construct a default instance. */ public OLMSException() { super(); } /** * Construct an instance with specified message. * * @param message the given message. */ public OLMSException(String message) { super(message); } /** * Construct an instance with specified cause. * * @param cause the cause of this exception. */ public OLMSException(Throwable cause) { super(cause); } /** * Construct an instance with specified message and cause. * * @param message the given message. * @param cause the cause of this exception. */ public OLMSException(String message, Throwable cause) { super(message, cause); } /** * Construct an instance with specified message, error code and cause. * * @param message the given message. * @param code the error code * @param cause the cause of this exception. */ public OLMSException(String message, String code, Throwable cause) { super(message, cause); } /* * Default implementation of toString() appends the class name with the message irrespective of whether there is value * returned by getLocalizedMessage(). However when getLocalizedMessage() has value then class name will not be appended * with the exception message. */ @Override public String toString() { String s = "Unknown Error"; String message = getLocalizedMessage(); return (message != null) ? (message) : s; } }
true
78ca161b8fae1a141ea3b7c7eaf7f91370531c23
Java
nonocodebox/oop
/ex4-java-compiler/main/CodeException.java
UTF-8
244
2.1875
2
[]
no_license
package clids.ex4.main; /** * * Represents a general exception in Sjava file. * */ public class CodeException extends Exception { private static final long serialVersionUID = 1L; public CodeException(String msg) { super(msg); } }
true
1c7122c62a5c49d09231f71b354b8c8fa0582cad
Java
winetx/new0713
/testgit/Study/src/com/one/Study03.java
UTF-8
122
2.109375
2
[]
no_license
package com.one; public class Study03<E> { public void show(E name){ System.out.println(name+"hai"); } }
true
8438435403e051a7d27b59831e15a7606cab8736
Java
ferchouche/SmallUML
/UML/src/uml/actions/LinkEndCreationData.java
UTF-8
3,450
2.28125
2
[]
no_license
/** */ package uml.actions; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Link End Creation Data</b></em>'. * <!-- end-user-doc --> * * <!-- begin-model-doc --> * LinkEndCreationData is LinkEndData used to provide values for one end of a link to be created by a CreateLinkAction. * if not end.isOrdered * then insertAt = null * else * not isReplaceAll=false implies * insertAt <> null and insertAt->forAll(type=UnlimitedNatural and is(1,1)) * endif * * <!-- end-model-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link uml.actions.LinkEndCreationData#getInsertAt <em>Insert At</em>}</li> * <li>{@link uml.actions.LinkEndCreationData#isIsReplaceAll <em>Is Replace All</em>}</li> * </ul> * * @see uml.actions.ActionsPackage#getLinkEndCreationData() * @model annotation="http://www.eclipse.org/emf/2002/Ecore constraints='insertAt_pin'" * annotation="http://www.eclipse.org/emf/2002/Ecore/OCL insertAt_pin='if not end.isOrdered\nthen insertAt = null\nelse\n\tnot isReplaceAll=false implies\n\tinsertAt <> null and insertAt->forAll(type=UnlimitedNatural and is(1,1))\nendif\n'" * @generated */ public interface LinkEndCreationData extends LinkEndData { /** * Returns the value of the '<em><b>Insert At</b></em>' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * <!-- begin-model-doc --> * For ordered Association ends, the InputPin that provides the position where the new link should be inserted or where an existing link should be moved to. The type of the insertAt InputPin is UnlimitedNatural, but the input cannot be zero. It is omitted for Association ends that are not ordered. * <!-- end-model-doc --> * @return the value of the '<em>Insert At</em>' reference. * @see #setInsertAt(InputPin) * @see uml.actions.ActionsPackage#getLinkEndCreationData_InsertAt() * @model ordered="false" * annotation="http://schema.omg.org/spec/MOF/2.0/emof.xml#Property.oppositeRoleName body='linkEndCreationData'" * @generated */ InputPin getInsertAt(); /** * Sets the value of the '{@link uml.actions.LinkEndCreationData#getInsertAt <em>Insert At</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Insert At</em>' reference. * @see #getInsertAt() * @generated */ void setInsertAt(InputPin value); /** * Returns the value of the '<em><b>Is Replace All</b></em>' attribute. * The default value is <code>"false"</code>. * <!-- begin-user-doc --> * <!-- end-user-doc --> * <!-- begin-model-doc --> * Specifies whether the existing links emanating from the object on this end should be destroyed before creating a new link. * <!-- end-model-doc --> * @return the value of the '<em>Is Replace All</em>' attribute. * @see #setIsReplaceAll(boolean) * @see uml.actions.ActionsPackage#getLinkEndCreationData_IsReplaceAll() * @model default="false" dataType="types.Boolean" required="true" ordered="false" * @generated */ boolean isIsReplaceAll(); /** * Sets the value of the '{@link uml.actions.LinkEndCreationData#isIsReplaceAll <em>Is Replace All</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Is Replace All</em>' attribute. * @see #isIsReplaceAll() * @generated */ void setIsReplaceAll(boolean value); } // LinkEndCreationData
true
6e09ef0513078361854643236eba451a8ac03fd1
Java
Sinchaohao/RongSysMedia
/sixin-admin/src/main/java/com/sixin/web/controller/iot/BroadController.java
UTF-8
11,740
1.804688
2
[]
no_license
package com.sixin.web.controller.iot; import com.sixin.broad.domain.*; import com.sixin.broad.service.*; import com.sixin.broad.utils.bFileUtil; import com.sixin.common.annotation.Log; import com.sixin.common.exception.BusinessException; import com.sixin.common.support.Convert; import com.sixin.common.utils.DateUtil; import com.sixin.common.utils.StringUtils; import com.sixin.framework.web.base.BaseController; import com.sixin.common.base.AjaxResult; import com.sixin.common.page.TableDataInfo; import com.sixin.common.enums.BusinessType; import com.sixin.common.utils.poi.ExcelUtil; import com.sixin.framework.util.ShiroUtils; import com.sixin.iot.domain.Broad; import com.sixin.iot.domain.BroadTerminal; import com.sixin.iot.service.IBroadService; import com.sixin.system.domain.SysUser; import com.sixin.system.service.ISysUserService; import com.sixin.village.domain.Files; import com.sixin.village.util.bFileUtil1; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import java.util.Map; /** * 终端信息操作处理 * * @author 蔡文静 * @date 2020-4-10 */ @Controller @RequestMapping("/iot/broad") public class BroadController extends BaseController { private String prefix = "iot/broad"; @Autowired private IBroadService broadService; @Autowired private IMessageService messageService; @Autowired private ISysUserService sysUserService; @Autowired private IAreaService areaService; @Autowired IAreaGroupingService iAreaGroupingService; @RequiresPermissions("iot:broadinfo:view") @GetMapping() public String broad() { return prefix + "/broad"; } //查询========================================================================================================== @RequiresPermissions("iot:broadinfo:list") @PostMapping("/list") @ResponseBody public TableDataInfo list(Broad broad){ startPage(); List<Broad> list = broadService.selectBroadList(broad); return getDataTable(list); } //删除========================================================================================================== @Log(title = "终端信息删除", businessType = BusinessType.DELETE) @RequiresPermissions("iot:broadinfo:remove") @PostMapping( "/remove") @ResponseBody public AjaxResult remove(String ids){ broadService.deleteManByIds(Convert.toStrArray(ids)); broadService.deleteConByIds(Convert.toStrArray(ids)); return toAjax(broadService.deleteBroadByIds(Convert.toStrArray(ids))); } //更新========================================================================================================== @GetMapping("/edit/{tid}") public String edit(@PathVariable("tid") String[] tid, ModelMap mmap){ Broad broad = broadService.selectBroadListByTids(tid).get(0); mmap.put("broad", broad); return prefix + "/edit"; } /** * 编辑保存终端信息 */ @RequiresPermissions("iot:broadinfo:edit") @Log(title = "终端信息修改", businessType = BusinessType.UPDATE) @PostMapping("/edit") @ResponseBody public AjaxResult editSave(Broad broad){ broadService.updateCon(broad); broadService.updateMan(broad); return toAjax( broadService.updateBroad(broad)); } //新增=========================================================================================================== @GetMapping("/add") public String add(){ return prefix + "/add"; } @Log(title = "新增终端", businessType = BusinessType.INSERT) @PostMapping("/add") @RequiresPermissions("iot:broadinfo:add") @ResponseBody public AjaxResult addSave(Broad broad){ // ,@RequestParam(value = "files") MultipartFile file[], // @RequestParam(value = "filesnum", required = false) Integer filesnum, // @RequestParam(value = "filename", required = false) String fname, // @RequestParam(value = "flenth" ,required = false)String flenth, //时长 // @RequestParam(value = "fsize",required = false) String fsize){//大小 //获取上传的图片,保存 MultipartFile pic= broad.getPoscenepic(); String fileurl = bFileUtil.saveImg(pic ); broad.setPoscene(fileurl); broadService.insertCon(broad); broadService.insertMan(broad); // String year = DateUtil.getYear(); // Date date = new Date(); // SimpleDateFormat dateFormat= new SimpleDateFormat("yyyyMMddhhmmss"); // System.out.println(dateFormat.format(date)); // String maxfileid = dateFormat.format(date); // //图片上传调用工具类 // try{ // int i; // String fileaddress = ""; // for(i=0;i<filesnum;i++) // { // //保存文件 // Files g = bFileUtil1.uplodeFile(maxfileid,file[i],fname,flenth,fsize,year); // System.out.println(g.toString());//在控制台输出文件信息 // fileaddress = fileaddress + g.getAddress() + ";";//通过fileaddress来储存文件地址 // } // broad.setPoscene(fileaddress);//给project实体的“文件地址”赋值 // // return toAjax(broadService.insertBroad(broad));//将project实体中的值插入数据表中 // }catch (Exception e){ // //return "上传文件失败"; // System.out.println("失败"); return toAjax(broadService.insertBroad(broad)); } //导出=========================================================================================================== @Log(title = "终端管理", businessType = BusinessType.EXPORT) @RequiresPermissions("iot:broadinfo:export") @PostMapping("/export") @ResponseBody public AjaxResult export(Broad broad){ List<Broad> list = broadService.selectBroadList(broad); ExcelUtil<Broad> util = new ExcelUtil<Broad>(Broad.class); return util.exportExcel(list, "终端管理表"); } //根据Tids批量导出=========================================================================================================== @Log(title = "终端管理", businessType = BusinessType.EXPORT) @RequiresPermissions("iot:broadinfo:export") @PostMapping("/exportbysingle") @ResponseBody public AjaxResult exportBroadByTids(@RequestParam("sjids") String[] tids) { List<Broad> list = broadService.selectBroadListByTids(tids); ExcelUtil<Broad> util = new ExcelUtil<Broad>(Broad.class); return util.exportExcel(list, "终端管理表"); } @GetMapping("/listProBroadTree") @ResponseBody public List<Map<String, Object>> listProBroadTree(){ List<Map<String, Object>> tree = messageService.selectMessageList(new BroadMessage()); return tree; } @GetMapping("/treeData") @ResponseBody public List<Map<String, Object>> treeData(){ SysUser currentUser = ShiroUtils.getSysUser();//从session中获取当前登陆用户的userid Long userid = currentUser.getUserId(); //int returnId = new Long(userid).intValue(); int roleid = sysUserService.selectRoleid(userid);//通过所获取的userid去广播用户表中查询用户所属区域的Roleid if(roleid == 1) { List<Map<String, Object>> tree = areaService.selectAreaTree(new Area()); return tree; }else { long aid; aid =Long.valueOf(sysUserService.selectAid(userid));//通过所获取的userid去广播用户表中查询用户所属区域的Aid Area update_area = new Area(); update_area.setAid(aid); List<Map<String, Object>> tree = areaService.selectAreaTree(update_area); return tree; } } /** * 选择区域树 * @description 目前村务在调用此接口 */ @GetMapping("/selectAidTree") public String selectAidTree() { return prefix + "/aidTree"; } @GetMapping("/selectBroadTree/{aid}") public String selectBroadTree(@PathVariable("aid") long aid, ModelMap mmap) { mmap.put("broad", areaService.selectAreaById(aid)); return prefix + "/listProBroadTree"; } @GetMapping("/phoneEdit/{tid}") public String phoneEdit(@PathVariable("tid") String tid, ModelMap mmap){ return prefix + "/phoneEdit"; } @PostMapping("/phoneEdit/{tid}") @ResponseBody public List<BroadTerminal> phoneEditpost(@PathVariable("tid") String tid, ModelMap mmap){ List<BroadTerminal> terminalTels= broadService.selectTelsByTid(tid); mmap.put("terminalTels", terminalTels); return terminalTels; } @PostMapping("/addphoneedit") @ResponseBody public int addphoneEdit(BroadTerminal terminalTels){ return broadService.addphoneEdit(terminalTels); } @GetMapping("/deletephoneedit/{telid}") @ResponseBody public String deletephoneedit(@PathVariable("telid") String telid){ if(broadService.deletephoneedit(telid)==1); return "操作成功"; } @PostMapping("/listProBroad") @ResponseBody public TableDataInfo listProBroad(Broad broad){ startPage() ; List<Broad> list = broadService.selectProBroadList(broad); return getDataTable(list); } @PostMapping( "/isuseSet") @ResponseBody public AjaxResult isuseSet(String tid, Boolean isuse){ return toAjax(broadService.updateIsuseByTid(tid,isuse)); } /** * 导入数据 */ @PostMapping("/importData") @ResponseBody public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception { ExcelUtil<Broad> util = new ExcelUtil<Broad>(Broad.class); List<Broad> broadList = util.importExcel(file.getInputStream()); String message = importBroad(broadList, updateSupport); return AjaxResult.success(message); } /** * 导入用户数据 * * @param BroadList 用户数据列表 * @param isUpdateSupport 是否更新支持,如果已存在,则进行更新数据(该功能未实现) * @return 结果 */ public String importBroad(List<Broad> broadList, Boolean isUpdateSupport) { if (StringUtils.isNull(broadList) || broadList.size() == 0) { throw new BusinessException("导入用户数据不能为空!"); } int successNum = 0; StringBuilder successMsg = new StringBuilder(); StringBuilder failureMsg = new StringBuilder(); /*通过读取表格内容获得Broadlist,再通过遍历Broadlist去将每一行数据插入数据库中*/ for (Broad broad : broadList) { try { broadService.insertCon(broad); broadService.insertMan(broad); broadService.insertBroad(broad); successNum++; successMsg.append("<br/>" + successNum + "用户 " + broad.getTid() + " 导入成功"); } catch (Exception e) { String msg = broad.getTid() + " 导入失败:"; failureMsg.append(msg + e.getMessage()); } } return successMsg.toString(); } }
true
31b238941b292b1d1c45b99e22fef27b4b941c16
Java
amitkpandey/pokemon
/PokemonToronto/core/src/com/pokemon/toronto/game/com/pokemon/toronto/area/SeafoamB2F.java
UTF-8
1,442
2.328125
2
[]
no_license
package com.pokemon.toronto.game.com.pokemon.toronto.area; import com.pokemon.toronto.game.com.pokemon.toronto.Pokemon.RoutePokemon; import com.pokemon.toronto.game.com.pokemon.toronto.Pokemon.attributes.PokemonId; import com.pokemon.toronto.game.com.pokemon.toronto.player.Player; import java.util.ArrayList; /** * Created by gregorykelsie on 2018-02-22. */ public class SeafoamB2F extends Route { public SeafoamB2F() { super(Route.SEAFOAM_B2F, "simulator/routes/seafoam.png", "Seafoam Islands B2F", "battle/ice.png"); } @Override protected void initGrassPokemon() { grassPokemon = new ArrayList<RoutePokemon>(); grassPokemon.add(new RoutePokemon(PokemonId.PSYDUCK.getValue(), 30, 32, 20)); grassPokemon.add(new RoutePokemon(PokemonId.SLOWPOKE.getValue(), 30, 32, 40)); grassPokemon.add(new RoutePokemon(PokemonId.SEEL.getValue(), 30, 32, 60)); grassPokemon.add(new RoutePokemon(PokemonId.ZUBAT.getValue(), 22, 24, 80)); grassPokemon.add(new RoutePokemon(PokemonId.GOLBAT.getValue(), 26, 30, 90)); grassPokemon.add(new RoutePokemon(PokemonId.GOLDUCK.getValue(), 32, 34, 95)); grassPokemon.add(new RoutePokemon(PokemonId.SLOWBRO.getValue(), 32, 34, 100)); } public boolean isAvailable(Player p) { if (p.getKantoBadges() >= 7) { return true; } else { return false; } } }
true
33ec2c812e9ea0ec60dfc578894070937883dd19
Java
SocialStudyOrganization/SocialStudyProject
/app/src/main/java/com/ndlp/socialstudy/ShowKursmitglieder/TransformRefreshingKursmitglieder.java
UTF-8
2,773
2.46875
2
[]
no_license
package com.ndlp.socialstudy.ShowKursmitglieder; import android.app.ProgressDialog; import android.content.Context; import android.os.AsyncTask; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; public class TransformRefreshingKursmitglieder extends AsyncTask<Void,Void,Boolean> { private Context context; private JSONArray jsonData; private RecyclerView recyclerView; private ProgressDialog pd; private ArrayList<KursmitgliederObject> kursmitgliederObjectArrayList = new ArrayList<>(); private KursmitgliederRecyclerAdapter kursmitgliederRecyclerAdapter = new KursmitgliederRecyclerAdapter(); // Constructor public TransformRefreshingKursmitglieder(Context context, JSONArray jsonData, RecyclerView recyclerView) { this.context = context; this.jsonData = jsonData; this.recyclerView = recyclerView; } // shows progressDialog to actualize data displayed @Override protected void onPreExecute() { super.onPreExecute(); pd = new ProgressDialog(context); pd.setTitle("Parse"); pd.setMessage("Loading your Files from the server..."); pd.show(); } @Override protected Boolean doInBackground(Void... params) { return this.parseData(); } // if result true handle set recyclerView @Override protected void onPostExecute(Boolean result) { super.onPostExecute(result); pd.dismiss(); if (result) { recyclerView.setLayoutManager(new LinearLayoutManager(context)); kursmitgliederRecyclerAdapter.setContext(context); kursmitgliederRecyclerAdapter.setScriptList(kursmitgliederObjectArrayList); recyclerView.setAdapter(kursmitgliederRecyclerAdapter); } } private Boolean parseData() { try { JSONObject jo; kursmitgliederObjectArrayList.clear(); for (int i = 0; i < jsonData.length(); i++) { jo = jsonData.getJSONObject(i); KursmitgliederObject kursmitgliederObject = new KursmitgliederObject(jo.getInt("Matrikelnummer"), jo.getString("email") , jo.getString("firstName"), jo.getString("surname")); kursmitgliederObjectArrayList.add(kursmitgliederObject); kursmitgliederRecyclerAdapter.notifyDataSetChanged(); } return true; } catch (JSONException e) { e.printStackTrace(); } return false; } }
true
0ba57bcd7e856ec0f6c71d73f21948ad366218eb
Java
lzyer2016/learning4all
/learning4algorithm/src/main/java/com/learning4algorithm/leetcode/medium/Reduce_Array_Size_to_The_Half.java
UTF-8
934
3.328125
3
[]
no_license
package com.learning4algorithm.leetcode.medium; import java.util.Comparator; import java.util.HashMap; import java.util.Map; import java.util.PriorityQueue; public class Reduce_Array_Size_to_The_Half { public int minSetSize(int[] arr) { Map<Integer, Integer> map = new HashMap<>(); for (int a : arr) { map.put(a, map.getOrDefault(a, 0) + 1); } PriorityQueue<Integer> queue = new PriorityQueue<>(Comparator.reverseOrder()); for (Map.Entry<Integer, Integer> entry : map.entrySet()) { queue.add(entry.getValue()); } int length = arr.length; int half = length / 2; int size = 0; while (!queue.isEmpty()) { int n = queue.poll(); length -= n; size++; if (length <= half) { break; } } return size; } }
true
73d1454bf1d2dd2c207e6924b3dcfe346404b26a
Java
JerryLi912/Data-Structures-Using-Java
/Graphs/src/Main.java
UTF-8
343
2.390625
2
[]
no_license
public class Main { public static void main(String[] args) { Graph graph = new Graph(4); graph.addEdge(0, 1, 10); graph.addEdge(0, 2, 10); graph.addEdge(1, 2, 10); graph.addEdge(2, 0, 10); graph.addEdge(2, 3, 10); graph.addEdge(3, 3, 10); graph.DFS(2); } }
true
5bc2153c5bb6d5d21ffd9c9ad0386a2cfdc28622
Java
mushroomhostage/Shelf
/server-bukkit/CraftingInventoryShelfCB.java
UTF-8
1,357
2.203125
2
[]
no_license
package net.minecraft.server; import net.minecraft.server.Container; import net.minecraft.server.EntityHuman; import net.minecraft.server.IInventory; import net.minecraft.server.ItemStack; import net.minecraft.server.Slot; import net.minecraft.server.TileEntityShelf; public class CraftingInventoryShelfCB extends Container { private TileEntityShelf entity; public EntityHuman player; public CraftingInventoryShelfCB(EntityHuman player, TileEntityShelf tileentityshelf) { this.player = player; IInventory iinventory = player.inventory; this.entity = tileentityshelf; int k; int i1; for(k = 0; k < 3; ++k) { for(i1 = 0; i1 < 3; ++i1) { this.a(new Slot(tileentityshelf, i1 + k * 3, 62 + i1 * 18, 17 + k * 18)); } } for(k = 0; k < 3; ++k) { for(i1 = 0; i1 < 9; ++i1) { this.a(new Slot(iinventory, i1 + k * 9 + 9, 8 + i1 * 18, 84 + k * 18)); } } for(k = 0; k < 9; ++k) { this.a(new Slot(iinventory, k, 8 + k * 18, 142)); } } public boolean b(EntityHuman entityhuman) { return this.entity.a(entityhuman); } public ItemStack a(int i) { return null; } public EntityHuman getPlayer() { return player; } public IInventory getInventory() { return entity; } }
true
cb1dd79209e5fa6c88ba4f0947e008cc0cd9bf0d
Java
wanxin0001/leetcode_code
/Template/Merge_Sorted_Array.java
UTF-8
1,049
3.359375
3
[]
no_license
/* Merge Sorted Array Total Accepted: 19377 Total Submissions: 60556 My Submissions Given two sorted integer arrays A and B, merge B into A as one sorted array. Note: You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements from B. The number of elements initialized in A and B are m and n respectively. */ public class Solution { public void merge(int A[], int m, int B[], int n) { if (n == 0) { return; } if (m == 0) { System.arraycopy(B, 0, A, 0, n); return; } int aPtr = m - 1; int bPtr = n - 1; int ptr = m + n - 1; while(aPtr >= 0 && bPtr >= 0) { if (A[aPtr] > B[bPtr]) { A[ptr--] = A[aPtr--]; } else { A[ptr--] = B[bPtr--]; } } if (bPtr != -1) {//NOTICE: IS -1, RATHER THAN 0 System.arraycopy(B,0, A, 0, bPtr + 1); } return; } }
true
611a7b0f7a9f3c370b6b055e881d458bbda42ec7
Java
vishnu021/ZkonceptArt
/core/src/com/zkncpt/zart/actor/ImageActor.java
UTF-8
799
2.828125
3
[]
no_license
package com.zkncpt.zart.actor; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.math.Rectangle; import com.badlogic.gdx.scenes.scene2d.ui.Image; public class ImageActor extends Image { Rectangle bounds; public Pixmap pixmap; public Rectangle getBounds() { return bounds; } public ImageActor(Pixmap pixmap) { super(new Texture(pixmap)); this.pixmap = pixmap; setBounds(getX(), getY(), getWidth(), getHeight()); bounds = new Rectangle((int) getX(), (int) getY(), (int) getWidth(), (int) getHeight()); } public void updateBounds() { bounds.setX(getX()); bounds.setY(getY()); } private int getIndex(int pixel, float[] arr, int length) { int i = 0; while (i < length && pixel > arr[i]) i++; return i; } }
true
cc46f157d26f58889872e8a7ba4db5d6c7f58f86
Java
AnthraX1/basys
/techsupport/src/com/aisino2/publicsystem/dao/IQyryshDao.java
UTF-8
981
1.8125
2
[]
no_license
package com.aisino2.publicsystem.dao; import java.util.List; import java.util.Map; import com.aisino2.core.dao.Page; import com.aisino2.publicsystem.domain.Qyrysh; public interface IQyryshDao { /** @param 企业人员审核(t_qyrysh) 增加 */ Qyrysh insertQyrysh(Qyrysh qyrysh); /** @param 企业人员审核(t_qyrysh) 删除 */ int deleteQyrysh(Qyrysh qyrysh); /** @param 企业人员审核(t_qyrysh) 修改 */ int updateQyrysh(Qyrysh qyrysh); /** @param 企业人员审核(t_qyrysh) 查询单条 */ Qyrysh getQyrysh(Qyrysh qyrysh); /** @param 企业人员审核(t_qyrysh) 分页查询 */ Page getListForPage(Map map, int pageNo,int pageSize,String sort,String desc); /** @param 企业人员审核(t_qyrysh) 多条查询 */ List getListQyrysh(Qyrysh qyrysh); /** @param 从个人员审核信息(t_cyrysh) 获得上级审核id */ Qyrysh getSjshid(Qyrysh qyrysh); /** @param 企业人员审核(t_qyrysh) 修改 */ int updateQyryshByqybg(Qyrysh qyrysh); }
true
9fd52c03ed2a8e90669b6fcb5a2d4c6f406c7d0e
Java
tomy9729/TargetIsPlatinum5
/장정훈/week4/day0803/BJ_1244.java
UTF-8
2,017
3.09375
3
[]
no_license
package week4.day0803; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class BJ_1244 { public static int[] ary; public static void main(String[] args) throws NumberFormatException, IOException { // TODO Auto-generated method stub BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // StringTokenizer st = new StringTokenizer(br.readLine()," "); StringBuilder sb = new StringBuilder(); int x = Integer.parseInt(br.readLine()); ary = new int[x]; StringTokenizer st = new StringTokenizer(br.readLine()," "); for(int i=0; i<x; i++) { ary[i] =Integer.parseInt(st.nextToken()); } int p = Integer.parseInt(br.readLine()); int[][] pAry = new int[p][2]; for(int i=0; i<p; i++) { st = new StringTokenizer(br.readLine()," "); pAry[i][0] = Integer.parseInt(st.nextToken()); pAry[i][1] = Integer.parseInt(st.nextToken()); } for(int i=0; i<pAry.length; i++) { if(pAry[i][0] == 1) { checkM(pAry[i][1]); }else if(pAry[i][0] == 2) { checkW(pAry[i][1]); } } // for(int a: ary) { // sb.append(a).append(" "); // } for(int i=0; i<ary.length; i++) { sb.append(ary[i]); if(i==ary.length-1) { break; } if((i+1)%20==0) { sb.append("\n"); }else { sb.append(" "); } } System.out.print(sb.toString()); } public static void checkM(int i) { for(int j=i-1; j<ary.length; j++) { if((j+1)%i==0) { if(ary[j]==0) { ary[j] =1; }else if(ary[j] ==1) { ary[j] =0; } } } } public static void checkW(int i) { i-=1; for(int j=(i+1),l=(i-1); j<ary.length; j++) { if(l<0 || j>ary.length-1) { break; }else if(ary[j]!=ary[l]) { break; } if(ary[j]==ary[l]) { if(ary[j]==1) { ary[j]=0; ary[l]=0; }else if(ary[j] ==0) { ary[j]=1; ary[l]=1; } } l--; } if(ary[i]==1) { ary[i]=0; }else if(ary[i] ==0) { ary[i]=1; } } }
true
4fe4f42756f718868ad81876fd0b0745e3c14a2f
Java
elouejmajdi/Ticket
/InternshipProject/src/main/java/com/tutorial/app/repostoriy/LicenseRepository.java
UTF-8
278
1.84375
2
[]
no_license
package com.tutorial.app.repostoriy; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import com.tutorial.app.model.License; public interface LicenseRepository extends JpaRepository<License, String> { }
true
d67915ff491a438973ff46f188abe65d17bf35a1
Java
AnOrinaryCabbage/InvisibilityPlus
/src/me/fluglow/invisibilityeffects/PotionParticleHider.java
UTF-8
1,311
2.3125
2
[ "MIT" ]
permissive
package me.fluglow.invisibilityeffects; import me.fluglow.HideSettings; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; import org.bukkit.scheduler.BukkitRunnable; import java.util.UUID; public class PotionParticleHider implements InvisibilityEffect { private final Plugin plugin; public PotionParticleHider(Plugin plugin) { this.plugin = plugin; } @Override public void onPlayerHide(UUID uuid) { Player player = Bukkit.getPlayer(uuid); if(player == null) return; new BukkitRunnable() { @Override public void run() { PotionEffect currEffect = player.getPotionEffect(PotionEffectType.INVISIBILITY); if(currEffect == null) return; PotionEffect newEffect = new PotionEffect(PotionEffectType.INVISIBILITY, currEffect.getDuration(), currEffect.getAmplifier(), currEffect.isAmbient(), false); player.removePotionEffect(PotionEffectType.INVISIBILITY); player.addPotionEffect(newEffect); } }.runTaskLater(plugin, 1L); } @Override public void onPlayerReveal(UUID uuid) { } @Override public HideSettings.HideSetting[] getHidingCases() { return new HideSettings.HideSetting[] { HideSettings.HideSetting.POTION_PARTICLES }; } }
true
855771e6f7b144f77cd388618a2da041244c3de8
Java
DominikBi/TextEditor
/src/main/Text.java
UTF-8
638
2.703125
3
[]
no_license
package src.main; import java.io.File; public class Text { private volatile String text; private volatile File path; private volatile String suffix; public synchronized File getName() { return path; } public synchronized void setName(File path) { this.path = path; } public synchronized String getSuffix() { return suffix; } public synchronized void setSuffix(String suffix) { this.suffix = suffix; } public synchronized String getText(){ return text; } public synchronized void setText(String text){ this.text = text; } }
true
77ef974d5150fbe4404fd236bf84f24f6c4f8c9d
Java
OpenStack-mobile/summit-app-android
/app/src/main/java/org/openstack/android/summit/dagger/modules/PushNotificationsInboxModule.java
UTF-8
5,573
1.8125
2
[ "Apache-2.0" ]
permissive
package org.openstack.android.summit.dagger.modules; import org.openstack.android.summit.common.DTOs.Assembler.IDTOAssembler; import org.openstack.android.summit.common.INavigationParametersStore; import org.openstack.android.summit.common.ISession; import org.openstack.android.summit.common.api.ISummitSelector; import org.openstack.android.summit.common.data_access.repositories.IPushNotificationDataStore; import org.openstack.android.summit.common.data_access.repositories.ISummitDataStore; import org.openstack.android.summit.common.network.IReachability; import org.openstack.android.summit.common.security.ISecurityManager; import org.openstack.android.summit.modules.main.IMainWireframe; import org.openstack.android.summit.modules.push_notifications_inbox.IPushNotificationsWireframe; import org.openstack.android.summit.modules.push_notifications_inbox.PushPushNotificationsWireframe; import org.openstack.android.summit.modules.push_notifications_inbox.business_logic.IPushNotificationDetailInteractor; import org.openstack.android.summit.modules.push_notifications_inbox.business_logic.IPushNotificationsListInteractor; import org.openstack.android.summit.modules.push_notifications_inbox.business_logic.ISettingsInteractor; import org.openstack.android.summit.modules.push_notifications_inbox.business_logic.PushNotificationDetailInteractor; import org.openstack.android.summit.modules.push_notifications_inbox.business_logic.PushNotificationsListInteractor; import org.openstack.android.summit.modules.push_notifications_inbox.user_interface.IPushNotificationDetailPresenter; import org.openstack.android.summit.modules.push_notifications_inbox.user_interface.IPushNotificationDetailView; import org.openstack.android.summit.modules.push_notifications_inbox.user_interface.IPushNotificationDetailWireframe; import org.openstack.android.summit.modules.push_notifications_inbox.user_interface.IPushNotificationsListPresenter; import org.openstack.android.summit.modules.push_notifications_inbox.user_interface.IPushNotificationsListView; import org.openstack.android.summit.modules.push_notifications_inbox.user_interface.PushNotificationDetailFragment; import org.openstack.android.summit.modules.push_notifications_inbox.user_interface.PushNotificationDetailPresenter; import org.openstack.android.summit.modules.push_notifications_inbox.user_interface.PushNotificationDetailWireframe; import org.openstack.android.summit.modules.push_notifications_inbox.user_interface.PushNotificationsListPresenter; import org.openstack.android.summit.modules.push_notifications_inbox.user_interface.PushPushNotificationsListFragment; import dagger.Module; import dagger.Provides; /** * Created by sebastian on 8/19/2016. */ @Module public class PushNotificationsInboxModule { @Provides IPushNotificationsListView providesNotificationsListFragment() { return new PushPushNotificationsListFragment(); } @Provides IPushNotificationDetailView providesPushNotificationDetailFragment() { return new PushNotificationDetailFragment(); } @Provides IPushNotificationsWireframe providesNotificationsWireframe(INavigationParametersStore navigationParametersStore) { return new PushPushNotificationsWireframe(navigationParametersStore); } @Provides IPushNotificationDetailWireframe providesPushNotificationDetailWireframe(IMainWireframe mainWireframe, INavigationParametersStore navigationParametersStore) { return new PushNotificationDetailWireframe(mainWireframe, navigationParametersStore); } @Provides IPushNotificationsListInteractor providesNotificationsListInteractor(ISecurityManager securityManager, IPushNotificationDataStore pushNotificationDataStore, IDTOAssembler dtoAssembler, ISummitDataStore summitDataStore, ISummitSelector summitSelector, ISession session, IReachability reachability) { return new PushNotificationsListInteractor(securityManager, pushNotificationDataStore, dtoAssembler, summitDataStore, summitSelector, session, reachability); } @Provides ISettingsInteractor providesSettingsInteractor (ISecurityManager securityManager, IPushNotificationDataStore pushNotificationDataStore, IDTOAssembler dtoAssembler, ISummitDataStore summitDataStore, ISummitSelector summitSelector, ISession session, IReachability reachability) { return new PushNotificationsListInteractor(securityManager, pushNotificationDataStore, dtoAssembler, summitDataStore, summitSelector, session, reachability); } @Provides IPushNotificationDetailInteractor providesPushNotificationDetailInteractor(ISecurityManager securityManager, IPushNotificationDataStore pushNotificationDataStore, IDTOAssembler dtoAssembler, ISummitDataStore summitDataStore, ISummitSelector summitSelector, IReachability reachability) { return new PushNotificationDetailInteractor(securityManager, pushNotificationDataStore, dtoAssembler, summitDataStore, summitSelector, reachability); } @Provides IPushNotificationsListPresenter providesNotificationsListPresenter(ISecurityManager securityManager, IPushNotificationsListInteractor interactor, IPushNotificationsWireframe wireframe) { return new PushNotificationsListPresenter(securityManager, interactor, wireframe); } @Provides IPushNotificationDetailPresenter providesPushNotificationDetailPresenter(IPushNotificationDetailInteractor interactor, IPushNotificationDetailWireframe wireframe) { return new PushNotificationDetailPresenter(interactor, wireframe); } }
true
0fa8d9eec9f2bb92fb721e3f43712e38f3ff5ca7
Java
buschmais/extended-objects
/neo4j/spi/src/main/java/com/buschmais/xo/neo4j/spi/AbstractNeo4jMetadataFactory.java
UTF-8
5,247
1.90625
2
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
package com.buschmais.xo.neo4j.spi; import java.util.List; import java.util.Map; import com.buschmais.xo.api.XOException; import com.buschmais.xo.neo4j.api.annotation.Batchable; import com.buschmais.xo.neo4j.api.annotation.Label; import com.buschmais.xo.neo4j.api.annotation.Property; import com.buschmais.xo.neo4j.api.annotation.Relation; import com.buschmais.xo.neo4j.api.model.Neo4jLabel; import com.buschmais.xo.neo4j.api.model.Neo4jRelationshipType; import com.buschmais.xo.neo4j.spi.metadata.IndexedPropertyMetadata; import com.buschmais.xo.neo4j.spi.metadata.NodeMetadata; import com.buschmais.xo.neo4j.spi.metadata.PropertyMetadata; import com.buschmais.xo.neo4j.spi.metadata.RelationshipMetadata; import com.buschmais.xo.spi.datastore.DatastoreMetadataFactory; import com.buschmais.xo.api.metadata.method.IndexedPropertyMethodMetadata; import com.buschmais.xo.api.metadata.type.TypeMetadata; import com.buschmais.xo.api.metadata.reflection.AnnotatedElement; import com.buschmais.xo.api.metadata.reflection.AnnotatedMethod; import com.buschmais.xo.api.metadata.reflection.AnnotatedType; import com.buschmais.xo.api.metadata.reflection.PropertyMethod; import com.google.common.base.CaseFormat; /** * {@link com.buschmais.xo.spi.datastore.DatastoreMetadataFactory} * implementation for Neo4j datastores. */ public abstract class AbstractNeo4jMetadataFactory<L extends Neo4jLabel, R extends Neo4jRelationshipType> implements DatastoreMetadataFactory<NodeMetadata<L>, L, RelationshipMetadata<R>, R> { @Override public NodeMetadata createEntityMetadata(AnnotatedType annotatedType, List<TypeMetadata> superTypes, Map<Class<?>, TypeMetadata> metadataByType) { Label labelAnnotation = annotatedType.getAnnotation(Label.class); L label = null; IndexedPropertyMethodMetadata<IndexedPropertyMetadata> indexedProperty = null; if (labelAnnotation != null) { String value = labelAnnotation.value(); if (Label.DEFAULT_VALUE.equals(value)) { value = annotatedType.getName(); } label = createLabel(value); Class<?> usingIndexOf = labelAnnotation.usingIndexedPropertyOf(); if (!Object.class.equals(usingIndexOf)) { TypeMetadata typeMetadata = metadataByType.get(usingIndexOf); indexedProperty = typeMetadata.getIndexedProperty(); } } boolean batchable = isBatchable(annotatedType); return new NodeMetadata<L>(label, indexedProperty, batchable); } @Override public <ImplementedByMetadata> ImplementedByMetadata createImplementedByMetadata(AnnotatedMethod annotatedMethod) { return null; } @Override public <CollectionPropertyMetadata> CollectionPropertyMetadata createCollectionPropertyMetadata(PropertyMethod propertyMethod) { return null; } @Override public <ReferencePropertyMetadata> ReferencePropertyMetadata createReferencePropertyMetadata(PropertyMethod propertyMethod) { return null; } @Override public PropertyMetadata createPropertyMetadata(PropertyMethod propertyMethod) { Property property = propertyMethod.getAnnotation(Property.class); String name = property != null ? property.value() : propertyMethod.getName(); return new PropertyMetadata(name); } @Override public IndexedPropertyMetadata createIndexedPropertyMetadata(PropertyMethod propertyMethod) { return new IndexedPropertyMetadata(); } @Override public RelationshipMetadata<R> createRelationMetadata(AnnotatedElement<?> annotatedElement, Map<Class<?>, TypeMetadata> metadataByType) { Relation relationAnnotation; boolean batchable; if (annotatedElement instanceof PropertyMethod) { relationAnnotation = annotatedElement.getAnnotation(Relation.class); batchable = true; } else if (annotatedElement instanceof AnnotatedType) { AnnotatedType annotatedType = (AnnotatedType) annotatedElement; relationAnnotation = annotatedType.getAnnotation(Relation.class); batchable = annotatedType.getAnnotatedElement().isAnnotation() || isBatchable(annotatedElement); } else { throw new XOException("Annotated element is not supported: " + annotatedElement); } String name = null; if (relationAnnotation != null) { String value = relationAnnotation.value(); if (!Relation.DEFAULT_VALUE.equals(value)) { name = value; } } if (name == null) { name = CaseFormat.UPPER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, annotatedElement.getName()); } return new RelationshipMetadata<>(createRelationshipType(name), batchable); } private boolean isBatchable(AnnotatedElement<?> annotatedElement) { Batchable batchable = annotatedElement.getAnnotation(Batchable.class); return batchable != null ? batchable.value() : isBatchableDefault(); } protected abstract R createRelationshipType(String name); protected abstract L createLabel(String name); protected abstract boolean isBatchableDefault(); }
true
7d132d6b2ed27da5bd3a852f54b606e943b39f98
Java
yzbbanban/yijing
/app/src/main/java/com/huohuo/ui/adapter/SearchFriendAdapter.java
UTF-8
3,868
2.203125
2
[]
no_license
package com.huohuo.ui.adapter; import android.support.annotation.Nullable; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.TextUtils; import android.text.style.ForegroundColorSpan; import android.view.View; import android.widget.TextView; import com.chad.library.adapter.base.BaseQuickAdapter; import com.dian.commonlib.base.BaseMyViewHolder; import com.huohuo.BuildConfig; import com.huohuo.R; import com.huohuo.dao.table.Friend; import java.util.List; /** * Created by kennysun on 2019/9/4. */ public class SearchFriendAdapter extends BaseQuickAdapter<Friend,BaseMyViewHolder> { private String searchKey = ""; public SearchFriendAdapter(int layoutResId, @Nullable List<Friend> data) { super(layoutResId, data); } @Override protected void convert(BaseMyViewHolder helper, Friend item) { helper.loadRoundImage(R.id.ivAvatar, BuildConfig.API_IMG_HOST + item.getHeadImage()); TextView tvName = helper.getView(R.id.tvName); TextView tvSearch = helper.getView(R.id.tvSearch); String remarkName = item.getNickName(); String nickName = item.getNickName(); String account = item.getMobile(); String name = ""; String search = ""; if (TextUtils.isEmpty(remarkName)) { name = nickName; } else { name = remarkName; } if (account.contains(searchKey)) { search = mContext.getResources().getString(R.string.phone_lable) + account; } if (nickName.contains(searchKey)) { search = mContext.getResources().getString(R.string.nickname_lable) + nickName; } ForegroundColorSpan searchKeySpan = new ForegroundColorSpan(mContext.getResources().getColor(R.color.colorAccent)); if (name.contains(searchKey)) {//显示的名字中包含搜索关键字,则不显示二级标题 tvSearch.setVisibility(View.GONE); //设置一级标题的展示 SpannableStringBuilder spannableRemarkName; //昵称不是空,且昵称含有关键字 int searchKeyStart = name.indexOf(searchKey);//关键字的起始位置 int searchKeyEnd = searchKey.length() + searchKeyStart;//关键字的结束位置 if (searchKeyStart != -1) { spannableRemarkName = new SpannableStringBuilder(name); spannableRemarkName.setSpan(searchKeySpan, searchKeyStart, searchKeyEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); tvName.setText(spannableRemarkName); } } else { tvName.setText(name); //设置二级标题的显示 SpannableStringBuilder spannableRemarkSub; if (!TextUtils.isEmpty(search)) { //昵称不是空,且昵称含有关键字 if (search.contains(searchKey)) { tvSearch.setVisibility(View.VISIBLE); int searchKeyStart = search.indexOf(searchKey);//关键字的起始位置 int searchKeyEnd = searchKey.length() + searchKeyStart;//关键字的结束位置 if (searchKeyStart != -1) { spannableRemarkSub = new SpannableStringBuilder(search); spannableRemarkSub.setSpan(searchKeySpan, searchKeyStart, searchKeyEnd, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); tvSearch.setText(spannableRemarkSub); } } else { tvSearch.setVisibility(View.GONE); } } else { tvSearch.setVisibility(View.GONE); } } } /** * 设置搜索的关键字 * * @param trim */ public void setSearchKey(String trim) { searchKey = trim; } }
true
0fb44210baaaa32d8ebdbcd42a50909c6530158a
Java
ChuaKaixin/DrawingApp
/src/main/java/com/app/drawing/Colour.java
UTF-8
80
2.03125
2
[]
no_license
package com.app.drawing; public interface Colour<T> { public T getColour(); }
true
a0ea28b3d6529076cbd519ee42f8f34fd9e87336
Java
ChristianLemke/Mad-Project
/USASurvivalApp/src/com/example/usasurvivalapp/RestaurantFragment.java
UTF-8
4,154
2.359375
2
[]
no_license
package com.example.usasurvivalapp; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import android.app.Fragment; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.*; import android.widget.RadioGroup.OnCheckedChangeListener; public class RestaurantFragment extends Fragment { TextView tips_value; TextView total_value; TextView euro_value; EditText input_restaurant; EditText input_customtip; RadioGroup radioGroup_tips;; RadioButton radio_tip15; RadioButton radio_tip18; RadioButton radio_tip20; RadioButton radio_customTip; /** * The fragment argument representing the section number for this fragment. */ private static final String ARG_SECTION_NUMBER = "section_number"; public static final int ARG_SECTION_NUMBER_RESTAURANT = 3; /** * Returns a new instance of this fragment for the given section number. */ public static RestaurantFragment newInstance() { RestaurantFragment fragment = new RestaurantFragment(); Bundle args = new Bundle(); args.putInt(ARG_SECTION_NUMBER, ARG_SECTION_NUMBER_RESTAURANT); fragment.setArguments(args); return fragment; } public RestaurantFragment() { } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_restaurant, container, false); euro_value = (TextView) rootView.findViewById(R.id.euro_value); total_value = (TextView) rootView.findViewById(R.id.total_value); tips_value = (TextView) rootView.findViewById(R.id.tips_value); radioGroup_tips = (RadioGroup) rootView .findViewById(R.id.radioGroup_tips); radio_tip15 = (RadioButton) rootView.findViewById(R.id.radio_tip15); radio_tip18 = (RadioButton) rootView.findViewById(R.id.radio_tip18); radio_tip20 = (RadioButton) rootView.findViewById(R.id.radio_tip20); input_customtip = (EditText) rootView .findViewById(R.id.input_customtip); radio_customTip = (RadioButton) rootView .findViewById(R.id.radio_customTip); input_restaurant = (EditText) rootView .findViewById(R.id.input_restaurant); input_restaurant.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { calcTotal(); } }); radioGroup_tips .setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { calcTotal(); } }); return rootView; } private void calcTotal() { CurrencyActivity c = new CurrencyActivity(); double currency=c.getOneDollarToXEuro();; System.out.println("currency"+currency); double euro=0; double tip_percent = 0; double tip = 0; double total = -1; double input = -1; try { input = Double.parseDouble(input_restaurant.getText().toString()); } catch (Exception e) { } if (input > 0) { if (radio_tip15.isChecked()) { tip_percent = 15; } else if (radio_tip18.isChecked()) { tip_percent = 18; } else if (radio_tip20.isChecked()) { tip_percent = 20; } else if (radio_customTip.isChecked()) { try { tip_percent = Double.parseDouble(input_customtip.getText() .toString()); } catch (Exception e) { } } if (tip_percent > 0) { tip = input * (tip_percent / 100); } DecimalFormat df = new DecimalFormat("0.00"); tips_value.setText(df.format(tip)); total = input + tip; total_value.setText(df.format(total)); euro = total * currency; euro_value.setText(df.format(euro)); } } }
true
326042ccc1d7cb9196620066bea82f9d9a1fb3ca
Java
gtf1119/testgit
/springMybatis/.svn/pristine/b9/b97f96c09a57c8eac154ffb3a0204e3e74ff9733.svn-base
UTF-8
1,114
2.15625
2
[ "Apache-2.0" ]
permissive
package com.ggg.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ggg.exception.SysException; import com.ggg.mapper.FriendMapper; import com.ggg.pojo.Friend; import com.ggg.pojo.GridCondition; import com.ggg.service.FriendService; @Service public class FriendServiceImpl implements FriendService { @Autowired private FriendMapper friendMapper; public void add(Friend friend) throws SysException { try { friendMapper.add(friend); } catch (Exception e) { throw new SysException("好友添加失败"); } } public List<Friend> queryFriendById(GridCondition condition) throws SysException { List<Friend> friendList = null; try { friendList = friendMapper.queryFriendById(condition); } catch (Exception e) { throw new SysException("还有查询失败"); } return friendList; } public void deleteFriend(Friend friend) throws Exception { try { friendMapper.deleteFriend(friend); } catch (Exception e) { throw new SysException("好友添加失败"); } } }
true
8f4eac944a726e8bf26d9a66b8d398328a466900
Java
Jerry-zhxf/Sale-Management
/Sale/src/org/zhxf/sale/web/CStockAction.java
UTF-8
2,779
2.296875
2
[]
no_license
package org.zhxf.sale.web; //公司库存 import java.util.List; import org.zhxf.sale.domain.Cpy; import org.zhxf.sale.domain.ItemInfo; import org.zhxf.sale.service.CpyService; import org.zhxf.sale.service.ItemInfoService; import org.zhxf.sale.utils.Page; import com.opensymphony.xwork2.ModelDriven; public class CStockAction extends BaseAction implements ModelDriven<Cpy> { private static final long serialVersionUID = -628649677616338668L; private Cpy model = new Cpy(); @Override public Cpy getModel() { return model; } // 分页查询 private Page<Cpy> page = new Page<Cpy>(); public Page<Cpy> getPage() { return page; } public void setPage(Page<Cpy> page) { this.page = page; } private CpyService cpyService; public void setCpyService(CpyService cpyService) { this.cpyService = cpyService; } private ItemInfoService iteminfoService; public void setItemInfoService(ItemInfoService iteminfoService) { this.iteminfoService = iteminfoService; } /** * 分页查询 */ public String list() throws Exception { String hql = "from Cpy"; cpyService.findPage(hql, page, Cpy.class, null); //User是实体 // 设置分页的url地址 page.setUrl("cstockAction_list"); // 将page对象压入栈顶 super.push(page); return "list"; } /** * 查看 */ public String toview() throws Exception { // 1.调用业务方法,根据id,得到对象 Cpy cpy = cpyService.get(Cpy.class, model.getItemNo()); // 放入栈顶 super.push(cpy); // 3.跳页面 return "toview"; } /** * 进入新增页面 */ public String tocreate() throws Exception { List<ItemInfo> iteminfo = iteminfoService.find("from ItemInfo", ItemInfo.class, null); super.put("roles", iteminfo); //提交的名字叫“role” return "tocreate"; } /** * 保存 */ public String insert() throws Exception { cpyService.saveOrUpdate(model); return "alist"; } /** * 进入修改页面 */ public String toupdate() throws Exception { // 1.调用业务方法,根据id,得到对象 Cpy cpy = cpyService.get(Cpy.class, model.getItemNo()); super.push(cpy); List<ItemInfo> iteminfo = iteminfoService.find("from ItemInfo", ItemInfo.class, null); super.put("roles", iteminfo); return "toupdate"; } /** * 修改 */ public String update() throws Exception { // 1.调用业务方法,根据id,得到对象 Cpy cpy = cpyService.get(Cpy.class, model.getItemNo()); cpy.setStockQty(model.getStockQty()); cpyService.saveOrUpdate(cpy); return "alist"; } /** * 删除 */ public String delete() throws Exception { String ids[] = model.getItemNo().split(", "); //调用业务方法,实现批量删除 cpyService.delete(Cpy.class, ids); return "alist"; } }
true
a8539f319c43d319d9f2e97f6bfa05009225eb47
Java
lodi957/E-voting
/Android/SE/app/src/main/java/com/se/httpwww/se/VotingPage.java
UTF-8
858
1.757813
2
[]
no_license
package com.se.httpwww.se; import android.app.ListActivity; import android.os.Bundle; import android.view.View; import android.widget.ListView; /** * Created by Dell on 4/7/2018. */ public class VotingPage extends ListActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_history); VotingPageView MyAdapter = new VotingPageView(this, User.getInstance().votingEventsList); setListAdapter(MyAdapter); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); // BackgroundGetCandidates bgc= new BackgroundGetCandidates(this); // bgc.execute(Info.getInstance().votingEventsList.get(position).getId()); } }
true
351faa40244b9e1e96112d69ca20e55c5640ae41
Java
wxl15/Algorithms
/Part I/Percolation/PercolationStats.java
UTF-8
2,135
3.1875
3
[]
no_license
import edu.princeton.cs.algs4.StdRandom; import edu.princeton.cs.algs4.StdStats; public class PercolationStats { private int trials; private double mean; private double stddev; // perform independent trials on an n-by-n grid public PercolationStats(int n, int trials) { if (n <= 0 || trials <= 0) { throw new IllegalArgumentException("input out of range"); } double[] fractions = new double[trials]; double sites = n * n; this.trials = trials; for (int i = 0; i < trials; i++) { double fraction; Percolation perc = new Percolation(n); while (!perc.percolates()) { int row = StdRandom.uniform(1, n + 1); int col = StdRandom.uniform(1, n + 1); perc.open(row, col); } fraction = perc.numberOfOpenSites() / sites; fractions[i] = fraction; } mean = StdStats.mean(fractions); stddev = StdStats.stddev(fractions); } private double interval() { return (1.96 * stddev()) / Math.sqrt(trials); } // sample mean of percolation threshold public double mean() { return mean; } // sample standard deviation of percolation threshold public double stddev() { return stddev; } // low endpoint of 95% confidence interval public double confidenceLo() { return mean - interval(); } // high endpoint of 95% confidence interval public double confidenceHi() { return mean + interval(); } // test client (see below) public static void main(String[] args) { int n = Integer.parseInt(args[0]); int trials = Integer.parseInt(args[1]); PercolationStats ps = new PercolationStats(n, trials); System.out.println("mean = " + ps.mean()); System.out.println("stddev = " + ps.stddev()); System.out.println("95% confidence interval = " + "[" + ps.confidenceLo() + ", " + ps.confidenceHi() + "]"); } }
true
8e9b46c87a65ac9f054385f747ecf047f191280c
Java
parthi9an/loganalytics
/src/main/java/com/metron/model/Pattern.java
UTF-8
1,502
2.765625
3
[]
no_license
package com.metron.model; import java.util.HashMap; import com.metron.orientdb.OrientUtils; import com.tinkerpop.blueprints.impls.orient.OrientBaseGraph; import com.tinkerpop.blueprints.impls.orient.OrientVertex; /** * Creates a vertex pattern if doesn't exist * @author Metron * */ public class Pattern extends BaseModel { public Pattern(String pattern,OrientBaseGraph graph) { super(graph); this.vertex = find(graph,pattern); if (vertex == null) { this.vertex = graph.addVertex("class:Pattern"); HashMap<String, Object> props = new HashMap<String, Object>(); props.put("pattern_type", pattern); props.put("association_count", 1); this.setProperties(props); this.save(); }else{ int count = this.vertex.getProperty("association_count"); count++; HashMap<String, Object> props = new HashMap<String, Object>(); props.put("association_count", count); this.setProperties(props); this.save(); } } /** * Find the pattern vertex matches patternType * @param graph * @param patternType * @return */ public OrientVertex find(OrientBaseGraph graph, String patternType) { OrientVertex pattern = OrientUtils.getVertex(graph, "select * from Pattern where pattern_type = '" + patternType + "'"); return pattern; } }
true
c4f25acb8b7b5b907cf2299a39be6da945930e65
Java
rrilla/LessonSpring
/diExam/src/main/java/com/hjh/diExam/App3.java
UTF-8
473
2.28125
2
[]
no_license
package com.hjh.diExam; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class App3 { public static void main(String[] args) { ApplicationContext ctx = new ClassPathXmlApplicationContext("bean1.xml"); IMessageBean bean = ctx.getBean("msg1", MessageBean.class); bean.sayHello("한재현"); bean = ctx.getBean("msgKr",IMessageBean.class); bean.sayHello("한재현"); } }
true
923cd5bd475fe9f0fe796920fbd7b02fef9d8a8a
Java
dmitryb-ov/DTBot
/src/main/java/com/example/dtbots/demo/transaction/TransactionManager.java
UTF-8
1,374
2.40625
2
[]
no_license
package com.example.dtbots.demo.transaction; import com.example.dtbots.demo.discord.message.DiscordMessageInviter; import com.example.dtbots.demo.telegram.message.TelegramMessageInviter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import java.lang.annotation.Annotation; public class TransactionManager { private static final String DISCORD_VAL = "discord"; private static final String TELEGRAM_VAL = "telegram"; @Autowired private ApplicationContext applicationContext; public void doTransaction(Class<?> fromClass, String word){ String annotationName = ""; for (Annotation annotation : fromClass.getAnnotations()) { Class<? extends Annotation> type = annotation.annotationType(); annotationName = type.getSimpleName(); if (annotationName.equalsIgnoreCase(TELEGRAM_VAL) || annotationName.equalsIgnoreCase(DISCORD_VAL)) { break; } } if (annotationName.equalsIgnoreCase(TELEGRAM_VAL)) { applicationContext.getBean(DiscordMessageInviter.class).sendAllMessages(word); } if (annotationName.equalsIgnoreCase(DISCORD_VAL)) { applicationContext.getBean(TelegramMessageInviter.class).sendAllTgMessage(word); } } }
true
48c937db3b163520f0e720369086ccb46e654276
Java
CHSOQIWEN/WebTest
/My-First-ServletTest/src/main/java/com/bittech/filter/CounterFilter.java
UTF-8
2,365
2.5
2
[]
no_license
package com.bittech.filter; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * @Author:chaoqiwen * @Date:2019/8/4 11:59 */ public class CounterFilter implements Filter { private File logFile; //适合任务是有序的 private ExecutorService executorService= Executors.newSingleThreadExecutor(); @Override public void init(FilterConfig filterConfig) throws ServletException { String filename=filterConfig.getInitParameter("logging_filename"); String webAppRoot=filterConfig.getServletContext().getRealPath("/"); this.logFile=new File(webAppRoot,filename); if(!this.logFile.exists()){ try { this.logFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } } @Override public void destroy() { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { String url=((HttpServletRequest)servletRequest).getRequestURI(); final File propertiesFile=this.logFile; executorService.execute(new Runnable() { @Override public void run() { Properties properties=new Properties(); try { properties.load(new FileInputStream(propertiesFile)); } catch (IOException e) { e.printStackTrace(); } String value= properties.getProperty(url); if(value==null){ value="1"; }else { value=String.valueOf(Integer.parseInt(value)+1); } properties.setProperty(url,value); try { properties.store(new FileOutputStream(propertiesFile),"update"); } catch (IOException e) { e.printStackTrace(); } } }); filterChain.doFilter(servletRequest,servletResponse); } }
true
a8671baf9e4ac0f34d853cc5407c03576262bfff
Java
zhaiyuyong/shiepApp
/src/cn/edu/shiep/api/HttpDataAccess.java
GB18030
17,624
2.1875
2
[]
no_license
package cn.edu.shiep.api; /** * Ŀ: ϺandroidͻMVC * ļ: HttpDataAccessOperation.java * ļID: * :ͨHttpʽȡݵijʼ * :½˧ * ڣ2011-01-04 * ޸ԭ * ޸ڣ * ޸ˣ * 汾ţV1.0 */ import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.List; import java.util.concurrent.TimeoutException; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.client.params.HttpClientParams; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.conn.params.ConnRoutePNames; import org.apache.http.conn.scheme.PlainSocketFactory; import org.apache.http.conn.scheme.Scheme; import org.apache.http.conn.scheme.SchemeRegistry; import org.apache.http.entity.FileEntity; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.HTTP; import org.apache.http.util.EntityUtils; import cn.edu.shiep.utils.NetUtil; import android.content.Context; /** * HttpDataAccessOperation * Httpӣ÷Ӧ,ʷݵĸ * ģID: * ģƣݷģ * ߣzsg * ڣ2011-01-11 */ public abstract class HttpDataAccess { protected Context context; DefaultHttpClient client;// ͻ˶ String httpMethodStr;// ӷ HttpResponse response;// httpӦ HttpParams httpParams;// Ӳ HttpEntity entity;// httpʵ String urlStr;// httpӵURL HttpGet httpGet;// get HttpPost httpPost;// post List<NameValuePair> postParams;// postӲ HttpHost proxy;// httpӴ String connectionTypeStr;// 뷽ʽ,netwap private boolean isHtttps=false;//Ƿhttps protected DefaultHttpClient getClient() { return client; } protected void setClient(DefaultHttpClient client) { this.client = client; } protected String getHttpMethodStr() { return httpMethodStr; } protected void setHttpMethodStr(String httpMethodStr) { this.httpMethodStr = httpMethodStr; } protected HttpResponse getResponse() { return response; } protected void setResponse(HttpResponse response) { this.response = response; } protected HttpParams getHttpParams() { return httpParams; } protected void setHttpParams(HttpParams httpParams) { this.httpParams = httpParams; } protected HttpEntity getEntity() { return entity; } protected void setEntity(HttpEntity entity) { this.entity = entity; } protected String getUrlStr() { return urlStr; } protected void setUrlStr(String urlStr) { this.urlStr = urlStr; } protected HttpGet getHttpGet() { return httpGet; } protected void setHttpGet(HttpGet httpGet) { this.httpGet = httpGet; } protected HttpPost getHttpPost() { return httpPost; } protected void setHttpPost(HttpPost httpPost) { this.httpPost = httpPost; } protected List<NameValuePair> getPostParams() { return postParams; } protected void setPostParams(List<NameValuePair> postParams) { this.postParams = postParams; } protected HttpHost getProxy() { return proxy; } protected void setProxy(HttpHost proxy) { this.proxy = proxy; } protected String getConnectionTypeStr() { return connectionTypeStr; } protected void setConnectionTypeStr(String connectionTypeStr) { this.connectionTypeStr = connectionTypeStr; } protected boolean isHtttps() { return isHtttps; } protected void setHtttps(boolean isHtttps) { this.isHtttps = isHtttps; } /** * HttpDataAccessOperation * HttpDataAccessOperation * urlStr,HttpӵURL * httpMethodStr,httpӷʽ * connectionTypeStr,뷽ʽ * 쳣 * ֵ * ߣ½˧ * ڣ2011-01-04 */ public HttpDataAccess(String urlStr, String httpMethodStr, String connectionTypeStr,Context context) { this.connectionTypeStr = connectionTypeStr; this.context=context; // if(this.httpParams==null){ this.httpParams = new BasicHttpParams(); // // ӵ200 // ConnManagerParams.setMaxTotalConnections(this.httpParams, 200); // // ÿ·ɵĬӵ20 // ConnPerRouteBean connPerRoute = new ConnPerRouteBean(20); } if(this.isHtttps){ SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443)); schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 8443)); ClientConnectionManager connManager = new ThreadSafeClientConnManager(this.httpParams, schemeRegistry); client = new DefaultHttpClient(connManager,this.httpParams);// ʼͻӶ https뷽ʽ // new IdleConnectionMonitorThread(connManager).start();// ջز }else{ // ǵHttpClient֧HTTPHTTPSģʽ SchemeRegistry schReg = new SchemeRegistry(); schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); // schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443)); // ʹ̰߳ȫӹHttpClient ClientConnectionManager conMgr = new ThreadSafeClientConnManager(this.httpParams, schReg); client = new DefaultHttpClient(conMgr,this.httpParams);// ʼͻӶ // new IdleConnectionMonitorThread(conMgr).start();// ջز } // ResponseHandler<byte[]> handler = new ResponseHandler<byte[]>() { // @Override // public byte[] handleResponse(HttpResponse response) // throws ClientProtocolException, IOException { // HttpEntity entity = response.getEntity(); // if (entity != null) { // return EntityUtils.toByteArray(entity); // } else { // return null; // } // } // }; // client.execute(httpGet, handler);//Ӧ // ط // HttpRequestRetryHandler retryHandler = new HttpRequestRetryHandler() { // @Override // public boolean retryRequest(IOException exception, // int executionCount, HttpContext context) { // // TODO Auto-generated method stub // // ط3 // if (executionCount > 3) { // return false; // } // if (exception instanceof SSLHandshakeException) { // return false; // } // if (exception instanceof NoHttpResponseException) { // return true; // } // HttpRequest request = (HttpRequest) context // .getAttribute(ExecutionContext.HTTP_REQUEST); // boolean idempotent = !(request instanceof HttpEntityEnclosingRequest); // if (idempotent) { // return true; // } else // return false; // } // }; // client.setHttpRequestRetryHandler(retryHandler);// ط httpParams = client.getParams();// Ӳ // Ҫwapwap뷽ʽô if (connectionTypeStr.equals("wap")) { proxy = new HttpHost("10.0.0.200", 80); httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy); } // Ӳ HttpConnectionParams.setConnectionTimeout(httpParams, 20 * 1000); HttpConnectionParams.setSoTimeout(httpParams, 20 * 1000); HttpConnectionParams.setSocketBufferSize(httpParams, 8196); HttpClientParams.setRedirecting(httpParams, true); this.httpMethodStr = httpMethodStr; this.urlStr = urlStr; if (httpMethodStr.equals("get")) { httpGet = new HttpGet(urlStr);// ʼget } if (httpMethodStr.equals("post")) { httpPost = new HttpPost(urlStr);// ʼpost } } /** * getResponse * ÷Ӧ * connectionTypeStr,ķʽ * httpMethod,httpӷʽ * 쳣ClientProtocolException * 쳣IOException쳣ᵼANR * 쳣NullPointerException쳣ᵼANR * ֵӦ * ߣ½˧ * ڣ2011-01-04 */ HttpResponse getResponse(String connectionTypeStr, HttpUriRequest httpMethod) throws ClientProtocolException, NullPointerException, IOException { HttpResponse response = null; if(NetUtil.isConnnected(context)){ //wap if (connectionTypeStr.equals("wap")) { response = client.execute(proxy, httpMethod); } else { //net response = client.execute(httpMethod); } }else{ throw new IOException(); } return response; } /** * getDataByGetMethod * Getӣ÷ַʽ * 쳣ClientProtocolException * 쳣IOException쳣ᵼANR * 쳣NullPointerException쳣ᵼANR * ֵJSONArrayJSONObjectʽַҪһЩListݻij * ߣ½˧ * ڣ2011-01-04 */ public String getDataByGetMethod() throws ClientProtocolException, IOException,TimeoutException, NullPointerException { StringBuilder result = new StringBuilder();//ݵַ if(httpPost!=null){ response = getResponse(connectionTypeStr, httpPost);// Ӧ }else{ response = getResponse(connectionTypeStr, httpGet);// Ӧ } //Ӧ if (response!=null&&response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { entity = response.getEntity(); //תַ if (entity != null) { BufferedReader reader = new BufferedReader( new InputStreamReader(entity.getContent(), HTTP.UTF_8), 8192); String line = null; while ((line = reader.readLine()) != null) { result.append(line + "\n"); } reader.close(); } if (entity != null) { entity.consumeContent(); } } return result.toString(); } /** * getDataByPostMethod * Postӣ÷ַʽ * 쳣ClientProtocolException * 쳣IOException쳣ᵼANR * 쳣NullPointerException쳣ᵼANR * ֵJSONArrayJSONObjectʽַҪһЩListݻij * ߣ½˧ * ڣ2011-01-04 */ public String getDataByPostMethod() throws ClientProtocolException, IOException,TimeoutException, NullPointerException { StringBuilder result = new StringBuilder();//ݵַ HttpEntity httpEntity = new UrlEncodedFormEntity(postParams, HTTP.UTF_8);//ʵ httpPost.setEntity(httpEntity);//ʵ if(httpPost!=null){ response = getResponse(connectionTypeStr, httpPost);// Ӧ }else{ response = getResponse(connectionTypeStr, httpGet);// Ӧ } // if (response!=null&&response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { entity = response.getEntity(); //תַ if (entity != null) { BufferedReader reader = new BufferedReader( new InputStreamReader(entity.getContent(), HTTP.UTF_8), 8192); String line = null; while ((line = reader.readLine()) != null) { result.append(line + "\n"); } reader.close(); } if (entity != null) { entity.consumeContent(); } } return result.toString(); } /** * getDataByPostSendString * Post,ַĸʽ˽ݷͣ÷ַʽ * 쳣ClientProtocolException * 쳣IOException쳣ᵼANR * 쳣NullPointerException쳣ᵼANR * ֵJSONArrayJSONObjectʽַҪһЩListݻij * ߣzsg * ڣ2011-01-04 */ public String getDataByPostSendString(String msg) throws ClientProtocolException, IOException,TimeoutException, NullPointerException { StringBuilder result = new StringBuilder();//ݵַ HttpEntity httpEntity = new StringEntity(msg,HTTP.UTF_8);//ʵ httpPost.setEntity(httpEntity);//ʵ if(httpPost!=null){ response = getResponse(connectionTypeStr, httpPost);// Ӧ }else{ response = getResponse(connectionTypeStr, httpGet);// Ӧ } // if (response!=null&&response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { entity = response.getEntity(); //תַ if (entity != null) { BufferedReader reader = new BufferedReader( new InputStreamReader(entity.getContent(), HTTP.UTF_8), 8192); String line = null; while ((line = reader.readLine()) != null) { result.append(line + "\n"); } reader.close(); } if (entity != null) { entity.consumeContent(); } } return result.toString(); } /** * ļϴ * @param file * @return * @throws ClientProtocolException * @throws TimeoutException * @throws NullPointerException * @throws IOException */ public String UploadFile(File file)throws ClientProtocolException,TimeoutException,NullPointerException, IOException { FileEntity reqEntity = new FileEntity(file, "binary/octet-stream"); httpPost.setEntity(reqEntity); String result=null; reqEntity.setContentType("binary/octet-stream"); System.out.println("executing request " + httpPost.getRequestLine()); if(httpPost!=null){ response = getResponse(connectionTypeStr, httpPost);// Ӧ }else{ response = getResponse(connectionTypeStr, httpGet);// Ӧ } // Ӧ if (response!=null&&response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity resEntity = response.getEntity(); if (resEntity != null) { result= EntityUtils.toString(resEntity); resEntity.consumeContent(); } }else{ result="fileFailure";//ļϴʧ } return result; } /** * getFileStream * ӷļ * fileNameStr,ļ * fileExtensionsStr,ļչ * 쳣ClientProtocolException ͻ쳣 * 쳣IOException쳣ᵼANR * 쳣NullPointerException쳣ᵼANR * ֵļļڴ洢ļ * ߣzsg * ڣ2011-01-04 */ public File getFileStream(String fileLoacation,String fileNameStr) throws ClientProtocolException, NullPointerException, IOException,TimeoutException{ if(httpPost!=null){ response = getResponse(connectionTypeStr, httpPost);// Ӧ }else{ response = getResponse(connectionTypeStr, httpGet);// Ӧ } File tempFile = new File(fileLoacation, fileNameStr);//ļ //Ӧ if (response!=null&&response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { InputStream is = response.getEntity().getContent(); // ļ FileOutputStream fileStream = new FileOutputStream(tempFile); byte[] buf = new byte[HttpConnectionParams .getSocketBufferSize(httpParams)]; int size = 0; // ļתֽ while ((size = is.read(buf)) != -1) { fileStream.write(buf, 0, size); } fileStream.close(); is.close(); if (entity != null) { entity.consumeContent(); } } return tempFile; } /** * ĿƣPFWX_PAD * ƣIdleConnectionMonitorThread * ThreadSafeClientConnManagerõջز * ˣzsg * ʱ䣺2012-8-14 */ public static class IdleConnectionMonitorThread extends Thread { private final ClientConnectionManager connMgr; private volatile boolean shutdown; public IdleConnectionMonitorThread(ClientConnectionManager connMgr) { super(); this.connMgr = connMgr; } @Override public void run() { try { while (!shutdown) { synchronized (this) { wait(5000); // رչ connMgr.closeExpiredConnections(); // ѡأرտг30 // connMgr.closeIdleConnections(30, TimeUnit.SECONDS); } } } catch (InterruptedException ex) { // ֹ shutdown(); } } public void shutdown() { shutdown = true; synchronized (this) { this.notify(); } } } }
true
c7a8421a67f9788e7d8a6827e198ca98c4e667c1
Java
jins040/hello
/src/majorleague2/service/ParkService.java
UTF-8
1,091
2.625
3
[]
no_license
package majorleague2.service; import majorleague2.model.Park; import java.util.ArrayList; import java.util.List; /** * Created by danawacomputer on 2017-04-10. */ public class ParkService implements IParkService { // 2번 public int countingNumOfNoneUS(List<Park> list) { int countNum = 0; for (Park e : list) { if(e.getCountry().equals("US")) { } else{ countNum++; } } return countNum; } // 3번 public List<String> findParkHavingAlias(List<Park> list) { List<String> listHavingAlias = new ArrayList<>(); for (Park e : list) { if(e.getParkAlias().equals("")) { } else{ listHavingAlias.add(e.getParkName()); } } return listHavingAlias; } // 4번 public double averageOfParkNameNum(List<Park> list) { int totalSum = 0; for (Park e : list) { totalSum += e.getParkName().length(); } return (double)totalSum / list.size(); } }
true
caad165540dd3022550637c821ff1b5cd38c3a82
Java
luisblazquezm/usal-gii-3-corteIngles-JADE-agentes
/CorteIngles/src/utilities/Debug.java
ISO-8859-1
543
2.9375
3
[]
no_license
/** * @author mrhyd * * Dummy class, created to emulate conditional compilation * */ package utilities; /** * @author Luis Blzquez Miambres y Samuel Gmez Snchez * */ public final class Debug { // Set to true or false depending on whether prints are wanted or not public static final boolean IS_ON = false; public static void message(String message) { if (Debug.IS_ON) System.out.println(message); } public static void formattedMessage(String format, Object... args) { if (Debug.IS_ON) System.out.printf(format, args); } }
true
93d8cddec5761ed72f7dfb9aef6ec39dd012e902
Java
Denikurumoff/firstproject
/oop_calculator/Operator.java
UTF-8
1,035
3.078125
3
[]
no_license
package oop_calculator; import java.util.Scanner; public class Operator implements interface_vvoda { private String operand_1; Scanner scanner = new Scanner(System.in); public String getOperand_1() { return operand_1; } public void setOperand_1(String operand_1) { this.operand_1 = operand_1; } public Scanner getScanner() { return scanner; } public void vvedi() { System.out.println("Какую операцию вы хотите совершить? "); while (true) { operand_1 = scanner.next(); if (!(operand_1.equals("+")) && !(operand_1.equals("-")) && !(operand_1.equals("*")) && !(operand_1.equals("/"))) { System.out.println("Выбранная вами функция не реализована в рамках данного калькулятора! Введите что-то еще"); scanner = new Scanner(System.in); } else break; } } }
true
b8ea6c3fdc3b90617145b59df6e5003936b750c7
Java
Alluxio/alluxio
/dora/tests/integration/src/main/java/alluxio/master/backcompat/ops/UpdateUfsMode.java
UTF-8
1,708
1.96875
2
[ "MIT", "EPL-1.0", "LicenseRef-scancode-proprietary-license", "CC0-1.0", "Apache-2.0", "Unlicense", "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause", "LicenseRef-scancode-free-unknown", "BSD-3-Clause", "CC-PDDC", "LicenseRef-scancode-public-domain" ]
permissive
/* * The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 * (the "License"). You may not use this work except in compliance with the License, which is * available at www.apache.org/licenses/LICENSE-2.0 * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied, as more fully set forth in the License. * * See the NOTICE file distributed with this work for information regarding copyright ownership. */ package alluxio.master.backcompat.ops; import static org.junit.Assert.assertFalse; import alluxio.AlluxioURI; import alluxio.client.file.FileSystemMasterClient; import alluxio.grpc.UfsPMode; import alluxio.grpc.UpdateUfsModePOptions; import alluxio.master.backcompat.TestOp; import alluxio.multi.process.Clients; /** * Test for updating UFS modes. */ public final class UpdateUfsMode implements TestOp { @Override public void apply(Clients clients) throws Exception { FileSystemMasterClient masterClient = clients.getFileSystemMasterClient(); masterClient.updateUfsMode(new AlluxioURI("/"), UpdateUfsModePOptions.newBuilder().setUfsMode(UfsPMode.READ_ONLY).build()); masterClient.updateUfsMode(new AlluxioURI("/"), UpdateUfsModePOptions.newBuilder().setUfsMode(UfsPMode.NO_ACCESS).build()); masterClient.updateUfsMode(new AlluxioURI("/"), UpdateUfsModePOptions.newBuilder().setUfsMode(UfsPMode.READ_WRITE).build()); } @Override public void check(Clients clients) throws Exception { FileSystemMasterClient masterClient = clients.getFileSystemMasterClient(); assertFalse(masterClient.getMountTable().get("/").getReadOnly()); } }
true
2e5785ee5d93526dccf9f627c38805f8bf01c2fe
Java
HausemasterIssue/novoline
/src/de/gerrygames/viarewind/utils/math/AABB.java
UTF-8
371
2.515625
3
[ "Unlicense" ]
permissive
package de.gerrygames.viarewind.utils.math; import de.gerrygames.viarewind.utils.math.Vector3d; public class AABB { Vector3d min; Vector3d max; public AABB(Vector3d var1, Vector3d var2) { this.min = var1; this.max = var2; } public Vector3d getMin() { return this.min; } public Vector3d getMax() { return this.max; } }
true
abfdb5b4beeffdfcd94200a8e43c280d40f53266
Java
alumichael/EmergencyNotifyPrivate
/app/src/main/java/com/mikelearning/projecttest/fcm/MyFirebaseMessagingService.java
UTF-8
4,957
2
2
[]
no_license
package com.mikelearning.projecttest.fcm; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.media.RingtoneManager; import android.net.Uri; import android.util.Log; import androidx.core.app.NotificationCompat; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.messaging.FirebaseMessagingService; import com.google.firebase.messaging.RemoteMessage; import com.mikelearning.projecttest.Constant; import com.mikelearning.projecttest.EmergencyChatApp; import com.mikelearning.projecttest.NotificationHome; import com.mikelearning.projecttest.R; import com.mikelearning.projecttest.Utils.UserPreferences; import com.mikelearning.projecttest.events.PushNotificationEvent; public class MyFirebaseMessagingService extends FirebaseMessagingService { private static final String TAG = "MyFirebaseMsgService"; @Override public void onNewToken(String token) { String string_token = "Refreshed token: " + token; Log.d(TAG, string_token); sendRegistrationToServer(token); } private void sendRegistrationToServer(final String token) { UserPreferences sharedPrefUtil = new UserPreferences(getApplicationContext()); String str = Constant.ARG_FIREBASE_TOKEN; sharedPrefUtil.saveString(str, token); if (FirebaseAuth.getInstance().getCurrentUser() != null) { if(sharedPrefUtil.getUserType().equals("Emergency-Office")){ FirebaseDatabase.getInstance().getReference().child(Constant.ARG_ORGS) .child(FirebaseAuth.getInstance().getCurrentUser().getEmail()) .child(str) .setValue(token); }else{ FirebaseDatabase.getInstance().getReference().child(Constant.ARG_USERS) .child(FirebaseAuth.getInstance().getCurrentUser().getEmail()) .child(str) .setValue(token); } } } @Override public void onMessageReceived(RemoteMessage remoteMessage) { // TODO(developer): Handle FCM messages here. // Not getting messages here? See why this may be: https://goo.gl/39bRNJ Log.d(TAG, "From: " + remoteMessage.getFrom()); // Check if message contains a data payload. if (remoteMessage.getData().size() > 0) { Log.d(TAG, "Message data payload: " + remoteMessage.getData()); String title = remoteMessage.getData().get(Constant.POST_TILE); String message = remoteMessage.getData().get("text"); String email = remoteMessage.getData().get("email"); String fcmToken = remoteMessage.getData().get("fcm_token"); String firstname = remoteMessage.getData().get("firstname"); String lastname = remoteMessage.getData().get("lastname"); String next_of_kin_num = remoteMessage.getData().get("next_kin_num"); if (!EmergencyChatApp.isNotificationActivityOpen()) { sendNotification( firstname, lastname, next_of_kin_num, title, message, email, fcmToken); }else { new PushNotificationEvent( firstname, lastname, next_of_kin_num, title, message, email, fcmToken); } } } private void sendNotification(String firstname,String lastname,String nextof_kin_num,String title,String message,String email,String firebaseToken) { Intent intent = new Intent(this, NotificationHome.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT); Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,"channel_emergency") .setSmallIcon(R.drawable.ic_account_circle_black_24dp) .setContentTitle(title) .setContentText(message+"\n"+"Name: "+firstname+" "+lastname+"\n"+"Next of Kin No: "+nextof_kin_num) .setAutoCancel(true) .setSound(defaultSoundUri) .setContentIntent(pendingIntent); NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(0, notificationBuilder.build()); } }
true
9da751a273ca734fd26f6e7ab664c7c8e6ab969e
Java
trantuyen/cloud-backend
/modules/common/websocket/src/main/java/io/theshire/common/websocket/configuration/WebsocketConfigurer.java
UTF-8
5,073
1.835938
2
[]
no_license
package io.theshire.common.websocket.configuration; import io.theshire.common.websocket.interceptor.SecuredChannelInterceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.messaging.converter.MessageConverter; import org.springframework.messaging.handler.invocation.HandlerMethodArgumentResolver; import org.springframework.messaging.handler.invocation.HandlerMethodReturnValueHandler; import org.springframework.messaging.simp.config.ChannelRegistration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker; import org.springframework.web.socket.config.annotation.StompEndpointRegistry; import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; import org.springframework.web.socket.config.annotation.WebSocketTransportRegistration; import org.springframework.web.socket.server.HandshakeInterceptor; import java.util.List; //Topics //In JMS a Topic implements publish and subscribe semantics. // When you publish a message it goes to all the subscribers who are interested - // so zero to many subscribers will receive a // copy of the message. Only subscribers who had an active subscription // at the time the broker receives // the message will get a // copy of the message. //Queues //A JMS Queue implements load balancer semantics. A single message // will be received by exactly one consumer. // If there are no consumers available at the time the message is sent it will be kept // until a consumer is available that can process the message. If a consumer receives a // message and does not acknowledge it before closing then the message will be // redelivered to another consumer. A queue can have many consumers with // messages load balanced across the available consumers. // So Queues implement a reliable load balancer in JMS. @Configuration @EnableWebSocketMessageBroker @Import({ WebsocketAuthenticationManager.class, WebSocketSessionContainerImpl.class }) public class WebsocketConfigurer implements WebSocketMessageBrokerConfigurer { @Value("${app.cloud.websockets.mq.userelay}") private String useStompRelay; @Value("${app.cloud.websockets.mq.relay.login}") private String relayLogin; @Value("${app.cloud.websockets.mq.relay.passcode}") private String relayPasscode; @Value("${app.cloud.websockets.mq.relay.host}") private String relayHost; @Value("${app.cloud.websockets.mq.relay.port}") private String relayPort; @Value("${app.cloud.websockets.mq.connect.path}") private String connectPath; @Value("${app.cloud.security.cors.allowedOrigin}") private String allowedOrigin; @Autowired private HandshakeInterceptor handshakeInterceptor; @Autowired private WebSocketSessionContainerImpl sessionContainer; @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint(connectPath).addInterceptors(handshakeInterceptor) .setAllowedOrigins(allowedOrigin); } @Override public void configureMessageBroker(MessageBrokerRegistry registry) { // all calls to /app means that the query to the broker will be processed with the java // application before going to the message broker (security purposes) registry.setApplicationDestinationPrefixes("/app"); registry.setUserDestinationPrefix("/user"); if ("true".equals(useStompRelay)) { registry.enableStompBrokerRelay("/queue", "/topic").setClientLogin(relayLogin) .setSystemLogin(relayLogin).setClientPasscode(relayPasscode) .setSystemPasscode(relayPasscode).setRelayHost(relayHost) .setRelayPort(Integer.parseInt(relayPort)); } else { registry.enableSimpleBroker("/queue", "/topic"); } } @Override public void configureWebSocketTransport(WebSocketTransportRegistration registry) { registry.setDecoratorFactories( wsHandler -> new CustomWebsocketHandlerDecorator(sessionContainer, wsHandler)); } @Override public void configureClientInboundChannel(ChannelRegistration registration) { registration.setInterceptors(new SecuredChannelInterceptor()); } @Override public void configureClientOutboundChannel(ChannelRegistration registration) { registration.setInterceptors(new SecuredChannelInterceptor()); } @Override public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { } @Override public void addReturnValueHandlers(List<HandlerMethodReturnValueHandler> returnValueHandlers) { } @Override public boolean configureMessageConverters(List<MessageConverter> messageConverters) { return true; } }
true
3cdfd64c0df5400c60f27aad80e103a9769e2337
Java
Balta-Stefan/Web-shop
/src/main/java/webStore/model/Product_review.java
UTF-8
708
2.46875
2
[]
no_license
package webStore.model; public class Product_review { public int review_ID, product_ID, customer_ID; public byte grade; public String comment; public Product_review(int review_ID, byte grade, String comment, int product_ID, int customer_ID) { this.review_ID = review_ID; this.product_ID = product_ID; this.customer_ID = customer_ID; this.grade = grade; this.comment = comment; } public Product_review(byte grade, String comment, int product_ID, int customer_ID) { this.product_ID = product_ID; this.customer_ID = customer_ID; this.grade = grade; this.comment = comment; } }
true
133b4080e94699f1dd70661f0b396d7f735da688
Java
sophiabuell/fdb-record-layer
/fdb-record-layer-lucene/src/main/java/com/apple/foundationdb/record/lucene/synonym/SynonymAnalyzer.java
UTF-8
4,747
1.867188
2
[ "Apache-2.0" ]
permissive
/* * SynonymAnalyzer.java * * This source file is part of the FoundationDB open source project * * Copyright 2015-2021 Apple Inc. and the FoundationDB project authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.apple.foundationdb.record.lucene.synonym; import com.apple.foundationdb.record.RecordCoreException; import com.apple.foundationdb.record.lucene.LuceneAnalyzerFactory; import com.apple.foundationdb.record.metadata.Index; import com.google.auto.service.AutoService; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.CharArraySet; import org.apache.lucene.analysis.LowerCaseFilter; import org.apache.lucene.analysis.StopFilter; import org.apache.lucene.analysis.StopwordAnalyzerBase; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.analysis.core.FlattenGraphFilter; import org.apache.lucene.analysis.standard.StandardAnalyzer; import org.apache.lucene.analysis.standard.StandardTokenizer; import org.apache.lucene.analysis.synonym.SynonymGraphFilter; import org.apache.lucene.analysis.synonym.SynonymMap; import org.apache.lucene.analysis.synonym.WordnetSynonymParser; import javax.annotation.Nonnull; import javax.annotation.Nullable; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.text.ParseException; /** * The analyzer for index with synonym enabled. * Only for in fly analysis during query time. * The synonyms are not indexed to disk. So no index rebuilding is needed if the wordnet file gets updated. */ public class SynonymAnalyzer extends StopwordAnalyzerBase { private static final String WORDNET_FILE_NAME = "wn_s.pl"; @Nullable private SynonymMap cachedSynonymMap = null; public SynonymAnalyzer(@Nullable CharArraySet stopwords) { super(stopwords); } @Override protected TokenStreamComponents createComponents(String fieldName) { final StandardTokenizer src = new StandardTokenizer(); TokenStream tok = new LowerCaseFilter(src); tok = new StopFilter(tok, stopwords); tok = new SynonymGraphFilter(tok, getSynonymMap(), true); return new TokenStreamComponents(src, tok); } @Override protected TokenStream normalize(String fieldName, TokenStream in) { return new LowerCaseFilter(in); } @Nonnull private SynonymMap getSynonymMap() { if (cachedSynonymMap == null) { cachedSynonymMap = buildSynonymMap(); } return cachedSynonymMap; } private static SynonymMap buildSynonymMap() { try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(WORDNET_FILE_NAME)) { WordnetSynonymParser parser = new WordnetSynonymParser(true, true, new Analyzer() { @Override protected TokenStreamComponents createComponents(String fieldName) { final StandardTokenizer src = new StandardTokenizer(); TokenStream tok = new LowerCaseFilter(src); tok = new FlattenGraphFilter(tok); return new TokenStreamComponents(src, tok); } }); parser.parse(new InputStreamReader(is, "UTF-8")); return parser.build(); } catch (IOException | ParseException ex) { throw new RecordCoreException("Failed to parse wordnet for synonym analyzer", ex); } } @AutoService(LuceneAnalyzerFactory.class) public static class SynonymAnalyzerFactory implements LuceneAnalyzerFactory { public static final String ANALYZER_NAME = "SYNONYM"; @Nonnull @Override public String getName() { return ANALYZER_NAME; } @SuppressWarnings("deprecation") @Nonnull @Override public Analyzer getIndexAnalyzer(@Nonnull Index index) { return new StandardAnalyzer(); } @SuppressWarnings("deprecation") @Nonnull @Override public Analyzer getQueryAnalyzer(@Nonnull Index index, @Nonnull Analyzer indexAnalyzer) { return new SynonymAnalyzer(StandardAnalyzer.STOP_WORDS_SET); } } }
true
8537104bba708b6afa95b757f5705ea6e4afbdcf
Java
ZPavel/spring-angular-jwt
/src/main/java/com/zpavel/service/impl/UserServiceImpl.java
UTF-8
712
2.09375
2
[]
no_license
package com.zpavel.service.impl; import com.zpavel.model.AppUser; import com.zpavel.repository.UserRepository; import com.zpavel.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; @Service public class UserServiceImpl implements UserService { @Autowired private UserRepository userRepository; @Override public AppUser findByUsername(String u) throws UsernameNotFoundException { return userRepository.findByUsername(u); } @Override public AppUser save(AppUser u) { return userRepository.save(u); } }
true
b77ca51a9dd69f95939318e15287b64e21ffef17
Java
ent-chirag/Cpewebinar-Latest
/app/src/main/java/com/entigrity/fragments/MyCreditsFragment.java
UTF-8
18,762
1.78125
2
[]
no_license
package com.entigrity.fragments; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.databinding.DataBindingUtil; import android.graphics.Typeface; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AlertDialog; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.entigrity.MainActivity; import com.entigrity.R; import com.entigrity.adapter.MyCreditAdapter; import com.entigrity.databinding.FragmentMycreditBinding; import com.entigrity.model.My_Credit.MyCreditsItem; import com.entigrity.model.My_Credit.My_Credit; import com.entigrity.utility.AppSettings; import com.entigrity.utility.Constant; import com.entigrity.view.DialogsUtils; import com.entigrity.view.SimpleDividerItemDecoration; import com.entigrity.webservice.APIService; import com.entigrity.webservice.ApiUtilsNew; import java.util.ArrayList; import java.util.List; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; public class MyCreditsFragment extends Fragment { View view; public Context context; FragmentMycreditBinding binding; MyCreditAdapter adapter; private APIService mAPIService; Typeface font; public int filter_type = 0; ProgressDialog progressDialog; LinearLayoutManager linearLayoutManager; private List<MyCreditsItem> mlistmycredit = new ArrayList<MyCreditsItem>(); public int start = 0, limit = 10; private boolean loading = true; public boolean islast = false; private static final String TAG = MyCreditsFragment.class.getName(); @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { binding = DataBindingUtil.inflate(inflater, R.layout.fragment_mycredit, null, false); context = getActivity(); mAPIService = ApiUtilsNew.getAPIService(); font = Typeface.createFromAsset(getActivity().getAssets(), "Montserrat-Light.ttf"); linearLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false); binding.recyclerviewMycredit.setLayoutManager(linearLayoutManager); binding.recyclerviewMycredit.addItemDecoration(new SimpleDividerItemDecoration(context)); binding.recyclerviewMycredit.setItemAnimator(new DefaultItemAnimator()); binding.recyclerviewMycredit.setHasFixedSize(true); if (Constant.isNetworkAvailable(context)) { progressDialog = DialogsUtils.showProgressDialog(context, getResources().getString(R.string.progrees_msg)); GetMyCredit(start, limit); } else { Snackbar.make(getActivity().findViewById(android.R.id.content), getResources().getString(R.string.please_check_internet_condition), Snackbar.LENGTH_SHORT).show(); } binding.lvCompleted.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { binding.lvCompleted.setBackgroundColor(getResources().getColor(R.color.webinar_status)); binding.lvPending.setBackgroundColor(0); binding.lvUpcoming.setBackgroundColor(0); binding.tvCompltedWebinarCount.setTextColor(getResources().getColor(R.color.White)); binding.tvCompleted.setTextColor(getResources().getColor(R.color.White)); binding.tvPendingWebinarCount.setTextColor(getResources().getColor(R.color.my_credit_webinar_report)); binding.tvPending.setTextColor(getResources().getColor(R.color.my_credit_webinar_report)); binding.tvUpcomingWebinarCount.setTextColor(getResources().getColor(R.color.my_credit_webinar_report)); binding.tvUpcoming.setTextColor(getResources().getColor(R.color.my_credit_webinar_report)); filter_type = 1; start = 0; limit = 10; loading = true; if (Constant.isNetworkAvailable(context)) { progressDialog = DialogsUtils.showProgressDialog(context, getResources().getString(R.string.progrees_msg)); GetMyCredit(start, limit); } else { Snackbar.make(binding.recyclerviewMycredit, getResources().getString(R.string.please_check_internet_condition), Snackbar.LENGTH_SHORT).show(); } } }); binding.lvPending.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { binding.lvPending.setBackgroundColor(getResources().getColor(R.color.webinar_status)); binding.lvCompleted.setBackgroundColor(0); binding.lvUpcoming.setBackgroundColor(0); binding.tvCompltedWebinarCount.setTextColor(getResources().getColor(R.color.my_credit_webinar_report)); binding.tvCompleted.setTextColor(getResources().getColor(R.color.my_credit_webinar_report)); binding.tvPendingWebinarCount.setTextColor(getResources().getColor(R.color.White)); binding.tvPending.setTextColor(getResources().getColor(R.color.White)); binding.tvUpcomingWebinarCount.setTextColor(getResources().getColor(R.color.my_credit_webinar_report)); binding.tvUpcoming.setTextColor(getResources().getColor(R.color.my_credit_webinar_report)); filter_type = 2; start = 0; limit = 10; loading = true; if (Constant.isNetworkAvailable(context)) { progressDialog = DialogsUtils.showProgressDialog(context, getResources().getString(R.string.progrees_msg)); GetMyCredit(start, limit); } else { Snackbar.make(binding.recyclerviewMycredit, getResources().getString(R.string.please_check_internet_condition), Snackbar.LENGTH_SHORT).show(); } } }); binding.lvUpcoming.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { binding.lvUpcoming.setBackgroundColor(getResources().getColor(R.color.webinar_status)); binding.lvCompleted.setBackgroundColor(0); binding.lvPending.setBackgroundColor(0); binding.tvCompltedWebinarCount.setTextColor(getResources().getColor(R.color.my_credit_webinar_report)); binding.tvCompleted.setTextColor(getResources().getColor(R.color.my_credit_webinar_report)); binding.tvPendingWebinarCount.setTextColor(getResources().getColor(R.color.my_credit_webinar_report)); binding.tvPending.setTextColor(getResources().getColor(R.color.my_credit_webinar_report)); binding.tvUpcomingWebinarCount.setTextColor(getResources().getColor(R.color.White)); binding.tvUpcoming.setTextColor(getResources().getColor(R.color.White)); filter_type = 3; start = 0; limit = 10; loading = true; if (Constant.isNetworkAvailable(context)) { progressDialog = DialogsUtils.showProgressDialog(context, getResources().getString(R.string.progrees_msg)); GetMyCredit(start, limit); } else { Snackbar.make(binding.recyclerviewMycredit, getResources().getString(R.string.please_check_internet_condition), Snackbar.LENGTH_SHORT).show(); } } }); binding.swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { refreshItems(); } }); binding.recyclerviewMycredit.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { if (loading) { if (!islast) { if (isLastVisible()) { loading = false; start = start + 10; limit = 10; loadNextPage(); } } } } }); binding.getRoot().setFocusableInTouchMode(true); binding.getRoot().requestFocus(); binding.getRoot().setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) { ConfirmationPopup(); return true; } return false; } }); return view = binding.getRoot(); } @Override public void onResume() { super.onResume(); if (Constant.isdataupdate) { Constant.isdataupdate = false; if (Constant.isNetworkAvailable(context)) { progressDialog = DialogsUtils.showProgressDialog(context, getResources().getString(R.string.progrees_msg)); GetMyCredit(start, limit); } else { Snackbar.make(getActivity().findViewById(android.R.id.content), getResources().getString(R.string.please_check_internet_condition), Snackbar.LENGTH_SHORT).show(); } } } @Override public void onDetach() { super.onDetach(); if (adapter != null) { adapter.unregister(getActivity()); } } private void loadNextPage() { if (Constant.isNetworkAvailable(context)) { binding.progressBar.setVisibility(View.VISIBLE); GetMyCredit(start, limit); } else { Snackbar.make(getActivity().findViewById(android.R.id.content), getResources().getString(R.string.please_check_internet_condition), Snackbar.LENGTH_SHORT).show(); } } public void refreshItems() { onItemsLoadComplete(); } void onItemsLoadComplete() { start = 0; limit = 10; loading = true; if (Constant.isNetworkAvailable(context)) { GetMyCredit(start, limit); } else { Snackbar.make(getActivity().findViewById(android.R.id.content), getResources().getString(R.string.please_check_internet_condition), Snackbar.LENGTH_SHORT).show(); } } public void ConfirmationPopup() { AlertDialog.Builder alertDialog = new AlertDialog.Builder(context); // Setting Dialog Title // alertDialog.setTitle("Confirm Delete..."); // Setting Dialog Message alertDialog.setMessage(getResources().getString(R.string.exit_validation)); // Setting Positive "Yes" Button alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Write your code here to invoke YES event dialog.cancel(); getActivity().finish(); } }); // Setting Negative "NO" Button alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Write your code here to invoke NO event dialog.cancel(); } }); // Showing Alert Message alertDialog.show(); } private void GetMyCredit(final int start, final int limit) { mAPIService.GetMyCredit(getResources().getString(R.string.accept), getResources().getString(R.string.bearer) + " " + AppSettings.get_login_token(context), filter_type , start, limit).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) .subscribe(new Subscriber<My_Credit>() { @Override public void onCompleted() { if (binding.progressBar.getVisibility() == View.VISIBLE) { binding.progressBar.setVisibility(View.GONE); } loading = true; if (start == 0 && limit == 10) { if (mlistmycredit.size() > 0) { adapter = new MyCreditAdapter(context, mlistmycredit); binding.recyclerviewMycredit.setAdapter(adapter); } } else { adapter.addLoadingFooter(); } } @Override public void onError(Throwable e) { if (start == 0 && limit == 10) { if (progressDialog.isShowing()) { progressDialog.dismiss(); } } else { if (binding.progressBar.getVisibility() == View.VISIBLE) { binding.progressBar.setVisibility(View.GONE); } } String message = Constant.GetReturnResponse(context, e); if (Constant.status_code == 401) { MainActivity.getInstance().AutoLogout(); } else { Snackbar.make(binding.ivnotification, message, Snackbar.LENGTH_SHORT).show(); } } @Override public void onNext(My_Credit myCredit) { if (myCredit.isSuccess() == true) { if (progressDialog.isShowing()) { progressDialog.dismiss(); } else { if (binding.swipeRefreshLayout.isRefreshing()) { binding.swipeRefreshLayout.setRefreshing(false); } } if (start == 0 && limit == 10) { if (mlistmycredit.size() > 0) { mlistmycredit.clear(); } } islast = myCredit.getPayload().get(0).isIslast(); if (start == 0 && limit == 10) { for (int i = 0; i < myCredit.getPayload().size(); i++) { mlistmycredit = myCredit.getPayload().get(i).getMyCredits(); } } else { if (mlistmycredit.size() > 20) { mlistmycredit.remove(mlistmycredit.size() - 1); } List<MyCreditsItem> webinaritems = new ArrayList<>(); for (int i = 0; i < myCredit.getPayload().size(); i++) { webinaritems = myCredit.getPayload().get(i).getMyCredits(); } adapter.addAll(webinaritems); } if (!myCredit.getPayload().get(0).getFullName().equalsIgnoreCase("")) { binding.tvUsername.setText(myCredit.getPayload().get(0).getFullName()); } if (!myCredit.getPayload().get(0).getEmail().equalsIgnoreCase("")) { binding.tvUseremailid.setText(myCredit.getPayload().get(0).getEmail()); } if (!myCredit.getPayload().get(0).getCompletedCount().equalsIgnoreCase("")) { binding.tvCompltedWebinarCount.setText(myCredit.getPayload().get(0).getCompletedCount()); } if (!myCredit.getPayload().get(0).getPendingCount().equalsIgnoreCase("")) { binding.tvPendingWebinarCount.setText(myCredit.getPayload().get(0).getPendingCount()); } if (!myCredit.getPayload().get(0).getUpcomingCount().equalsIgnoreCase("")) { binding.tvUpcomingWebinarCount.setText(myCredit.getPayload().get(0).getUpcomingCount()); } if (mlistmycredit.size() > 0) { binding.swipeRefreshLayout.setVisibility(View.VISIBLE); binding.tvNodatafound.setVisibility(View.GONE); } else { binding.tvNodatafound.setVisibility(View.VISIBLE); binding.swipeRefreshLayout.setVisibility(View.GONE); } } else { if (progressDialog.isShowing()) { progressDialog.dismiss(); } else { if (binding.swipeRefreshLayout.isRefreshing()) { binding.swipeRefreshLayout.setRefreshing(false); } } Snackbar.make(binding.ivnotification, myCredit.getMessage(), Snackbar.LENGTH_SHORT).show(); } } }); } boolean isLastVisible() { LinearLayoutManager layoutManager = ((LinearLayoutManager) binding.recyclerviewMycredit.getLayoutManager()); int pos = layoutManager.findLastCompletelyVisibleItemPosition(); int numItems = binding.recyclerviewMycredit.getAdapter().getItemCount() - 1; return (pos >= numItems); } }
true
4508a9519152cc265af90f0a620c2d752c2b8ca6
Java
MertDundar1/ETB-0.6
/src/minecraft/com/enjoytheban/module/modules/world/PingSpoof.java
UTF-8
1,675
2.28125
2
[]
no_license
package com.enjoytheban.module.modules.world; import com.enjoytheban.api.events.world.EventPacketSend; import com.enjoytheban.module.Module; import com.enjoytheban.module.ModuleType; import com.enjoytheban.utils.TimerUtil; import java.awt.Color; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import net.minecraft.client.Minecraft; import net.minecraft.client.network.NetHandlerPlayClient; import net.minecraft.network.NetworkManager; import net.minecraft.network.Packet; import net.minecraft.network.play.client.C00PacketKeepAlive; import optifine.MathUtils; public class PingSpoof extends Module { private List<Packet> packetList = new CopyOnWriteArrayList(); private TimerUtil timer = new TimerUtil(); public PingSpoof() { super("PingSpoof", new String[] { "spoofping", "ping" }, ModuleType.World); setColor(new Color(117, 52, 203).getRGB()); } @com.enjoytheban.api.EventHandler private void onPacketSend(EventPacketSend e) { if (((e.getPacket() instanceof C00PacketKeepAlive)) && (mc.thePlayer.isEntityAlive())) { packetList.add(e.getPacket()); e.setCancelled(true); } if (timer.hasReached(750.0D)) { if (!packetList.isEmpty()) { int i = 0; double totalPackets = MathUtils.getIncremental(Math.random() * 10.0D, 1.0D); for (Packet packet : packetList) if (i < totalPackets) { i++; mc.getNetHandler().getNetworkManager().sendPacket(packet); packetList.remove(packet); } } mc.getNetHandler().getNetworkManager().sendPacket(new C00PacketKeepAlive(10000)); timer.reset(); } } }
true
70762ddb4c63ecf60a18b0ab9c84fb556f0f15af
Java
jjiyeon6/javasource
/Interface/src/battle/Unit.java
UTF-8
127
2.40625
2
[]
no_license
package battle; public interface Unit { public abstract void move(int x, int y); public abstract void stop(); }
true
b58dde6fb4043bb22aae79b80e59ba5141355bbb
Java
iBot/HAW-CI-SS12
/HAW-CI-SS12/src/prak3/node/DeclarationsNode.java
UTF-8
1,684
2.96875
3
[]
no_license
package prak3.node; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import prak3.descr.AbstractDescr; public class DeclarationsNode extends AbstractNode implements Node { /** * */ private static final long serialVersionUID = 1L; private List<AbstractNode> consts = new ArrayList<AbstractNode>();; private List<AbstractNode> typs = new ArrayList<AbstractNode>();; private List<AbstractNode> vars = new ArrayList<AbstractNode>();; private List<ProcedureDeclarationNode> procedureDeaclaration = new ArrayList<ProcedureDeclarationNode>(); public DeclarationsNode(String name, int line, int column) { super(name, line, column); } public void addProcedureDeclaration(ProcedureDeclarationNode pd){ this.procedureDeaclaration.add(pd); } @Override public AbstractDescr compile(HashMap<String, AbstractDescr> symbolTable) { // TODO Auto-generated method stub return null; } public void addTyp(AbstractNode typ){ this.typs.add(typ); } public void addConst(AbstractNode c){ this.consts.add(c); } public void addVar(AbstractNode v){ this.vars.add(v); } @Override public void print() { indent(); System.out.format("Declarations: %n, Zeile: %s, Spalte: %s", name, line, column); if(!(consts.isEmpty())){ for(AbstractNode a : consts){ a.print(); } } else if(!(typs.isEmpty())){ for(AbstractNode a: typs){ a.print(); } } else if(!(vars.isEmpty())){ for(AbstractNode a: vars){ a.print(); } } for(ProcedureDeclarationNode p : procedureDeaclaration){ p.print(); } unindent(); } }
true
c8e83dfdee8aa4429a4cc655d633f6a4229de11d
Java
infiniti24/InterviewCode
/src/com/shoumo/geek/tree/SimpleNode.java
UTF-8
248
2.90625
3
[]
no_license
package com.shoumo.geek.tree; public class SimpleNode { int data; SimpleNode left, right; public SimpleNode(int data) { this.data = data; left = right = null; } @Override public String toString() { return String.valueOf(data); } }
true
e665f6ce0a9a5ee5d49a251a707f04d8441ce33b
Java
seasarorg/s2axis2
/s2axis2/src/main/java/org/seasar/remoting/axis2/connector/RESTConnector.java
UTF-8
6,624
1.953125
2
[]
no_license
/* * Copyright 2004-2010 the Seasar Foundation and the Others. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.seasar.remoting.axis2.connector; import java.lang.reflect.Method; import org.apache.axiom.om.OMElement; import org.apache.axis2.Constants; import org.apache.axis2.addressing.EndpointReference; import org.apache.axis2.client.Options; import org.seasar.framework.container.S2Container; import org.seasar.framework.container.factory.SingletonS2ContainerFactory; import org.seasar.framework.util.StringUtil; import org.seasar.remoting.axis2.client.RESTContext; import org.seasar.remoting.axis2.client.RESTRequestBuilder; import org.seasar.remoting.axis2.client.RequestBuilder; import org.seasar.remoting.axis2.client.S2AxisClientContext; import org.seasar.remoting.axis2.util.RESTUtil; /** * RESTをサポートしているWebサービスと通信するためのコネクタです。<br> * <br> * このコネクタを利用する場合は、サービスの引数は1つに限ります。<br> * その引数のパラメータより、サービスを実行するためのRESTパラメータを生成します。<br> * * @author takanori */ public class RESTConnector extends AbstractRPCConnector { /** Action名(メソッド名)を付加するかどうかの指定 */ protected boolean appendAction = false; /** RESTのコンテキスト */ protected RESTContext restContext; /** RequestBuilder */ protected RequestBuilder requestBuilder; /** * デフォルトのコンストラクタ。 */ public RESTConnector() {} /** * このオブジェクトの初期化を行います。 <br> * parentOptionsに、 REST形式の呼び出しを行う際のパラメータを設定します。 */ @Override protected void init() { super.init(); if (this.restContext == null) { this.restContext = getRestContext(); } if (this.requestBuilder == null) { this.requestBuilder = getRequestBuilder(); } super.options.setTransportInProtocol(Constants.TRANSPORT_HTTP); String keyEnableRest = Constants.Configuration.ENABLE_REST; if (super.options.getProperty(keyEnableRest) == null) { super.options.setProperty(keyEnableRest, Constants.VALUE_TRUE); } } /** * {@inheritDoc} */ @Override protected Object execute(Method method, Object[] args, Options options) throws Exception { // Content-Typeの指定 String contentType = this.restContext.getContentType(method); if (!StringUtil.isEmpty(contentType)) { options.setProperty(Constants.Configuration.MESSAGE_TYPE, contentType); } // HttpMethodの指定 String httpMethod = this.restContext.getHttpMethod(method); options.setProperty(Constants.Configuration.HTTP_METHOD, httpMethod); // エンドポイントの設定 String localEPR = S2AxisClientContext.getEndpointURL(); EndpointReference targetEPR; if (!StringUtil.isEmpty(localEPR)) { targetEPR = new EndpointReference(localEPR); } else { // REST形式での通信用に設定し直す。 String targetUrl = getTargetUrl(method); targetEPR = new EndpointReference(targetUrl); } options.setTo(targetEPR); Class returnType = method.getReturnType(); OMElement request = this.requestBuilder.create(method, args, options); OMElement response; if (returnType.equals(void.class)) { super.client.sendRobust(request); response = null; } else { response = super.client.sendReceive(request); } Object result = deserialize(returnType, response); return result; } /** * 指定されたメソッドから、対象サービスのリソースパスであるURIを取得します。 * * @param method メソッド * @return エンドポイントのURL */ protected String getTargetUrl(Method method) { String targetUrl = this.baseURL.toString(); if (targetUrl.endsWith(RESTUtil.URI_SEPARATOR)) { targetUrl = targetUrl.substring(0, targetUrl.lastIndexOf(RESTUtil.URI_SEPARATOR)); } String uriTemplate = RESTUtil.getUriTemplate(method, this.appendAction); return targetUrl + uriTemplate; } /** * RequestBuilderを取得します。 * * @return RequestBuilder */ protected RequestBuilder getRequestBuilder() { S2Container container = SingletonS2ContainerFactory.getContainer().getRoot(); RequestBuilder requestBuilder = null; if (requestBuilder == null) { requestBuilder = (RequestBuilder)container.getComponent(RESTRequestBuilder.class); } return requestBuilder; } /** * RESTのコンテキストを取得します。 * * @return RESTContext */ protected RESTContext getRestContext() { S2Container container = SingletonS2ContainerFactory.getContainer().getRoot(); RESTContext context = null; if (context == null) { context = (RESTContext)container.getComponent(RESTContext.class); } return context; } /** * URIにアクション名(メソッド名)を含めるかどうかを取得する。 * * @return 含める場合はture */ public boolean isAppendAction() { return this.appendAction; } /** * URIにアクション名を含めるかどうかを指定する。 * * @param appendAction 含める場合はture */ public void setAppendAction(boolean appendAction) { this.appendAction = appendAction; } }
true
2589eece43e23ab7beca0523ab372c3ade424f91
Java
ushitora/RSFA-QueryLearning
/rsfalearning/src/main/java/rsfalearning/RSFABALearnerSimulatedMembershipOracle.java
UTF-8
844
1.898438
2
[]
no_license
package rsfalearning; import java.util.ArrayList; import java.util.List; import org.sat4j.specs.TimeoutException; import algebralearning.oracles.MembershipOracle; public class RSFABALearnerSimulatedMembershipOracle<D> extends MembershipOracle<D> { private RSFAObservationTable<D> table; private Integer srcRowIdx; private Integer dstRowIdx; public RSFABALearnerSimulatedMembershipOracle(RSFAObservationTable<D> t, Integer s, Integer d) { table = t; srcRowIdx = s; dstRowIdx = d; } public boolean query(D a) throws TimeoutException { List<D> qa = new ArrayList<D>(table.U.get(srcRowIdx)); qa.add(a); ArrayList<Boolean> tempRow = table.getTempRow(qa); if(table.isNewPrime(tempRow)) { table.addRow(qa); throw new UIsExtendedException(); } return table.isSubseteq(table.T.get(dstRowIdx), tempRow); } }
true
1c240c01fcaa5e4582923fe7004ecc98f0ea4d35
Java
lsw159134/azikezhi
/src/main/java/com/zikezhi/controller/PrimaryController.java
UTF-8
3,215
2.03125
2
[]
no_license
package com.zikezhi.controller; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.zikezhi.entity.Primary; import com.zikezhi.service.PrimaryService; /** * 一级分类 * @author wrp * */ @Controller public class PrimaryController { @Resource(name = "primaryService") private PrimaryService primaryService; @RequestMapping("1019/zai/xin/jian/queryPrimaryProductAll") @ResponseBody public List<Primary> queryPrimaryProductAll(HttpSession session, Model model){ List<Primary> primaryList=primaryService.queryAll(); model.addAttribute("primaryList", primaryList); return primaryList; } @RequestMapping("1019/zai/xin/jian/upPrimary") @ResponseBody public Map<String, Object> upPrimary(Primary p,HttpSession session, Model model){ Map<String, Object> map = new HashMap<String, Object>(); if (session.getAttribute("user") == null) { map.put("result","login"); return map; } int i=primaryService.updateByPrimaryKeySelective(p); if(i==0){ map.put("result","fail"); map.put("msg","失败"); }else{ map.put("result","seccuss"); map.put("msg","成功"); } return map; } @RequestMapping("1019/zai/xin/jian/addPrimary") @ResponseBody public Map<String, Object> addPrimary(Primary p,HttpSession session, Model model){ Map<String, Object> map = new HashMap<String, Object>(); if (session.getAttribute("user") == null) { map.put("result","login"); return map; } p.setPrimary_addtime(new Date()); int i=primaryService.insertSelective(p); if(i==0){ map.put("result","fail"); map.put("msg","失败"); }else{ map.put("result","seccuss"); map.put("msg","成功"); } return map; } @RequestMapping("1019/zai/xin/jian/queryPrimaryName") @ResponseBody public Map<String, Object> queryPrimaryName(Primary p,HttpSession session, Model model){ Map<String, Object> map = new HashMap<String, Object>(); if (session.getAttribute("user") == null) { map.put("result","login"); return map; } p.setPrimary_addtime(new Date()); int i=primaryService.queryPrimaryName(p); if(i!=0){ map.put("result","fail"); map.put("msg","失败"); }else{ map.put("result","seccuss"); map.put("msg","成功"); } return map; } @RequestMapping("1019/zai/xin/jian/deletePrimary") public String deletePrimary(int id,HttpSession session, Model model){ if (session.getAttribute("user") == null) { return "Adminlogin"; } primaryService.deletePrimary(id); return "redirect:queryPrimaryAll"; } @RequestMapping("1019/zai/xin/jian/queryPrimaryAll") public String queryPrimaryAll(HttpSession session, Model model){ if (session.getAttribute("user") == null) { return "Adminlogin"; } List<Primary> primaryList=primaryService.queryAll(); model.addAttribute("primaryList", primaryList); model.addAttribute("primaryAll", "primaryAll"); return "adminHome"; } }
true
4a3195f9876afeda5e42b4ab312709154670fbd9
Java
masterprash2/seattleSearch
/app/src/main/java/com/homeaway/seattlesearch/app/di/MainThreadScheduler.java
UTF-8
300
1.734375
2
[]
no_license
package com.homeaway.seattlesearch.app.di; import javax.inject.Qualifier; import java.lang.annotation.Retention; import java.lang.annotation.Documented; import static java.lang.annotation.RetentionPolicy.RUNTIME; @Qualifier @Documented @Retention(RUNTIME) public @interface MainThreadScheduler { }
true
1f8f057acc4c8d574b679a1b26f5e07e28b05ebe
Java
oneperfect/ONER
/core/src/main/java/com/demon/core/mysql/MySQLDialectUTF8.java
UTF-8
300
1.960938
2
[]
no_license
package com.demon.core.mysql; import org.hibernate.dialect.MySQL5Dialect; /** * @Auther: oneperfect * @Date: 2019/03/14 */ public class MySQLDialectUTF8 extends MySQL5Dialect { @Override public String getTableTypeString() { return " ENGINE=InnoDB DEFAULT CHARSET=utf8"; } }
true
73c0f87fe86e6bddc0653f3fe122562a486c7b11
Java
alzimmermsft/azure-sdk-for-java
/sdk/hdinsight/azure-resourcemanager-hdinsight/src/test/java/com/azure/resourcemanager/hdinsight/generated/ExtensionsGetAzureMonitorStatusWithResponseMockTests.java
UTF-8
3,491
1.75
2
[ "LGPL-2.1-or-later", "BSD-3-Clause", "MIT", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-unknown-license-reference", "CC0-1.0", "LicenseRef-scancode-generic-cla" ]
permissive
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.hdinsight.generated; import com.azure.core.credential.AccessToken; import com.azure.core.http.HttpClient; import com.azure.core.http.HttpHeaders; import com.azure.core.http.HttpRequest; import com.azure.core.http.HttpResponse; import com.azure.core.management.AzureEnvironment; import com.azure.core.management.profile.AzureProfile; import com.azure.core.util.Context; import com.azure.resourcemanager.hdinsight.HDInsightManager; import com.azure.resourcemanager.hdinsight.models.AzureMonitorResponse; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; import java.time.OffsetDateTime; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; public final class ExtensionsGetAzureMonitorStatusWithResponseMockTests { @Test public void testGetAzureMonitorStatusWithResponse() throws Exception { HttpClient httpClient = Mockito.mock(HttpClient.class); HttpResponse httpResponse = Mockito.mock(HttpResponse.class); ArgumentCaptor<HttpRequest> httpRequest = ArgumentCaptor.forClass(HttpRequest.class); String responseStr = "{\"clusterMonitoringEnabled\":true,\"workspaceId\":\"iuubwefqsf\",\"selectedConfigurations\":{\"configurationVersion\":\"qtferrqwexjkmf\",\"globalConfigurations\":{\"abtqwpwyawbzasqb\":\"jwogqqnobpudc\",\"kyexaoguyaipi\":\"clj\",\"um\":\"sdaultxij\"},\"tableList\":[]}}"; Mockito.when(httpResponse.getStatusCode()).thenReturn(200); Mockito.when(httpResponse.getHeaders()).thenReturn(new HttpHeaders()); Mockito .when(httpResponse.getBody()) .thenReturn(Flux.just(ByteBuffer.wrap(responseStr.getBytes(StandardCharsets.UTF_8)))); Mockito .when(httpResponse.getBodyAsByteArray()) .thenReturn(Mono.just(responseStr.getBytes(StandardCharsets.UTF_8))); Mockito .when(httpClient.send(httpRequest.capture(), Mockito.any())) .thenReturn( Mono .defer( () -> { Mockito.when(httpResponse.getRequest()).thenReturn(httpRequest.getValue()); return Mono.just(httpResponse); })); HDInsightManager manager = HDInsightManager .configure() .withHttpClient(httpClient) .authenticate( tokenRequestContext -> Mono.just(new AccessToken("this_is_a_token", OffsetDateTime.MAX)), new AzureProfile("", "", AzureEnvironment.AZURE)); AzureMonitorResponse response = manager.extensions().getAzureMonitorStatusWithResponse("hahzvechndbnwi", "hol", Context.NONE).getValue(); Assertions.assertEquals(true, response.clusterMonitoringEnabled()); Assertions.assertEquals("iuubwefqsf", response.workspaceId()); Assertions.assertEquals("qtferrqwexjkmf", response.selectedConfigurations().configurationVersion()); Assertions .assertEquals( "jwogqqnobpudc", response.selectedConfigurations().globalConfigurations().get("abtqwpwyawbzasqb")); } }
true
1f54226eb03ba08244c5b393bb90534f79bf977a
Java
sarah-ceo/GSB-Application
/src/FenetreResponsable.java
UTF-8
4,594
2.28125
2
[]
no_license
import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.table.DefaultTableModel; import javax.swing.JLabel; import java.awt.Font; import java.util.Date; import javax.swing.SwingConstants; import javax.swing.JScrollPane; import javax.swing.JSpinner; import javax.swing.JTable; import javax.swing.SpinnerDateModel; import javax.swing.JButton; import javax.swing.JComboBox; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class FenetreResponsable extends JFrame { private JTable table; private JPanel contentPane; private JScrollPane scrollPane; private JButton btnDtailsParVisiteur; private JComboBox comboBox; private JSpinner spinnerDebut; private JSpinner spinnerFin; private JButton btnActualiser; private JButton btnDeconnexion; /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { FenetreResponsable frame = new FenetreResponsable(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public FenetreResponsable() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(150, 150, 700, 400); setResizable(false); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JLabel lblAccueil = new JLabel("Visites par r\u00E9gion"); lblAccueil.setBounds(203, 5, 319, 25); lblAccueil.setHorizontalAlignment(SwingConstants.CENTER); lblAccueil.setFont(new Font("Tahoma", Font.PLAIN, 20)); contentPane.add(lblAccueil); JPanel panel = new JPanel(); panel.setBounds(5, 39, 679, 322); contentPane.add(panel); panel.setLayout(null); scrollPane = new JScrollPane(); scrollPane.setBounds(10, 53, 659, 224); panel.add(scrollPane); table = new JTable(); table.setModel(new DefaultTableModel( new Object[][] { }, new String[] { } )); scrollPane.setViewportView(table); btnDtailsParVisiteur = new JButton("D\u00E9tails par visiteur"); btnDtailsParVisiteur.setBounds(223, 288, 235, 23); panel.add(btnDtailsParVisiteur); JLabel lblRgion = new JLabel("R\u00E9gion :"); lblRgion.setHorizontalAlignment(SwingConstants.CENTER); lblRgion.setFont(new Font("Tahoma", Font.PLAIN, 15)); lblRgion.setBounds(10, 19, 63, 23); panel.add(lblRgion); comboBox = new JComboBox(); comboBox.setBounds(71, 22, 139, 20); panel.add(comboBox); JLabel lblEntreLe = new JLabel("Entre le :"); lblEntreLe.setHorizontalAlignment(SwingConstants.CENTER); lblEntreLe.setBounds(220, 25, 56, 14); panel.add(lblEntreLe); JLabel lblEtLe = new JLabel("Et le :"); lblEtLe.setHorizontalAlignment(SwingConstants.CENTER); lblEtLe.setBounds(380, 25, 46, 14); panel.add(lblEtLe); spinnerDebut = new JSpinner(new SpinnerDateModel()); spinnerDebut.setBounds(286, 22, 84, 23); JSpinner.DateEditor de_spinnerDebut = new JSpinner.DateEditor(spinnerDebut, "dd/MM/yyyy"); spinnerDebut.setEditor(de_spinnerDebut); spinnerDebut.setValue(new Date()); panel.add(spinnerDebut); spinnerFin = new JSpinner(new SpinnerDateModel()); JSpinner.DateEditor de_spinnerFin = new JSpinner.DateEditor(spinnerFin, "dd/MM/yyyy"); spinnerFin.setEditor(de_spinnerFin); spinnerFin.setValue(new Date()); spinnerFin.setBounds(425, 22, 84, 23); panel.add(spinnerFin); btnActualiser = new JButton("Actualiser"); btnActualiser.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { } }); btnActualiser.setBounds(519, 19, 150, 23); panel.add(btnActualiser); btnDeconnexion = new JButton("Deconnexion"); btnDeconnexion.setBounds(532, 5, 152, 23); contentPane.add(btnDeconnexion); } public JScrollPane getScrollPane() { return scrollPane; } public JButton getBtnDtailsParVisiteur() { return btnDtailsParVisiteur; } public JComboBox getComboBox() { return comboBox; } public JSpinner getSpinnerDebut() { return spinnerDebut; } public JSpinner getSpinnerFin() { return spinnerFin; } public JButton getBtnActualiser() { return btnActualiser; } public JTable getTable() { return table; } public JButton getBtnDeconnexion() { return btnDeconnexion; } }
true
49c183e1bf9be503251700e0b789f861a56e78f0
Java
contactmathewjoseph/RetroNews
/app/src/main/java/com/ytosko/twc/retronews/urlhelper.java
UTF-8
540
2.296875
2
[]
no_license
package com.ytosko.twc.retronews; public class urlhelper { private String title,url; public urlhelper() { } public urlhelper(String title, String url) { this.title = title; this.url = url; } public String getTitle() { return title; } public urlhelper setTitle(String title) { this.title = title; return this; } public String getUrl() { return url; } public urlhelper setUrl(String url) { this.url = url; return this; } }
true
b8c9b91f604230a45435ce64974f07daac0c8e8f
Java
wat-org/melody
/melody.common/src/main/java/com/wat/melody/common/ssh/ISshConnectionDatas.java
UTF-8
383
1.820313
2
[]
no_license
package com.wat.melody.common.ssh; import com.wat.melody.common.network.Host; import com.wat.melody.common.network.Port; /** * * @author Guillaume Cornet * */ public interface ISshConnectionDatas { public Host getHost(); public Host setHost(Host host); public Port getPort(); public Port setPort(Port port); public boolean getTrust(); public boolean setTrust(boolean b); }
true
8d76e2cf645c4074d97e0e7d723140aa0152e28b
Java
it114-final-ZakariaIsmaili/final-part22-generics-ZakariaIsmaili
/src/main/java/section2/classes/State.java
UTF-8
972
3.015625
3
[]
no_license
/** * */ package section2.classes; import section2.interfaces.HasCapital; import section2.interfaces.HasGovernor; import section2.interfaces.HasName; /** * @author Alt * */ public class State <C extends Capital,G extends Governor> implements HasCapital<C>, HasName, HasGovernor<G> { private String name; private C Capital; private G Governor; public State(String _name) { name = _name; } public State (String string, C _Capital, section2.classes.Governor governor2) { Capital = _Capital; } public State (G _Governor){ Governor = _Governor; } public String getName() { // TODO Auto-generated method stub return name; } public String getCapitalName() { // TODO Auto-generated method stub return name; } public G getGovernor() { // TODO Auto-generated method stub return Governor; } public C getCapital() { // TODO Auto-generated method stub return Capital; } }
true
3949322dffcabfbc6d847bd5a00f81df3d28e9a1
Java
ambitious0212/Algorithm
/Algorithm/src/kr/hakin/algorithm/kakao/NewsClustering.java
UTF-8
377
2.171875
2
[]
no_license
package kr.hakin.algorithm.kakao; public class NewsClustering { public static void main(String[] args) { String str1 = "FRANCE"; String str2 = "french"; str1 = str1.toUpperCase(); str2 = str2.toUpperCase(); } public static void createGroup(String data) { } public static void mergeSort(char[] data, int left, int right) { } }
true
df70196c673c1c4375508e37e4b41deda813aeb3
Java
shanumas/assignment
/assignment/src/main/java/com/uma/assignment/AssignmentApplication.java
UTF-8
1,315
2.421875
2
[]
no_license
package com.uma.assignment; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import com.uma.assignment.Operations.Operation; import com.uma.assignment.models.Person; import com.uma.assignment.repositories.PersonRepository; import com.uma.assignment.services.PersonService; @SpringBootApplication public class AssignmentApplication implements CommandLineRunner { @Autowired PersonService personService; private static Logger LOG = LoggerFactory.getLogger(AssignmentApplication.class); public static void main(String[] args) { LOG.info("STARTING THE APPLICATION"); SpringApplication.run(AssignmentApplication.class, args); LOG.info("APPLICATION FINISHED"); } @Override public void run(String... args) { LOG.info("EXECUTING : command line runner"); RequestHandler requestHandler = new RequestHandler(personService); System.out.println("Press Enter to start, \"q\" to quit"); while(!System.console().readLine().equals("q")) { //continue loop until q is pressed if(!requestHandler.handleRequest()) { break; } } } }
true
1cfcd50f8b8c1d5da4a2554b3424e4d8066d86f1
Java
dorin-suletea/DoublePotato
/app/src/main/java/com/dsu/dev4fun/doublepotato/ui/fragment/SettingsFragment.java
UTF-8
5,292
2.28125
2
[]
no_license
package com.dsu.dev4fun.doublepotato.ui.fragment; import android.app.Fragment; import android.content.DialogInterface; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.Spinner; import com.dsu.dev4fun.doublepotato.R; import com.dsu.dev4fun.doublepotato.model.UserPreferences; import com.dsu.dev4fun.doublepotato.model.meta.DataBuilder; import com.dsu.dev4fun.doublepotato.model.util.MethodWrapper; public class SettingsFragment extends Fragment { private EditText memoryTf; private EditText chanelIdTf; private EditText appIdTf; private Button purgeBtn; private CheckBox volControlsBox; private ProgressBar progressBar; private Button saveBtn; private Button discardBtn; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); View view = inflater.inflate(R.layout.fragment_settings, container, false); memoryTf = (EditText) view.findViewById(R.id.settings_memory_idd); chanelIdTf = (EditText) view.findViewById(R.id.settings_channel_id); appIdTf = (EditText) view.findViewById(R.id.settings_app_id); purgeBtn = (Button) view.findViewById(R.id.delete_all_id); volControlsBox = (CheckBox) view.findViewById(R.id.settings_checkbox_vol_controls); saveBtn = (Button) view.findViewById(R.id.settings_save_id); discardBtn = (Button) view.findViewById(R.id.settings_discard_id); progressBar = (ProgressBar) view.findViewById(R.id.purge_progress); addListeners(); return view; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); initValues(); } private void initValues() { memoryTf.setText(Integer.toString(UserPreferences.getInstance().getMemoryAllocation())); chanelIdTf.setText(UserPreferences.getInstance().getChannelId()); appIdTf.setText(UserPreferences.getInstance().getAppId()); boolean volControls = UserPreferences.getInstance().isVolControlsEnabled(); volControlsBox.setChecked(volControls); } private void addListeners() { discardBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getFragmentManager().popBackStack(); } }); saveBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int allocatedMemory = Integer.parseInt(memoryTf.getText().toString()); String chanelID = chanelIdTf.getText().toString(); String appId = appIdTf.getText().toString(); boolean volumeControls = volControlsBox.isChecked(); UserPreferences.getInstance().setMemoryAllocation(allocatedMemory); UserPreferences.getInstance().setChannelId(chanelID); UserPreferences.getInstance().setAppId(appId); UserPreferences.getInstance().setVolControlsEnabled(volumeControls); UserPreferences.getInstance().savePreferences(); getFragmentManager().popBackStack(); /** Re init the data builder with the new preferences **/ DataBuilder.getInstance().init(chanelID, appId, SettingsFragment.this.getActivity()); } }); purgeBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new AlertDialog.Builder(SettingsFragment.this.getActivity()) .setIcon(android.R.drawable.ic_dialog_alert) .setTitle("Delete all") .setMessage("This action will delete all the downloaded songs and metadata about them") .setPositiveButton("Delete all", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { progressBar.setVisibility(View.VISIBLE); DataBuilder.getInstance().purgeLocalDbAndFiles(); MethodWrapper<Void> afterLocalDbInit = new MethodWrapper<Void>() { @Override public void execute(Void params) { progressBar.setVisibility(View.GONE); getFragmentManager().popBackStack(); } }; DataBuilder.getInstance().readLocalModel(afterLocalDbInit); } }) .setNegativeButton("Cancel", null) .show(); } }); } }
true
ce9e18720bfd7448715dfd88cfc1621cd43a9501
Java
Emmilaze/Intro_collection
/src/Utils.java
UTF-8
1,810
3.0625
3
[]
no_license
import java.util.Collection; import java.util.HashMap; import java.util.Iterator; public class Utils { static int key[]; public static long add (Collection list, String data[]) { long time = System.currentTimeMillis(); for (String str: data) list.add(str); return System.currentTimeMillis() - time; } public static long remove(Collection list) { long time = System.currentTimeMillis(); Iterator iterator = list.iterator(); while (iterator.hasNext()) { iterator.next(); iterator.remove(); } return System.currentTimeMillis() - time; } public static long getElement(Collection list) { Object str; long time = System.currentTimeMillis(); Iterator iterator = list.iterator(); while (iterator.hasNext()) str = iterator.next(); return System.currentTimeMillis() - time; } public static long add (HashMap map, String data[]) { key = new int[data.length]; for (int i = 0; i < key.length; i++) key[i] = i; long time = System.currentTimeMillis(); for (int i = 0; i < data.length; i++) { map.put(key[i], data[i]); } return System.currentTimeMillis() - time; } public static long remove(HashMap map) { long time = System.currentTimeMillis(); for (int i = 0; i < key.length; i++) map.remove(key[i]); return System.currentTimeMillis() - time; } public static long getElement(HashMap map) { String str; long time = System.currentTimeMillis(); for (int i = 0; i < key.length; i++) str = (String)map.get(key[i]); return System.currentTimeMillis() - time; } }
true
2eedc366ac58fd47fe72e492e31e2b243fcd258c
Java
jtriche21/Ref-Mesiter-Team-Green
/src/views/NoteView.java
UTF-8
2,324
3.734375
4
[]
no_license
package views; import java.util.ArrayList; import java.util.Scanner; import controllers.NoteController; import interfaces.INoteModel; import interfaces.INoteView; import models.NoteModel; /** * A view class for the viewing and printing of Note objects. * * @author Nick Ruby * @version 4/18/18 */ public class NoteView implements INoteView{ /**The note object.*/ private INoteModel note; /**The scanner object to get user input.*/ private Scanner scanIn; /** * The default constructor. * * @param note The new note object. */ public NoteView(INoteModel note) { this.note = note; scanIn = new Scanner(System.in); } /** * Prints out a certain Note. * * @param note The note to print. */ public void printNote(NoteModel note) { System.out.println(note.toString()); } /** * Prints out all of the notes. * * @param noteList The ArrayList of all notes to print. */ public void printNotes(ArrayList<NoteModel> noteList) { String printString = ""; //Adds the title of each note to printString. for(NoteModel note : noteList) { //Adds a newline to each line except the last. if(noteList.indexOf(note) != noteList.size() - 1) printString += note.getTitle() + "\n"; else printString += note.getTitle(); } System.out.println(printString); } /** * Gets user input and set the notes fields. */ @Override public void getInputNote() { System.out.println("Note Title: "); String title = scanIn.nextLine(); System.out.println("Note Description: "); String description = scanIn.nextLine(); note.set(title, description); } /** * Returns the note object. * * @return The note object. */ @Override public INoteModel getData() { return note; } /** * Sets the note object. * * @param note The new note object. */ @Override public void setData(INoteModel note) { this.note = note; } }
true
ba727c52f666f471140d804d261e1f15f964438c
Java
JgyXyyxy/GA
/src/main/java/com/sdu/com/sdu/ga/Chromosome.java
UTF-8
2,631
3.015625
3
[]
no_license
package com.sdu.com.sdu.ga; import com.sdu.pic.ColorFormat; import java.awt.*; import java.util.*; /** * Created by J on 2017/5/19. */ public class Chromosome { private Color color; private boolean[] gene; private double score; public Chromosome() { gene = new boolean[24]; for (int i = 0; i < 24; i++) { gene[i] = Math.random() >= 0.5; } } public Chromosome(Color color) { this.color = color; try { this.gene = ColorFormat.toBinaryGene(color); } catch (Exception e) { e.printStackTrace(); } } public Color getColor() { return color; } public void setColor(Color color) { this.color = color; } public boolean[] getGene() { return gene; } public void setGene(boolean[] gene) { this.gene = gene; } public double getScore() { return score; } public void setScore(double score) { this.score = score; } public void mutation(int num) { int size = gene.length; for (int i = 0; i < num; i++) { //寻找变异位置 int at = ((int) (Math.random() * size)) % size; //变异后的值 boolean bool = !gene[at]; gene[at] = bool; } } public static Chromosome clone(final Chromosome c) { if (c == null || c.gene == null) { return null; } Chromosome copy = new Chromosome(); for (int i = 0; i < 24; i++) { copy.gene[i] = c.gene[i]; } return copy; } public static ArrayList<Chromosome> crossover(Chromosome p1, Chromosome p2) { if (p1 == null || p2 == null) { return null; } if (p1.gene == null || p2.gene == null) { return null; } if (p1.gene.length != p2.gene.length) { return null; } Chromosome c1 = clone(p1); Chromosome c2 = clone(p2); //随机产生交叉互换位置 int size = c1.gene.length; int a = ((int) (Math.random() * size)) % size; int b = ((int) (Math.random() * size)) % size; int min = a > b ? b : a; int max = a > b ? a : b; //对位置上的基因进行交叉互换 for (int i = min; i <= max; i++) { boolean t = c1.gene[i]; c1.gene[i] = c2.gene[i]; c2.gene[i] = t; } ArrayList<Chromosome> list = new ArrayList<Chromosome>(); list.add(c1); list.add(c2); return list; } }
true
1439b77ee715c06e74e4da802bd5c7be43907db3
Java
Grga-Pitic/simple-oop-snake
/src/main/game/services/FoodService.java
UTF-8
917
2.953125
3
[]
no_license
package main.game.services; import java.util.Random; import main.game.Food; import main.game.GameContainer; /** * Class service. It need to generate new random food position. * @author Grga * */ public class FoodService { public static FoodService instance; public void randomPosition(Food food) { int fieldWidth = GameContainer.getInstance().getSettings().getWidth(); int fieldHeigth = GameContainer.getInstance().getSettings().getHeight(); Random random = new Random(); int x = random.nextInt(fieldWidth); int y = random.nextInt(fieldHeigth); boolean [][] field = GameContainer.getInstance().getField(); while(field[x][y]){ x = random.nextInt(fieldWidth); y = random.nextInt(fieldHeigth); } food.setX(x); food.setY(y); } public static FoodService getInstance() { if(instance == null) { instance = new FoodService(); } return instance; } }
true
11c2932be0100fb12b1c9869cbad274fbe696a7f
Java
kinosker/CS2103-CE2
/src/fileLogger/Logger.java
UTF-8
365
2.640625
3
[]
no_license
package fileLogger; import java.io.BufferedWriter; import java.util.ArrayList; /** * @author TienLong Provides the implementation of the logger (The strategy to * log header/content) */ public interface Logger { public void logHeader(BufferedWriter writer); public void logContent(BufferedWriter writer, ArrayList<String> toDoList); }
true
81c56ad604715c391acb18cac2d83fbc006b65d2
Java
kwaghela73/Travelone
/app/src/main/java/com/demons/travelone/MyFirebaseInstanceIdService.java
UTF-8
1,218
1.734375
2
[]
no_license
package com.demons.travelone; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.IBinder; import android.preference.PreferenceManager; import android.util.Log; import com.google.firebase.iid.FirebaseInstanceId; import com.google.firebase.iid.FirebaseInstanceIdService; import com.google.firebase.messaging.FirebaseMessaging; import com.google.firebase.messaging.FirebaseMessagingService; public class MyFirebaseInstanceIdService extends FirebaseInstanceIdService { //private String tokenPreferenceKey = "fcm_msg"; //final static String Infotopicname = "trips"; private static final String REG_TOKEN="REG_TOKEN"; public MyFirebaseInstanceIdService() { } @Override public void onTokenRefresh() { String recent_token = FirebaseInstanceId.getInstance().getToken(); SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences(getString(R.string.FCM_PREF), Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(getString(R.string.FCM_TOKEN),recent_token); editor.commit(); } }
true
4a428fa4ddcf9d3849a77e71afbbb37c72f719dd
Java
obaby/bjqd
/src/main/java/cn/xports/qd2/adapter/PersonalTrainBinder.java
UTF-8
3,450
1.945313
2
[]
no_license
package cn.xports.qd2.adapter; import android.os.Bundle; import android.support.annotation.NonNull; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import cn.xports.baselib.adapter.XBaseHolder; import cn.xports.baselib.util.GlideUtil; import cn.xports.baselib.util.MoneyUtil; import cn.xports.qd2.R; import cn.xports.qd2.entity.K; import cn.xports.qd2.entity.TrainItem; import cn.xports.qd2.training.TrainingDetailActivity; import com.blankj.utilcode.util.ActivityUtils; import me.drakeet.multitype.ItemViewBinder; public class PersonalTrainBinder extends ItemViewBinder<TrainItem, XBaseHolder> { /* access modifiers changed from: protected */ @NonNull public XBaseHolder onCreateViewHolder(@NonNull LayoutInflater layoutInflater, @NonNull ViewGroup viewGroup) { return new XBaseHolder(layoutInflater.inflate(R.layout.item_personal_train, viewGroup, false)); } /* access modifiers changed from: protected */ public void onBindViewHolder(@NonNull XBaseHolder xBaseHolder, @NonNull final TrainItem trainItem) { ImageView imageView = (ImageView) xBaseHolder.getView(R.id.iv_header); GlideUtil.loadImage(imageView.getContext(), trainItem.getCoursePicUrl(), R.drawable.bg_default).into(imageView); xBaseHolder.setText(R.id.ct_suit, trainItem.getSuitPerson()); xBaseHolder.setText(R.id.tv_name, trainItem.getCourseName()); TextView textView = (TextView) xBaseHolder.getView(R.id.ct_suit); TextView textView2 = (TextView) xBaseHolder.getView(R.id.ct_prom); int i = 4; boolean z = false; textView.setVisibility(!TextUtils.isEmpty(trainItem.getSuitPerson()) ? 0 : 4); if (MoneyUtil.str2Int(trainItem.getOriginalPrice()) > trainItem.getPrice()) { i = 0; } textView2.setVisibility(i); if (trainItem.getSubjectPrice() != null) { int i2 = R.id.tv_real_money; xBaseHolder.setText(i2, "¥" + MoneyUtil.simpleYuan(trainItem.getSubjectPrice().intValue()) + "起"); } else { int i3 = R.id.tv_real_money; xBaseHolder.setText(i3, "¥" + MoneyUtil.simpleYuan(trainItem.getPrice())); } TextView textView3 = (TextView) xBaseHolder.getView(R.id.tv_old_money); textView3.getPaint().setFlags(16); textView3.setText("¥" + MoneyUtil.simpleYuan(trainItem.getOriginalPrice())); int i4 = R.id.tv_old_money; if (MoneyUtil.str2Int(trainItem.getOriginalPrice()) > trainItem.getPrice()) { z = true; } xBaseHolder.setVisible(i4, z); String courseEnrolled = trainItem.getCourseEnrolled(); if (trainItem.isPrivate()) { courseEnrolled = trainItem.getPrivateCourseEnrolled(); } if (TextUtils.isEmpty(courseEnrolled)) { courseEnrolled = K.k0; } int i5 = R.id.tv_has_sign; xBaseHolder.setText(i5, courseEnrolled + "人已报名"); xBaseHolder.itemView.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { Bundle bundle = new Bundle(); bundle.putString("courseId", trainItem.getCourseId()); ActivityUtils.startActivity(bundle, TrainingDetailActivity.class); } }); } }
true
e77ce29c0e261d6b96f0f4df5bd2f103756f937d
Java
he-shuang/dkha-sz
/dkha-admin/dkha-admin-server/src/main/java/com/dkha/service/SysMenuService.java
UTF-8
1,187
1.992188
2
[]
no_license
package com.dkha.service; import com.dkha.commons.mybatis.service.BaseService; import com.dkha.commons.security.user.UserDetail; import com.dkha.dto.SysMenuDTO; import com.dkha.entity.SysMenuEntity; import java.util.List; import java.util.Set; /** * 菜单管理 * @since 1.0.0 */ public interface SysMenuService extends BaseService<SysMenuEntity> { SysMenuDTO get(Long id); void save(SysMenuDTO dto); void update(SysMenuDTO dto); void delete(Long id); /** * 菜单列表 * * @param type 菜单类型 */ List<SysMenuDTO> getMenuList(Integer type); /** * 用户菜单列表 * * @param userDetail 用户信息 * @param type 菜单类型 */ List<SysMenuDTO> getUserMenuList(UserDetail userDetail, Integer type); /** * 用户菜单导航 * @param userDetail 用户信息 */ List<SysMenuDTO> getUserMenuNavList(UserDetail userDetail); /** * 获取用户权限标识 */ Set<String> getUserPermissions(UserDetail userDetail); /** * 根据父菜单,查询子菜单 * @param pid 父菜单ID */ List<SysMenuDTO> getListPid(Long pid); }
true