code
stringlengths 3
1.04M
| repo_name
stringlengths 5
109
| path
stringlengths 6
306
| language
stringclasses 1
value | license
stringclasses 15
values | size
int64 3
1.04M
|
---|---|---|---|---|---|
package com.sind.projectx.domain.food.menu;
import org.hibernate.validator.constraints.NotBlank;
import org.hibernate.validator.constraints.NotEmpty;
import java.util.ArrayList;
import java.util.List;
/**
* @author Dmytro Bekuzarov
*/
public class MenuSection {
@NotBlank
private String name;
@NotEmpty
private List<String> items = new ArrayList<>();
private List<MenuSection> sections = new ArrayList<>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getItems() {
return items;
}
public void setItems(List<String> items) {
this.items = items;
}
public List<MenuSection> getSections() {
return sections;
}
public void setSections(List<MenuSection> sections) {
this.sections = sections;
}
}
|
dmytro-bekuzarov/projectx-api
|
projectx-api-domain/src/main/java/com/sind/projectx/domain/food/menu/MenuSection.java
|
Java
|
mit
| 890 |
// package it.at.oiml.bitbucket.lfs;
//
// import org.junit.Test;
// import org.junit.runner.RunWith;
// import com.atlassian.plugins.osgi.test.AtlassianPluginsTestRunner;
// import at.oiml.bitbucket.lfs.MyPluginComponent;
// import com.atlassian.sal.api.ApplicationProperties;
//
// import static org.junit.Assert.assertEquals;
//
// @RunWith(AtlassianPluginsTestRunner.class)
// public class MyComponentWiredTest
// {
// private final ApplicationProperties applicationProperties;
// private final MyPluginComponent myPluginComponent;
//
// public MyComponentWiredTest(ApplicationProperties applicationProperties,MyPluginComponent myPluginComponent)
// {
// this.applicationProperties = applicationProperties;
// this.myPluginComponent = myPluginComponent;
// }
//
// @Test
// public void testMyName()
// {
// assertEquals("names do not match!", "myComponent:" + applicationProperties.getDisplayName(),myPluginComponent.getName());
// }
// }
|
joerg/stash-git-lfs
|
src/test/java/it/at/oiml/stash/lfs/MyComponentWiredTest.java
|
Java
|
mit
| 1,003 |
/*
Binary Tree Upside Down
Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into left leaf nodes. Return the new root.
For example:
Given a binary tree {1,2,3,4,5},
1
/ \
2 3
/ \
4 5
return the root of the binary tree [4,5,2,#,#,3,1].
4
/ \
5 2
/ \
3 1
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
Hide Tags Tree
Hide Similar Problems (E) Reverse Linked List
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode upsideDownBinaryTree(TreeNode root) {
TreeNode p = root, parent = null, parentRight = null;
while (p!=null) {
TreeNode left = p.left;
p.left = parentRight;
parentRight = p.right;
p.right = parent;
parent = p;
p = left;
}
return parent;
}
}
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode upsideDownBinaryTree(TreeNode root) {
if(root==null)return root;
if(root.left==null && root.right==null)return root;
TreeNode newRoot = upsideDownBinaryTree(root.left);
root.left.left=root.right;
root.left.right=root;
root.left=null;
root.right=null;
return newRoot;
}
}
/*
1
/\
2 3
/\
4 5
1
/
2 -3
/
4 - 5
*/
|
Yujia-Xiao/Leetcode
|
List/Binary_Tree_Upside_Down.java
|
Java
|
mit
| 1,805 |
package ru.mail.parking.sw2.system;
import com.sonyericsson.extras.liveware.aef.registration.Registration;
import com.sonyericsson.extras.liveware.extension.util.ExtensionUtils;
import com.sonyericsson.extras.liveware.extension.util.registration.RegistrationInformation;
import android.content.ContentValues;
import ru.mail.parking.R;
import ru.mail.parking.ui.SettingsActivity;
import static ru.mail.parking.App.app;
public class SwRegInfo extends RegistrationInformation {
public static final String EXTENSION_KEY = app().getPackageName();
private static final ContentValues INFO = new ContentValues();
public SwRegInfo() {
INFO.put(Registration.ExtensionColumns.CONFIGURATION_ACTIVITY, SettingsActivity.class.getName());
INFO.put(Registration.ExtensionColumns.NAME, app().getString(R.string.sw_title));
INFO.put(Registration.ExtensionColumns.EXTENSION_KEY, EXTENSION_KEY);
INFO.put(Registration.ExtensionColumns.LAUNCH_MODE, Registration.LaunchMode.CONTROL);
String icon = ExtensionUtils.getUriString(app(), R.drawable.icon);
INFO.put(Registration.ExtensionColumns.HOST_APP_ICON_URI, icon);
icon = ExtensionUtils.getUriString(app(), R.drawable.icon_sw);
INFO.put(Registration.ExtensionColumns.EXTENSION_48PX_ICON_URI, icon);
}
@Override
public ContentValues getExtensionRegistrationConfiguration() {
return INFO;
}
@Override
public int getRequiredWidgetApiVersion() {
return RegistrationInformation.API_NOT_REQUIRED;
}
@Override
public int getRequiredSensorApiVersion() {
return RegistrationInformation.API_NOT_REQUIRED;
}
@Override
public int getRequiredNotificationApiVersion() {
return RegistrationInformation.API_NOT_REQUIRED;
}
@Override
public int getRequiredControlApiVersion() {
return 2;
}
@Override
public boolean controlInterceptsBackButton() {
return true;
}
@Override
public boolean isDisplaySizeSupported(int width, int height) {
return width == app().getResources().getDimensionPixelSize(R.dimen.smart_watch_2_control_width) &&
height == app().getResources().getDimensionPixelSize(R.dimen.smart_watch_2_control_height);
}
}
|
trashkalmar/MrParkingNavigator
|
src/ru/mail/parking/sw2/system/SwRegInfo.java
|
Java
|
mit
| 2,177 |
/**
* ****************************************************************************
* Copyright 2014 Virginia Polytechnic Institute and State University
* <p/>
* 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
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* 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 edu.vt.vbi.patric.portlets;
import edu.vt.vbi.patric.beans.Genome;
import edu.vt.vbi.patric.beans.Taxonomy;
import edu.vt.vbi.patric.common.DataApiHandler;
import edu.vt.vbi.patric.common.SiteHelper;
import edu.vt.vbi.patric.common.SolrCore;
import edu.vt.vbi.patric.dao.DBDisease;
import edu.vt.vbi.patric.dao.ResultType;
import org.apache.commons.lang.StringUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.ObjectReader;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.portlet.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class DiseaseOverview extends GenericPortlet {
private static final Logger LOGGER = LoggerFactory.getLogger(DiseaseOverview.class);
private ObjectReader jsonReader;
@Override
public void init() throws PortletException {
super.init();
ObjectMapper objectMapper = new ObjectMapper();
jsonReader = objectMapper.reader(Map.class);
}
@Override
protected void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {
SiteHelper.setHtmlMetaElements(request, response, "Disease Overview");
response.setContentType("text/html");
response.setTitle("Disease Overview");
String contextType = request.getParameter("context_type");
String contextId = request.getParameter("context_id");
int taxonId;
List<Integer> targetGenusList = Arrays
.asList(1386,773,138,234,32008,194,83553,1485,776,943,561,262,209,1637,1763,780,590,620,1279,1301,662,629);
DataApiHandler dataApi = new DataApiHandler();
if (contextType.equals("genome")) {
Genome genome = dataApi.getGenome(contextId);
taxonId = genome.getTaxonId();
} else {
taxonId = Integer.parseInt(contextId);
}
Taxonomy taxonomy = dataApi.getTaxonomy(taxonId);
List<String> taxonLineageNames = taxonomy.getLineageNames();
List<String> taxonLineageRanks = taxonomy.getLineageRanks();
List<Integer> taxonLineageIds = taxonomy.getLineageIds();
List<Taxonomy> genusList = new LinkedList<>();
for (int i = 0; i < taxonLineageIds.size(); i++) {
if (taxonLineageRanks.get(i).equals("genus") && targetGenusList.contains(taxonLineageIds.get(i))) {
Taxonomy genus = new Taxonomy();
genus.setId(taxonLineageIds.get(i));
genus.setTaxonName(taxonLineageNames.get(i));
genusList.add(genus);
}
}
if (genusList.isEmpty()) {
SolrQuery query = new SolrQuery("lineage_ids:" + taxonId + " AND taxon_rank:genus AND taxon_id:(" + StringUtils.join(targetGenusList, " OR ") + ")");
String apiResponse = dataApi.solrQuery(SolrCore.TAXONOMY, query);
Map resp = jsonReader.readValue(apiResponse);
Map respBody = (Map) resp.get("response");
genusList = dataApi.bindDocuments((List<Map>) respBody.get("docs"), Taxonomy.class);
}
request.setAttribute("contextType", contextType);
request.setAttribute("contextId", contextId);
request.setAttribute("genusList", genusList);
PortletRequestDispatcher prd = getPortletContext().getRequestDispatcher("/WEB-INF/jsp/disease_overview.jsp");
prd.include(request, response);
}
@SuppressWarnings("unchecked")
public void serveResource(ResourceRequest request, ResourceResponse response) throws PortletException, IOException {
response.setContentType("application/json");
String type = request.getParameter("type");
String cId = request.getParameter("cId");
DBDisease conn_disease = new DBDisease();
int count_total;
JSONArray results = new JSONArray();
PrintWriter writer = response.getWriter();
if (type.equals("incidence")) {
JSONObject jsonResult = new JSONObject();
// String cType = request.getParameter("cType");
// sorting
// String sort_field = request.getParameter("sort");
// String sort_dir = request.getParameter("dir");
// Map<String, String> key = new HashMap<>();
// Map<String, String> sort = null;
//
// if (sort_field != null && sort_dir != null) {
// sort = new HashMap<String, String>();
// sort.put("field", sort_field);
// sort.put("direction", sort_dir);
// }
//
// key.put("cId", cId);
// key.put("cType", cType);
count_total = 1;
jsonResult.put("total", count_total);
JSONObject obj = new JSONObject();
obj.put("rownum", "1");
obj.put("pathogen", "Pathogen");
obj.put("disease", "Disease");
obj.put("incidence", "10");
obj.put("infection", "5");
results.add(obj);
jsonResult.put("results", results);
jsonResult.writeJSONString(writer);
}
else if (type.equals("disease_tree")) {
JSONArray jsonResult = new JSONArray();
String tree_node = request.getParameter("node");
List<ResultType> items = conn_disease.getMeshHierarchy(cId, tree_node);
if (items.size() > 0) {
int min = Integer.parseInt(items.get(0).get("lvl"));
try {
for (ResultType item : items) {
if (min == Integer.parseInt(item.get("lvl"))) {
boolean flag = false;
JSONObject obj = DiseaseOverview.encodeNodeJSONObject(item);
String mesh_id = (String) obj.get("tree_node");
for (int j = 0; j < jsonResult.size(); j++) {
JSONObject temp = (JSONObject) jsonResult.get(j);
if (temp.get("tree_node").equals(mesh_id)) {
flag = true;
temp.put("pathogen", temp.get("pathogen") + "<br>" + obj.get("pathogen"));
temp.put("genome", temp.get("genome") + "<br>" + obj.get("genome"));
temp.put("vfdb", temp.get("vfdb") + "<br>" + obj.get("vfdb"));
temp.put("gad", temp.get("gad") + "<br>" + obj.get("gad"));
temp.put("ctd", temp.get("ctd") + "<br>" + obj.get("ctd"));
temp.put("taxon_id", temp.get("taxon_id") + "<br>" + obj.get("taxon_id"));
jsonResult.set(j, temp);
}
}
if (!flag) {
jsonResult.add(obj);
}
}
}
}
catch (Exception ex) {
LOGGER.error(ex.getMessage(), ex);
}
}
jsonResult.writeJSONString(writer);
}
writer.close();
}
@SuppressWarnings("unchecked")
public static JSONObject encodeNodeJSONObject(ResultType rt) {
JSONObject obj = new JSONObject();
obj.putAll(rt);
obj.put("id", rt.get("tree_node"));
obj.put("node", rt.get("tree_node"));
obj.put("expanded", "true");
if (rt.get("leaf").equals("1")) {
obj.put("leaf", "true");
}
else {
obj.put("leaf", "false");
}
return obj;
}
}
|
PATRIC3/patric3_website
|
portal/patric-diseaseview/src/edu/vt/vbi/patric/portlets/DiseaseOverview.java
|
Java
|
mit
| 7,388 |
/*****************************************************************************
* Course: CS 27500
* Name: Adam Joseph Cook
* Email: cook5@purduecal.edu
* Assignment: 1
*
* The <CODE>TestDrive</CODE> Java application simulates a car being driven
* depending on its provided fuel efficiency and fuel amount.
*
* @author Adam Joseph Cook
* <A HREF="mailto:cook5@purduecal.edu"> (cook5@purduecal.edu) </A>
*****************************************************************************/
import java.util.Scanner;
public class TestDrive
{
public static void main( String[] args ) {
Scanner sc = new Scanner(System.in);
Car car;
boolean mainDone = false;
while (!mainDone) {
System.out.print("Enter fuel efficiency: ");
double fuelEfficiency = sc.nextDouble();
car = new Car(fuelEfficiency);
if (fuelEfficiency == 0) {
// The user entered a fuel efficiency of zero, so terminate the
// program.
System.exit(0);
}
boolean outerDone = false;
while (!outerDone) {
System.out.print("Enter amount of fuel: ");
double fuelAmountToAdd = sc.nextDouble();
if (fuelAmountToAdd == 0) {
// The user entered a zero value for the fuel to add, so
// terminate this outer loop.
outerDone = true;
} else {
// Add provided fuel to the car.
car.addFuel(fuelAmountToAdd);
boolean innerDone = false;
while (!innerDone) {
System.out.print("Enter distance to travel: ");
double distanceToTravel = sc.nextDouble();
if (distanceToTravel == 0) {
// The user entered a zero distance to travel, so
// terminate this inner loop.
innerDone = true;
} else {
// Attempt to travel the distance provided with the
// car.
double distanceTraveled = car.drive(distanceToTravel);
System.out.println(" Distance actually " +
"traveled = " + distanceTraveled);
System.out.println(" Current fuelLevel = " +
car.getFuelLevel());
System.out.println(" Current odometer = " +
car.getOdometer());
}
}
}
}
}
}
}
|
adamjcook/cs27500
|
hw1/TestDrive.java
|
Java
|
mit
| 2,807 |
/*
* Copyright 2001-2013 Aspose Pty Ltd. All Rights Reserved.
*
* This file is part of Aspose.Pdf. The source code in this file
* is only intended as a supplement to the documentation, and is provided
* "as is", without warranty of any kind, either expressed or implied.
*/
package programmersguide.workingwithasposepdfgenerator.workingwithtext.textformatting.inheritingtextformat.java;
import com.aspose.pdf.*;
public class InheritingTextFormat
{
public static void main(String[] args) throws Exception
{
// The path to the documents directory.
String dataDir = "src/programmersguide/workingwithasposepdfgenerator/workingwithtext(generator)/textformatting/inheritingtextformat/data/";
}
}
|
asposemarketplace/Aspose-Pdf-Java
|
src/programmersguide/workingwithasposepdfgenerator/workingwithtext/textformatting/inheritingtextformat/java/InheritingTextFormat.java
|
Java
|
mit
| 751 |
package smash.data.tweets.pojo;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
/**
* @author Yikai Gong
*/
public class TweetCoordinates implements Serializable {
private String type;
// Order in lon-lat. Follow the GeoJSON/WKT standard which JTS is holing on
// Ref: http://www.macwright.org/lonlat/
// and http://docs.geotools.org/latest/userguide/library/referencing/epsg.html
private List<BigDecimal> coordinates;
public TweetCoordinates() {
}
public TweetCoordinates(Double lon, Double lat) {
this();
type = "point";
List<BigDecimal> l = new ArrayList<>();
l.add(0, BigDecimal.valueOf(lon));
l.add(1, BigDecimal.valueOf(lat));
coordinates = l;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<BigDecimal> getCoordinates() {
return coordinates;
}
public void setCoordinates(List<BigDecimal> coordinates) {
this.coordinates = coordinates;
}
public BigDecimal getLon() {
return coordinates.get(0);
}
public BigDecimal getLat() {
return coordinates.get(1);
}
}
|
project-rhd/smash-app
|
smash-tweets/smash-tweets-data/src/main/java/smash/data/tweets/pojo/TweetCoordinates.java
|
Java
|
mit
| 1,190 |
package com.bellini.recipecatalog.exception.recipe;
public class NotExistingRecipeException extends RuntimeException {
private static final long serialVersionUID = 2975419159984559986L;
private Long id;
public NotExistingRecipeException(Long id) {
super();
if (id == null) {
throw new IllegalArgumentException("Null object used as initializer of the exception");
}
this.id = id;
}
@Override
public String getMessage() {
return "Recipe " + id + " not found in database";
}
}
|
riccardobellini/recipecatalog-backend-java
|
src/main/java/com/bellini/recipecatalog/exception/recipe/NotExistingRecipeException.java
|
Java
|
mit
| 559 |
package biz.golek.whattodofordinner.view.activities;
import android.support.annotation.NonNull;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.greenrobot.eventbus.Subscribe;
import java.util.List;
import biz.golek.whattodofordinner.R;
import biz.golek.whattodofordinner.business.contract.request_data.GeneratePromptsRequestData;
import biz.golek.whattodofordinner.business.contract.response_data.DinnerListItem;
import biz.golek.whattodofordinner.view.ActivityDependencyProvider;
import biz.golek.whattodofordinner.view.adapters.DinnerListItemArrayAdapter;
import biz.golek.whattodofordinner.view.awareness.IActivityDependencyProviderAware;
import biz.golek.whattodofordinner.view.messages.DinnerDeletedMessage;
import biz.golek.whattodofordinner.view.messages.DinnerUpdatedMessage;
import biz.golek.whattodofordinner.view.view_models.PromptsActivityViewModel;
public class PromptsActivity extends AppCompatActivity implements IActivityDependencyProviderAware {
private String PROMPTS_LIST_VIEW_MODEL = "promptsListViewModel";
private PromptsActivityViewModel viewModel;
private ActivityDependencyProvider activityDependencyProvider;
private ArrayAdapter adapter;
private ListView listView;
private DinnerListItem nonOfThisListItem;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_prompts);
setupActionBar();
if (savedInstanceState != null)
viewModel = (PromptsActivityViewModel) savedInstanceState.getSerializable(PROMPTS_LIST_VIEW_MODEL);
else
viewModel = (PromptsActivityViewModel)getIntent().getSerializableExtra("VIEW_MODEL");
listView = (ListView) findViewById(R.id.prompts_list);
List<DinnerListItem> prompts = viewModel.prompts;
nonOfThisListItem = new DinnerListItem();
nonOfThisListItem.id = -1L;
nonOfThisListItem.name = getResources().getString(R.string.non_of_this);
prompts.add(nonOfThisListItem);
adapter = new DinnerListItemArrayAdapter(this, prompts);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
DinnerListItem item = (DinnerListItem)listView.getItemAtPosition(position);
if (item == nonOfThisListItem)
activityDependencyProvider.getGeneratePromptsController().Run(getDenyRequestData());
else
activityDependencyProvider.getDinnerChosenController().Run(item.id, item.name);
}
});
registerForContextMenu(listView);
activityDependencyProvider.getEventBusProvider().get().register(this);
}
@Subscribe
public void onDinnerDeleteMessage(DinnerDeletedMessage event) {
DinnerListItem dinner = null;
for (DinnerListItem d : viewModel.prompts)
if (d.id.equals(event.getId()))
dinner = d;
if (dinner != null)
viewModel.prompts.remove(dinner);
adapter.notifyDataSetChanged();
}
@Subscribe
public void onDinnerUpdatedMessage(DinnerUpdatedMessage event) {
boolean updated = false;
for (DinnerListItem dinner : viewModel.prompts) {
if (dinner.id.equals(event.getId())) {
dinner.id = event.getId();
dinner.name = event.getName();
updated = true;
}
}
if (updated)
adapter.notifyDataSetChanged();
}
@Override
protected void onDestroy() {
super.onDestroy();
activityDependencyProvider.getEventBusProvider().get().unregister(this);
}
@NonNull
private GeneratePromptsRequestData getDenyRequestData() {
GeneratePromptsRequestData rd = new GeneratePromptsRequestData();
rd.soup_profile = viewModel.getSoupProfile();
rd.vegetarian_profile = viewModel.getVegetarianProfile();
rd.maximum_duration = viewModel.getMaximumDuration();
Long[] oldExcludes = viewModel.getExcludes();
List<DinnerListItem> prompts = viewModel.prompts;
int oldExcludesLength = oldExcludes!= null ? oldExcludes.length : 0;
int promptsSize = prompts != null ? prompts.size() : 0;
if (oldExcludesLength + promptsSize > 0)
{
Long[] excludes = new Long[oldExcludesLength + promptsSize];
Integer index = 0;
if (oldExcludes != null)
{
for (Long id: oldExcludes) {
excludes[index++] = id;
}
}
if (prompts != null)
{
for (DinnerListItem dli: prompts) {
excludes[index++] = dli.id;
}
}
rd.excludes = excludes;
}
return rd;
}
/**
* Set up the {@link android.app.ActionBar}, if the API is available.
*/
private void setupActionBar() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
// Show the Up button in the action bar.
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId()==R.id.prompts_list) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
DinnerListItem dinnerListItem = (DinnerListItem)listView.getItemAtPosition(info.position);
if (dinnerListItem != nonOfThisListItem)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.dinner_list_item_menu, menu);
}
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
DinnerListItem dinnerListItem = (DinnerListItem)listView.getItemAtPosition(info.position);
switch(item.getItemId()) {
case R.id.dinner_list_item_menu_edit:
activityDependencyProvider.getEditDinnerController().Run(dinnerListItem.id);
return true;
case R.id.dinner_list_item_menu_delete:
activityDependencyProvider.getDeleteDinnerController().Run(dinnerListItem.id);
return true;
default:
return super.onContextItemSelected(item);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
outState.putSerializable(PROMPTS_LIST_VIEW_MODEL, viewModel);
super.onSaveInstanceState(outState);
}
@Override
public void Set(ActivityDependencyProvider item) {
activityDependencyProvider = item;
}
}
|
bartoszgolek/whattodofordinner
|
app/src/main/java/biz/golek/whattodofordinner/view/activities/PromptsActivity.java
|
Java
|
mit
| 7,640 |
package twg2.template.codeTemplate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* @param <T> the {@link ClassInfo} to build
*
* @author TeamworkGuy2
* @since 2015-1-24
*/
public final class ClassTemplateBuilder<T extends ClassInfo> {
private T tmpl;
public ClassTemplateBuilder(T tmpl) {
this.tmpl = tmpl;
}
public ClassTemplateBuilder(T tmpl, String className, String packageName) {
this.tmpl = tmpl;
tmpl.setClassName(className);
tmpl.setPackageName(packageName);
}
public ClassTemplateBuilder<T> setPackageName(String packageName) {
tmpl.setPackageName(packageName);
return this;
}
/** Alias for {@link #addImportStatement(Class...)} */
@SafeVarargs
public final ClassTemplateBuilder<T> imports(Class<?>... importStatements) {
return addImportStatement(importStatements);
}
@SafeVarargs
public final ClassTemplateBuilder<T> addImportStatement(Class<?>... importStatements) {
List<String> statements = tmpl.getImportStatements();
if(statements == null) {
statements = new ArrayList<>();
tmpl.setImportStatements(statements);
}
if(importStatements == null) {
return this;
}
for(Class<?> importStatement : importStatements) {
statements.add(importStatement.getCanonicalName());
}
return this;
}
/** Alias for {@link #addImportStatement(String...)} */
@SafeVarargs
public final ClassTemplateBuilder<T> imports(String... importStatements) {
return addImportStatement(importStatements);
}
@SafeVarargs
public final ClassTemplateBuilder<T> addImportStatement(String... importStatements) {
List<String> imports = tmpl.getImportStatements();
if(imports == null) {
imports = new ArrayList<>();
tmpl.setImportStatements(imports);
}
if(importStatements == null) {
return this;
}
for(String importStatement : importStatements) {
imports.add(importStatement);
}
return this;
}
public ClassTemplateBuilder<T> setClassModifier(String classAccessModifier) {
tmpl.setClassModifier(classAccessModifier);
return this;
}
public ClassTemplateBuilder<T> setClassType(String classType) {
tmpl.setClassType(classType);
return this;
}
public ClassTemplateBuilder<T> addTypeParameters(Iterable<? extends Map.Entry<String, String>> classParameterNamesAndTypes) {
for(Map.Entry<String, String> classParam : classParameterNamesAndTypes) {
addTypeParameter(classParam.getKey(), classParam.getValue());
}
return this;
}
public ClassTemplateBuilder<T> addTypeParameter(String classParameterName, String classTypeParameterDefinition) {
if(tmpl.getClassTypeParameterDefinitions() == null) {
tmpl.setClassTypeParameterDefinitions(new ArrayList<>());
}
if(tmpl.getClassTypeParameterNames() == null) {
tmpl.setClassTypeParameterNames(new ArrayList<>());
}
tmpl.getClassTypeParameterNames().add(classParameterName);
tmpl.getClassTypeParameterDefinitions().add(classTypeParameterDefinition);
return this;
}
public ClassTemplateBuilder<T> setClassName(String className) {
tmpl.setClassName(className);
return this;
}
/** Alias for {@link #setExtendClassName(Class)} */
public ClassTemplateBuilder<T> extend(Class<?> extendClassName) {
return setExtendClassName(extendClassName);
}
public ClassTemplateBuilder<T> setExtendClassName(Class<?> extendClassName) {
tmpl.setExtendClassName(extendClassName.getCanonicalName().replace("java.lang.", ""));
return this;
}
/** Alias for {@link #setExtendClassName(String)} */
public ClassTemplateBuilder<T> extend(String extendClassName) {
return setExtendClassName(extendClassName);
}
public ClassTemplateBuilder<T> setExtendClassName(String extendClassName) {
tmpl.setExtendClassName(extendClassName);
return this;
}
/** Alias for {@link #addImplementClassNames(String...)} */
@SafeVarargs
public final ClassTemplateBuilder<T> implement(String... implementClassNames) {
return addImplementClassNames(implementClassNames);
}
@SafeVarargs
public final ClassTemplateBuilder<T> addImplementClassNames(String... implementClassNames) {
List<String> implementNames = tmpl.getImplementClassNames();
if(implementNames == null) {
implementNames = new ArrayList<>();
tmpl.setImplementClassNames(implementNames);
}
if(implementClassNames == null) {
return this;
}
for(String implementClassName : implementClassNames) {
implementNames.add(implementClassName);
}
return this;
}
/** Alias for {@link #addImplementClassNames(Class...)} */
@SafeVarargs
public final ClassTemplateBuilder<T> implement(Class<?>... implementClassNames) {
return addImplementClassNames(implementClassNames);
}
@SafeVarargs
public final ClassTemplateBuilder<T> addImplementClassNames(Class<?>... implementClassNames) {
List<String> implementNames = tmpl.getImplementClassNames();
if(implementNames == null) {
implementNames = new ArrayList<>();
tmpl.setImplementClassNames(implementNames);
}
if(implementClassNames == null) {
return this;
}
for(Class<?> implementClassName : implementClassNames) {
implementNames.add(implementClassName.getCanonicalName().replace("java.lang.", ""));
}
return this;
}
public T getTemplate() {
return tmpl;
}
public static ClassTemplateBuilder<ClassInfo> newInst() {
return new ClassTemplateBuilder<ClassInfo>(new ClassTemplate());
}
public static <T extends ClassInfo> ClassTemplateBuilder<T> of(T inst) {
return new ClassTemplateBuilder<>(inst);
}
public static <T extends ClassInfo> ClassTemplateBuilder<T> of(T inst, String className, String packageName) {
return new ClassTemplateBuilder<>(inst, className, packageName);
}
public static ClassTemplateBuilder<ClassTemplate> of(String className) {
return of(className, null);
}
public static ClassTemplateBuilder<ClassTemplate> of(String className, String packageName) {
return new ClassTemplateBuilder<>(new ClassTemplate(), className, packageName);
}
}
|
TeamworkGuy2/JTwg2Templating
|
src/twg2/template/codeTemplate/ClassTemplateBuilder.java
|
Java
|
mit
| 5,967 |
/*
* Globalcode - "The Developers Company"
*
* Academia do Java
*
*/
public abstract class Agencia {
private String numero;
private Banco banco;
/**
* @param num
* Numero da agencia
* @param bc
* banco ao qual a agencia pertence
*/
public Agencia(String num, Banco bc) {
numero = num;
banco = bc;
}
/**
* @return numero do banco
*/
public Banco getBanco() {
return banco;
}
/**
* @return numero da agencia
*/
public String getNumero() {
return numero;
}
/**
* @param b
* banco
*/
public void setBanco(Banco b) {
banco = b;
}
/**
* @param num
* numero da agencia
*/
public void setNumero(String num) {
numero = num;
}
/**
* Metodo para impressao de todos os dados da classe
*/
public void imprimeDados() {
System.out.println("Agencia no. " + numero);
banco.imprimeDados();
}
public void ajustarLimites(ContaEspecial[] contasEspeciais) {
System.out.println("===================================================================");
System.out.println("Agencia: " + this.getNumero() + " ajustando limites");
for (int i = 0; i < contasEspeciais.length; i++) {
ContaEspecial ce = contasEspeciais[i];
if (ce != null) {
if (ce.getAgencia() != this) {
System.out.println("A conta " + ce.getNumero() + " nao pertence a esta agencia");
} else {
double limiteAntigo = ce.getLimite();
ajustarLimiteIndividual(ce);
double limiteAjustado = ce.getLimite();
System.out.println("conta " + ce.getNumero() +
"\tlimite antigo: " + limiteAntigo +
"\tlimite ajustado: " + limiteAjustado);
}
}
}
System.out.println("limites ajustados");
System.out.println("===================================================================");
}
protected abstract void ajustarLimiteIndividual(ContaEspecial contaEspecial);
public Conta abrirConta(Cliente titular, double saldoInicial) {
String numeroConta = "" + (int) (Math.random() * 9999999);
if (saldoInicial <= 500) {
return new Conta(saldoInicial, numeroConta, titular, this);
} else if (saldoInicial > 500 && saldoInicial <= 1000) {
String hoje = "" + new java.util.Date();
return new ContaPoupanca(saldoInicial, numeroConta, titular, this, hoje);
} else {
return null;
}
}
}
|
andersonsilvade/workspacejava
|
engsoft1globalcode/aj2lab10_02/src/Agencia.java
|
Java
|
mit
| 2,802 |
package com.ccsi.commons.dto.tenant;
/**
* @author mbmartinez
*/
public class BaseCcsiInfo {
protected Long id;
protected String name;
protected String description;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
|
lordmarkm/ccsi
|
ccsi-commons/src/main/java/com/ccsi/commons/dto/tenant/BaseCcsiInfo.java
|
Java
|
mit
| 595 |
package flow;
/**
* This interface is used to define the name of variables that are
* declared in the call flow. All variables are defined as
* <code>public static final String</code>, which allows user-defined
* code to reference variable names by the Java variable name.
* Last generated by Orchestration Designer at: 2013-FEB-03 08:27:04 PM
*/
public interface IProjectVariables {
//{{START:PROJECT:VARIABLES
/**
* This is a reserved block of variable name definitions.
* The variable names defined here can be used as the key
* to get the <code>com.avaya.sce.runtime.Variable</code>
* from the <code>SCESession</code> at runtime.<br>
*
* For example, given a variable name <code>phoneNum</code>,
* user-defined code should access the variable in this format:<PRE>
* Variable phNum = mySession.getVariable(IProjectVariables.PHONE_NUM);
* if ( phNum != null ) {
* // do something with the variable
* }</PRE>
*
* This block of code is generated automatically by Orchestration Designer and should not
* be manually edited as changes may be overwritten by future code generation.
* Last generated by Orchestration Designer at: 2013-JUN-19 09:09:36 PM
*/
public static final String MAIN_MENU = "MainMenu";
public static final String BLIND_TRANSFER = "BlindTransfer";
public static final String TIME = "time";
public static final String REDIRECTINFO = "redirectinfo";
public static final String MAIN_MENU_TEXT = "MainMenuText";
public static final String SESSION = "session";
public static final String DD_LAST_EXCEPTION = "ddLastException";
public static final String DATE = "date";
public static final String SHAREDUUI = "shareduui";
//}}END:PROJECT:VARIABLES
//{{START:PROJECT:VARIABLEFIELDS
public static final String MAIN_MENU_FIELD_COLUMN_0 = "Column0";
public static final String MAIN_MENU_FIELD_CONFIDENCE = "confidence";
public static final String MAIN_MENU_FIELD_INPUTMODE = "inputmode";
public static final String MAIN_MENU_FIELD_INTERPRETATION = "interpretation";
public static final String MAIN_MENU_FIELD_NOINPUTCOUNT = "noinputcount";
public static final String MAIN_MENU_FIELD_NOMATCHCOUNT = "nomatchcount";
public static final String MAIN_MENU_FIELD_UTTERANCE = "utterance";
public static final String MAIN_MENU_FIELD_VALUE = "value";
public static final String TIME_FIELD_AUDIO = "audio";
public static final String TIME_FIELD_HOUR = "hour";
public static final String TIME_FIELD_MILLISECOND = "millisecond";
public static final String TIME_FIELD_MINUTE = "minute";
public static final String TIME_FIELD_SECOND = "second";
public static final String TIME_FIELD_TIMEZONE = "timezone";
public static final String REDIRECTINFO_FIELD_PRESENTATIONINFO = "presentationinfo";
public static final String REDIRECTINFO_FIELD_REASON = "reason";
public static final String REDIRECTINFO_FIELD_SCREENINGINFO = "screeninginfo";
public static final String REDIRECTINFO_FIELD_URI = "uri";
public static final String SESSION_FIELD_AAI = "aai";
public static final String SESSION_FIELD_ANI = "ani";
public static final String SESSION_FIELD_CALLTAG = "calltag";
public static final String SESSION_FIELD_CHANNEL = "channel";
public static final String SESSION_FIELD_CONVERSEFIRST = "conversefirst";
public static final String SESSION_FIELD_CONVERSESECOND = "conversesecond";
public static final String SESSION_FIELD_CURRENTLANGUAGE = "currentlanguage";
public static final String SESSION_FIELD_DNIS = "dnis";
public static final String SESSION_FIELD_EXIT_CUSTOMER_ID = "exitCustomerId";
public static final String SESSION_FIELD_EXIT_INFO_1 = "exitInfo1";
public static final String SESSION_FIELD_EXIT_INFO_2 = "exitInfo2";
public static final String SESSION_FIELD_EXIT_PREFERRED_PATH = "exitPreferredPath";
public static final String SESSION_FIELD_EXIT_REASON = "exitReason";
public static final String SESSION_FIELD_EXIT_TOPIC = "exitTopic";
public static final String SESSION_FIELD_LASTERROR = "lasterror";
public static final String SESSION_FIELD_MEDIATYPE = "mediatype";
public static final String SESSION_FIELD_MESSAGE_TYPE = "messageType";
public static final String SESSION_FIELD_PROTOCOLNAME = "protocolname";
public static final String SESSION_FIELD_PROTOCOLVERSION = "protocolversion";
public static final String SESSION_FIELD_SESSIONID = "sessionid";
public static final String SESSION_FIELD_SESSIONLABEL = "sessionlabel";
public static final String SESSION_FIELD_SHAREDMODE = "sharedmode";
public static final String SESSION_FIELD_UCID = "ucid";
public static final String SESSION_FIELD_UUI = "uui";
public static final String SESSION_FIELD_VIDEOBITRATE = "videobitrate";
public static final String SESSION_FIELD_VIDEOCODEC = "videocodec";
public static final String SESSION_FIELD_VIDEOENABLED = "videoenabled";
public static final String SESSION_FIELD_VIDEOFARFMTP = "videofarfmtp";
public static final String SESSION_FIELD_VIDEOFORMAT = "videoformat";
public static final String SESSION_FIELD_VIDEOFPS = "videofps";
public static final String SESSION_FIELD_VIDEOHEIGHT = "videoheight";
public static final String SESSION_FIELD_VIDEONEARFMTP = "videonearfmtp";
public static final String SESSION_FIELD_VIDEOWIDTH = "videowidth";
public static final String SESSION_FIELD_VPCALLEDEXTENSION = "vpcalledextension";
public static final String SESSION_FIELD_VPCONVERSEONDATA = "vpconverseondata";
public static final String SESSION_FIELD_VPCOVERAGEREASON = "vpcoveragereason";
public static final String SESSION_FIELD_VPCOVERAGETYPE = "vpcoveragetype";
public static final String SESSION_FIELD_VPRDNIS = "vprdnis";
public static final String SESSION_FIELD_VPREPORTURL = "vpreporturl";
public static final String DD_LAST_EXCEPTION_FIELD_ERRORCODE = "errorcode";
public static final String DD_LAST_EXCEPTION_FIELD_MESSAGE = "message";
public static final String DD_LAST_EXCEPTION_FIELD_OBJECT = "object";
public static final String DD_LAST_EXCEPTION_FIELD_STACKTRACE = "stacktrace";
public static final String DD_LAST_EXCEPTION_FIELD_TYPE = "type";
public static final String DATE_FIELD_AUDIO = "audio";
public static final String DATE_FIELD_DAYOFMONTH = "dayofmonth";
public static final String DATE_FIELD_DAYOFWEEK = "dayofweek";
public static final String DATE_FIELD_DAYOFWEEKNUM = "dayofweeknum";
public static final String DATE_FIELD_DAYOFYEAR = "dayofyear";
public static final String DATE_FIELD_MONTH = "month";
public static final String DATE_FIELD_MONTHINYEAR = "monthinyear";
public static final String DATE_FIELD_YEAR = "year";
public static final String SHAREDUUI_FIELD_ID = "id";
public static final String SHAREDUUI_FIELD_VALUE = "value";
//}}END:PROJECT:VARIABLEFIELDS
}
|
RadishSystems/choiceview-webapi-avaya-demo
|
RadishTest/WEB-INF/src/flow/IProjectVariables.java
|
Java
|
mit
| 6,735 |
package piskvork;
/**
* Root interface for a Piskvork command. A command must provide a string to
* send to the AI, and a method to validate the response.
*/
public interface PiskvorkCommand {
/**
* Get the string for this command to send to the AI.
* @return String identifier of the command, e.g. TURN or MESSAGE, plus
* any other parameters to send to the AI.
*/
String getCommandString();
/**
* Return whether or not this command requires a response.
* @return True by default, overridden to false if required.
*/
default boolean requiresResponse() {
return true;
}
/**
* Validate a response for this command.
* @param response Response to validate
* @return Boolean representing whether this response is valid
*/
default boolean validateResponse(String response) {
return true;
}
}
|
haslam22/gomoku
|
src/main/java/piskvork/PiskvorkCommand.java
|
Java
|
mit
| 898 |
/* Copyright (C) 2001, 2008 United States Government as represented by
the Administrator of the National Aeronautics and Space Administration.
All Rights Reserved.
*/
package gov.nasa.worldwind.render;
import gov.nasa.worldwind.geom.*;
import gov.nasa.worldwind.render.airspaces.*;
import javax.media.opengl.*;
/**
* @author brownrigg
* @version $Id: SurfaceCircle2.java 9230 2009-03-06 05:36:26Z dcollins $
*/
public class SurfaceCircle2 extends CappedCylinder
{
public SurfaceCircle2(LatLon location, double radius)
{
super(location, radius);
}
public SurfaceCircle2(AirspaceAttributes shapeAttributes)
{
super(shapeAttributes);
}
public SurfaceCircle2()
{
super();
}
protected void doRenderGeometry(DrawContext dc, String drawStyle)
{
beginDrawShape(dc);
super.doRenderGeometry(dc, drawStyle);
endDrawShape(dc);
}
protected void beginDrawShape(DrawContext dc)
{
// Modify the projection transform to shift the depth values slightly toward the camera in order to
// ensure the shape is selected during depth buffering.
GL gl = dc.getGL();
float[] pm = new float[16];
gl.glGetFloatv(GL.GL_PROJECTION_MATRIX, pm, 0);
pm[10] *= .8; // TODO: See Lengyel 2 ed. Section 9.1.2 to compute optimal/minimal offset
gl.glPushAttrib(GL.GL_TRANSFORM_BIT);
gl.glMatrixMode(GL.GL_PROJECTION);
gl.glPushMatrix();
gl.glLoadMatrixf(pm, 0);
}
protected void endDrawShape(DrawContext dc)
{
GL gl = dc.getGL();
gl.glMatrixMode(GL.GL_PROJECTION);
gl.glPopMatrix();
gl.glPopAttrib();
}
}
|
caadxyz/Macro-Thinking-Micro-action
|
experimental/gov/nasa/worldwind/render/SurfaceCircle2.java
|
Java
|
mit
| 1,719 |
package com.martin.lolli;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
/**
* Fragment used for managing interactions for and presentation of a navigation drawer.
* See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
* design guidelines</a> for a complete explanation of the behaviors implemented here.
*/
public class NavigationDrawerFragment extends Fragment {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
public NavigationDrawerFragment() {
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
selectItem(mCurrentSelectedPosition, mFromSavedInstanceState);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of actions in the action bar.
setHasOptionsMenu(true);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
final Bundle savedInstanceState) {
mDrawerListView = (ListView) inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position, false);
}
});
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{
getString(R.string.title_section1),
getString(R.string.title_section2),
getString(R.string.title_section3),
getString(R.string.title_section4)
}
));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
return mDrawerListView;
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* @param fragmentId The android:id of this fragment in its activity's layout.
* @param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().invalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
@Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(
int position, boolean fromSavedInstanceState) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position, fromSavedInstanceState);
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
@Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return getActivity().getActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position, boolean fromSavedInstanceState);
}
}
|
martindisch/Lolli
|
app/src/main/java/com/martin/lolli/NavigationDrawerFragment.java
|
Java
|
mit
| 10,019 |
package org.bouncycastle.asn1.cms;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1Integer;
import org.bouncycastle.asn1.ASN1Object;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.ASN1Set;
import org.bouncycastle.asn1.BERSequence;
import org.bouncycastle.asn1.BERTaggedObject;
public class EncryptedData
extends ASN1Object
{
private ASN1Integer version;
private EncryptedContentInfo encryptedContentInfo;
private ASN1Set unprotectedAttrs;
public static EncryptedData getInstance(Object o)
{
if (o instanceof EncryptedData)
{
return (EncryptedData)o;
}
if (o != null)
{
return new EncryptedData(ASN1Sequence.getInstance(o));
}
return null;
}
public EncryptedData(EncryptedContentInfo encInfo)
{
this(encInfo, null);
}
public EncryptedData(EncryptedContentInfo encInfo, ASN1Set unprotectedAttrs)
{
this.version = new ASN1Integer((unprotectedAttrs == null) ? 0 : 2);
this.encryptedContentInfo = encInfo;
this.unprotectedAttrs = unprotectedAttrs;
}
private EncryptedData(ASN1Sequence seq)
{
this.version = ASN1Integer.getInstance(seq.getObjectAt(0));
this.encryptedContentInfo = EncryptedContentInfo.getInstance(seq.getObjectAt(1));
if (seq.size() == 3)
{
this.unprotectedAttrs = ASN1Set.getInstance(seq.getObjectAt(2));
}
}
public ASN1Integer getVersion()
{
return version;
}
public EncryptedContentInfo getEncryptedContentInfo()
{
return encryptedContentInfo;
}
public ASN1Set getUnprotectedAttrs()
{
return unprotectedAttrs;
}
/**
* <pre>
* EncryptedData ::= SEQUENCE {
* version CMSVersion,
* encryptedContentInfo EncryptedContentInfo,
* unprotectedAttrs [1] IMPLICIT UnprotectedAttributes OPTIONAL }
* </pre>
* @return a basic ASN.1 object representation.
*/
public ASN1Primitive toASN1Primitive()
{
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(version);
v.add(encryptedContentInfo);
if (unprotectedAttrs != null)
{
v.add(new BERTaggedObject(false, 1, unprotectedAttrs));
}
return new BERSequence(v);
}
}
|
sake/bouncycastle-java
|
src/org/bouncycastle/asn1/cms/EncryptedData.java
|
Java
|
mit
| 2,516 |
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
/**
* Created by jackrosenhauer on 5/5/15.
*/
public class Main {
public static void main(String[] args){
final int DEFAULT_PORT = 8080; // For security reasons, only root can use ports < 1024.
int portNumber = args.length > 1 ? Integer.parseInt(args[0]) : DEFAULT_PORT;
ServerSocket serverSocket;
int threadsCreated = 0;
try{
serverSocket = new ServerSocket(portNumber);
while (true) {
Thread t = new Worker(serverSocket);
t.start();
threadsCreated++;
System.out.println("Threads Created & Processed: " + threadsCreated);
}
} catch (IOException e) {
System.err.println("Oops! " + e);
} catch (Exception e){
System.out.println("Something else went terribly wrong");
e.printStackTrace();
}
}
}
|
jackrosenhauer/web-server
|
src/Main.java
|
Java
|
mit
| 983 |
package com.agamemnus.cordova.plugin;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.ads.InterstitialAd;
import com.google.android.gms.ads.mediation.admob.AdMobExtras;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.PluginResult;
import org.apache.cordova.PluginResult.Status;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.os.Bundle;
import java.util.Iterator;
import java.util.Random;
import android.provider.Settings;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import android.util.Log;
public class AdMob extends CordovaPlugin {
// Common tag used for logging statements.
private static final String LOGTAG = "AdMob";
private static final boolean CORDOVA_4 = Integer.valueOf(CordovaWebView.CORDOVA_VERSION.split("\\.")[0]) >= 4;
// Cordova Actions.
private static final String ACTION_SET_OPTIONS = "setOptions";
private static final String ACTION_CREATE_BANNER_VIEW = "createBannerView";
private static final String ACTION_DESTROY_BANNER_VIEW = "destroyBannerView";
private static final String ACTION_REQUEST_AD = "requestAd";
private static final String ACTION_SHOW_AD = "showAd";
private static final String ACTION_CREATE_INTERSTITIAL_VIEW = "createInterstitialView";
private static final String ACTION_REQUEST_INTERSTITIAL_AD = "requestInterstitialAd";
private static final String ACTION_SHOW_INTERSTITIAL_AD = "showInterstitialAd";
// Options.
private static final String OPT_AD_ID = "adId";
private static final String OPT_AD_SIZE = "adSize";
private static final String OPT_BANNER_AT_TOP = "bannerAtTop";
private static final String OPT_OVERLAP = "overlap";
private static final String OPT_OFFSET_TOPBAR = "offsetTopBar";
private static final String OPT_IS_TESTING = "isTesting";
private static final String OPT_AD_EXTRAS = "adExtras";
private static final String OPT_AUTO_SHOW = "autoShow";
// The adView to display to the user.
private ViewGroup parentView;
private AdView adView;
// If the user wants banner view overlap webview, we will need this layout.
private RelativeLayout adViewLayout = null;
// The interstitial ad to display to the user.
private InterstitialAd interstitialAd;
private AdSize adSize = AdSize.SMART_BANNER;
private String adId = "";
private boolean bannerAtTop = false;
private boolean bannerOverlap = false;
private boolean offsetTopBar = false;
private boolean isTesting = false;
private boolean bannerShow = true;
private boolean autoShow = true;
private boolean autoShowBanner = true;
private boolean autoShowInterstitial = true;
private boolean bannerVisible = false;
private boolean isGpsAvailable = false;
private JSONObject adExtras = null;
@Override public void initialize (CordovaInterface cordova, CordovaWebView webView) {
super.initialize (cordova, webView);
isGpsAvailable = (GooglePlayServicesUtil.isGooglePlayServicesAvailable(cordova.getActivity()) == ConnectionResult.SUCCESS);
Log.w (LOGTAG, String.format("isGooglePlayServicesAvailable: %s", isGpsAvailable ? "true" : "false"));
}
// This is the main method for the AdMob plugin. All API calls go through here.
// This method determines the action, and executes the appropriate call.
//
// @param action The action that the plugin should execute.
// @param inputs The input parameters for the action.
// @param callbackContext The callback context.
// @return A PluginResult representing the result of the provided action.
// A status of INVALID_ACTION is returned if the action is not recognized.
@Override public boolean execute (String action, JSONArray inputs, CallbackContext callbackContext) throws JSONException {
PluginResult result = null;
if (ACTION_SET_OPTIONS.equals(action)) {
JSONObject options = inputs.optJSONObject(0);
result = executeSetOptions(options, callbackContext);
} else if (ACTION_CREATE_BANNER_VIEW.equals(action)) {
JSONObject options = inputs.optJSONObject(0);
result = executeCreateBannerView(options, callbackContext);
} else if (ACTION_CREATE_INTERSTITIAL_VIEW.equals(action)) {
JSONObject options = inputs.optJSONObject(0);
result = executeCreateInterstitialView(options, callbackContext);
} else if (ACTION_DESTROY_BANNER_VIEW.equals(action)) {
result = executeDestroyBannerView(callbackContext);
} else if (ACTION_REQUEST_INTERSTITIAL_AD.equals(action)) {
JSONObject options = inputs.optJSONObject(0);
result = executeRequestInterstitialAd(options, callbackContext);
} else if (ACTION_REQUEST_AD.equals(action)) {
JSONObject options = inputs.optJSONObject(0);
result = executeRequestAd(options, callbackContext);
} else if (ACTION_SHOW_AD.equals(action)) {
boolean show = inputs.optBoolean(0);
result = executeShowAd(show, callbackContext);
} else if (ACTION_SHOW_INTERSTITIAL_AD.equals(action)) {
boolean show = inputs.optBoolean(0);
result = executeShowInterstitialAd(show, callbackContext);
} else {
Log.d (LOGTAG, String.format("Invalid action passed: %s", action));
result = new PluginResult(Status.INVALID_ACTION);
}
if (result != null) callbackContext.sendPluginResult (result);
return true;
}
private PluginResult executeSetOptions (JSONObject options, CallbackContext callbackContext) {
Log.w (LOGTAG, "executeSetOptions");
this.setOptions (options);
callbackContext.success ();
return null;
}
private void setOptions (JSONObject options) {
if (options == null) return;
if (options.has(OPT_AD_ID)) this.adId = options.optString (OPT_AD_ID);
if (options.has(OPT_AD_SIZE)) this.adSize = adSizeFromString (options.optString(OPT_AD_SIZE));
if (options.has(OPT_BANNER_AT_TOP)) this.bannerAtTop = options.optBoolean (OPT_BANNER_AT_TOP);
if (options.has(OPT_OVERLAP)) this.bannerOverlap = options.optBoolean (OPT_OVERLAP);
if (options.has(OPT_OFFSET_TOPBAR)) this.offsetTopBar = options.optBoolean (OPT_OFFSET_TOPBAR);
if (options.has(OPT_IS_TESTING)) this.isTesting = options.optBoolean (OPT_IS_TESTING);
if (options.has(OPT_AD_EXTRAS)) this.adExtras = options.optJSONObject (OPT_AD_EXTRAS);
if (options.has(OPT_AUTO_SHOW)) this.autoShow = options.optBoolean (OPT_AUTO_SHOW);
}
// Parses the create banner view input parameters and runs the create banner
// view action on the UI thread. If this request is successful, the developer
// should make the requestAd call to request an ad for the banner.
//
// @param inputs The JSONArray representing input parameters. This function
// expects the first object in the array to be a JSONObject with the input parameters.
// @return A PluginResult representing whether or not the banner was created successfully.
private PluginResult executeCreateBannerView (JSONObject options, final CallbackContext callbackContext) {
this.setOptions (options);
autoShowBanner = autoShow;
cordova.getActivity().runOnUiThread (new Runnable() {
@Override public void run () {
boolean adViewWasNull = (adView == null);
if (adView == null) {
adView = new AdView (cordova.getActivity());
adView.setAdUnitId (adId);
adView.setAdSize (adSize);
}
if (adView.getParent() != null) ((ViewGroup)adView.getParent()).removeView(adView);
if (adViewLayout == null) {
adViewLayout = new RelativeLayout(cordova.getActivity());
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
if (CORDOVA_4) {
((ViewGroup) webView.getView().getParent()).addView(adViewLayout, params);
} else {
((ViewGroup) webView).addView(adViewLayout, params);
}
}
bannerVisible = false;
adView.loadAd (buildAdRequest());
if (adViewWasNull) adView.setAdListener (new BannerListener());
if (autoShowBanner) executeShowAd (true, null);
callbackContext.success ();
}
});
return null;
}
private PluginResult executeDestroyBannerView (CallbackContext callbackContext) {
Log.w (LOGTAG, "executeDestroyBannerView");
final CallbackContext delayCallback = callbackContext;
cordova.getActivity().runOnUiThread (new Runnable() {
@Override public void run () {
if (adView != null) {
ViewGroup parentView = (ViewGroup)adView.getParent();
if (parentView != null) parentView.removeView(adView);
adView.destroy ();
adView = null;
}
bannerVisible = false;
delayCallback.success ();
}
});
return null;
}
// Parses the create interstitial view input parameters and runs the create interstitial
// view action on the UI thread. If this request is successful, the developer should make the requestAd call to request an ad for the banner.
//
// @param inputs The JSONArray representing input parameters. This function expects the first object in the array to be a JSONObject with the input parameters.
// @return A PluginResult representing whether or not the banner was created successfully.
private PluginResult executeCreateInterstitialView (JSONObject options, CallbackContext callbackContext) {
this.setOptions (options);
autoShowInterstitial = autoShow;
final CallbackContext delayCallback = callbackContext;
cordova.getActivity().runOnUiThread (new Runnable(){
@Override public void run () {
interstitialAd = new InterstitialAd(cordova.getActivity());
interstitialAd.setAdUnitId (adId);
interstitialAd.loadAd (buildAdRequest());
interstitialAd.setAdListener (new InterstitialListener());
delayCallback.success ();
}
});
return null;
}
private AdRequest buildAdRequest () {
AdRequest.Builder request_builder = new AdRequest.Builder();
if (isTesting) {
// This will request test ads on the emulator and deviceby passing this hashed device ID.
String ANDROID_ID = Settings.Secure.getString(cordova.getActivity().getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
String deviceId = md5(ANDROID_ID).toUpperCase();
request_builder = request_builder.addTestDevice(deviceId).addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
}
Bundle bundle = new Bundle();
bundle.putInt("cordova", 1);
if (adExtras != null) {
Iterator<String> it = adExtras.keys();
while (it.hasNext()) {
String key = it.next();
try {
bundle.putString(key, adExtras.get(key).toString());
} catch (JSONException exception) {
Log.w (LOGTAG, String.format("Caught JSON Exception: %s", exception.getMessage()));
}
}
}
AdMobExtras adextras = new AdMobExtras (bundle);
request_builder = request_builder.addNetworkExtras (adextras);
AdRequest request = request_builder.build ();
return request;
}
// Parses the request ad input parameters and runs the request ad action on
// the UI thread.
//
// @param inputs The JSONArray representing input parameters. This function expects the first object in the array to be a JSONObject with the input parameters.
// @return A PluginResult representing whether or not an ad was requested succcessfully.
// Listen for onReceiveAd() and onFailedToReceiveAd() callbacks to see if an ad was successfully retrieved.
private PluginResult executeRequestAd (JSONObject options, CallbackContext callbackContext) {
this.setOptions (options);
if (adView == null) {
callbackContext.error ("adView is null, call createBannerView first");
return null;
}
final CallbackContext delayCallback = callbackContext;
cordova.getActivity().runOnUiThread (new Runnable() {
@Override public void run () {
adView.loadAd (buildAdRequest());
delayCallback.success ();
}
});
return null;
}
private PluginResult executeRequestInterstitialAd (JSONObject options, CallbackContext callbackContext) {
this.setOptions (options);
if (adView == null) {
callbackContext.error ("interstitialAd is null: call createInterstitialView first.");
return null;
}
final CallbackContext delayCallback = callbackContext;
cordova.getActivity().runOnUiThread (new Runnable() {
@Override public void run () {
interstitialAd.loadAd (buildAdRequest());
delayCallback.success ();
}
});
return null;
}
// Parses the show ad input parameters and runs the show ad action on the UI thread.
//
// @param inputs The JSONArray representing input parameters. This function
// expects the first object in the array to be a JSONObject with the
// input parameters.
// @return A PluginResult representing whether or not an ad was requested
// succcessfully. Listen for onReceiveAd() and onFailedToReceiveAd()
// callbacks to see if an ad was successfully retrieved.
private PluginResult executeShowAd (final boolean show, final CallbackContext callbackContext) {
bannerShow = show;
if (adView == null) return new PluginResult (Status.ERROR, "adView is null: call createBannerView first.");
cordova.getActivity().runOnUiThread (new Runnable(){
@Override public void run () {
if(bannerVisible == bannerShow) { // No change.
} else if (bannerShow) {
if (adView.getParent() != null) {
((ViewGroup)adView.getParent()).removeView(adView);
}
if (bannerOverlap) {
RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
params2.addRule(bannerAtTop ? RelativeLayout.ALIGN_PARENT_TOP : RelativeLayout.ALIGN_PARENT_BOTTOM);
adViewLayout.addView(adView, params2);
adViewLayout.bringToFront();
} else {
if (CORDOVA_4) {
ViewGroup wvParentView = (ViewGroup) webView.getView().getParent();
if (parentView == null) {
parentView = new LinearLayout(webView.getContext());
}
if (wvParentView != null && wvParentView != parentView) {
wvParentView.removeView(webView.getView());
((LinearLayout) parentView).setOrientation(LinearLayout.VERTICAL);
parentView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 0.0F));
webView.getView().setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 1.0F));
parentView.addView(webView.getView());
cordova.getActivity().setContentView(parentView);
}
} else {
parentView = (ViewGroup) ((ViewGroup) webView).getParent();
}
if (bannerAtTop) {
parentView.addView (adView, 0);
} else {
parentView.addView (adView);
}
parentView.bringToFront ();
parentView.requestLayout();
}
adView.setVisibility (View.VISIBLE);
bannerVisible = true;
} else {
adView.setVisibility (View.GONE);
bannerVisible = false;
}
if (callbackContext != null) callbackContext.success ();
}
});
return null;
}
private PluginResult executeShowInterstitialAd (final boolean show, final CallbackContext callbackContext) {
if (interstitialAd == null) return new PluginResult(Status.ERROR, "interstitialAd is null: call createInterstitialView first.");
cordova.getActivity().runOnUiThread (new Runnable () {
@Override public void run () {
if (interstitialAd.isLoaded()) interstitialAd.show ();
if (callbackContext != null) callbackContext.success ();
}
});
return null;
}
// This class implements the AdMob ad listener events. It forwards the events to the JavaScript layer. To listen for these events, use:
// document.addEventListener ('onReceiveAd' , function());
// document.addEventListener ('onFailedToReceiveAd', function(data){});
// document.addEventListener ('onPresentAd' , function());
// document.addEventListener ('onDismissAd' , function());
// document.addEventListener ('onLeaveToAd' , function());
public class BasicListener extends AdListener {
@Override public void onAdFailedToLoad (int errorCode) {
webView.loadUrl (String.format(
"javascript:cordova.fireDocumentEvent('onFailedToReceiveAd', { 'error': %d, 'reason':'%s' });",
errorCode, getErrorReason(errorCode))
);
}
}
private class BannerListener extends BasicListener {
@Override public void onAdLoaded () {webView.loadUrl ("javascript:cordova.fireDocumentEvent('onReceiveAd');");}
@Override public void onAdOpened () {webView.loadUrl ("javascript:cordova.fireDocumentEvent('onPresentAd');");}
@Override public void onAdClosed () {webView.loadUrl ("javascript:cordova.fireDocumentEvent('onDismissAd');");}
@Override public void onAdLeftApplication () {webView.loadUrl ("javascript:cordova.fireDocumentEvent('onLeaveToAd');");}
}
private class InterstitialListener extends BasicListener {
@Override public void onAdLoaded () {
Log.w ("AdMob", "InterstitialAdLoaded");
webView.loadUrl ("javascript:cordova.fireDocumentEvent('onReceiveInterstitialAd');");
if (autoShowInterstitial) executeShowInterstitialAd (true, null);
}
@Override public void onAdOpened () {
webView.loadUrl ("javascript:cordova.fireDocumentEvent('onPresentInterstitialAd');");
}
@Override public void onAdClosed () {
webView.loadUrl ("javascript:cordova.fireDocumentEvent('onDismissInterstitialAd');");
interstitialAd = null;
}
@Override public void onAdLeftApplication () {
webView.loadUrl ("javascript:cordova.fireDocumentEvent('onLeaveToInterstitialAd');");
interstitialAd = null;
}
}
@Override public void onPause (boolean multitasking) {
if (adView != null) adView.pause ();
super.onPause (multitasking);
}
@Override public void onResume (boolean multitasking) {
super.onResume (multitasking);
isGpsAvailable = (GooglePlayServicesUtil.isGooglePlayServicesAvailable(cordova.getActivity()) == ConnectionResult.SUCCESS);
if (adView != null) adView.resume ();
}
@Override public void onDestroy () {
if (adView != null) {
adView.destroy ();
adView = null;
}
if (adViewLayout != null) {
ViewGroup parentView = (ViewGroup)adViewLayout.getParent();
if(parentView != null) {
parentView.removeView(adViewLayout);
}
adViewLayout = null;
}
super.onDestroy ();
}
/**
* Gets an AdSize object from the string size passed in from JavaScript.
* Returns null if an improper string is provided.
*
* @param size The string size representing an ad format constant.
* @return An AdSize object used to create a banner.
*/
public static AdSize adSizeFromString (String size) {
if ("BANNER".equals(size)) {
return AdSize.BANNER;
} else if ("IAB_MRECT".equals(size)) {
return AdSize.MEDIUM_RECTANGLE;
} else if ("IAB_BANNER".equals(size)) {
return AdSize.FULL_BANNER;
} else if ("IAB_LEADERBOARD".equals(size)) {
return AdSize.LEADERBOARD;
} else if ("SMART_BANNER".equals(size)) {
return AdSize.SMART_BANNER;
} else {
return null;
}
}
/** Gets a string error reason from an error code. */
public String getErrorReason (int errorCode) {
String errorReason = "";
switch(errorCode) {
case AdRequest.ERROR_CODE_INTERNAL_ERROR:
errorReason = "Internal error";
break;
case AdRequest.ERROR_CODE_INVALID_REQUEST:
errorReason = "Invalid request";
break;
case AdRequest.ERROR_CODE_NETWORK_ERROR:
errorReason = "Network Error";
break;
case AdRequest.ERROR_CODE_NO_FILL:
errorReason = "No fill";
break;
}
return errorReason;
}
public static final String md5 (final String s) {
try {
MessageDigest digest = java.security.MessageDigest.getInstance ("MD5");
digest.update (s.getBytes());
byte messageDigest[] = digest.digest ();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++) {
String h = Integer.toHexString(0xFF & messageDigest[i]);
while (h.length() < 2) h = "0" + h;
hexString.append (h);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
}
return "";
}
}
|
agamemnus/cordova-plugin-admob
|
src/android/AdMob.java
|
Java
|
mit
| 20,788 |
package fi.ozzi.tapsudraft.service;
import com.google.common.collect.ImmutableMap;
import fi.ozzi.tapsudraft.model.Player;
import fi.ozzi.tapsudraft.model.Position;
import fi.ozzi.tapsudraft.repository.PlayerRepository;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;
import java.util.Random;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class PlayerFetchService {
private static final Logger LOG = LoggerFactory.getLogger(PlayerFetchService.class);
@Value("${service.playerfetch.baseUrl}")
private String baseUrl;
@NonNull
private PlayerRepository playerRepository;
@Scheduled(cron = "${service.playerfetch.cron}")
public void fetchPlayers() throws IOException {
Map<String, String> params = ImmutableMap.<String, String>builder()
.put("js", "1")
.put("rand", Float.toString(new Random().nextFloat()))
.put("player_team", "all")
.put("player_value", "all")
.put("type", "player_search")
.put("phase", "0")
.build();
String url = buildUrlFromMap(baseUrl, params);
LOG.debug(url);
HttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = httpClient.execute(httpGet);
if (response.getStatusLine().getStatusCode() != 200) {
LOG.debug("HTTP resp " + response.getStatusLine().getStatusCode());
}
Document doc = Jsoup.parse(response.getEntity().getContent(), "UTF-8", url);
Elements positionGroups = doc.getElementsByTag("tbody");
for (Element group : positionGroups) {
Elements rows = group.getElementsByTag("tr");
for (Element row : rows) {
Element nameData = row.select("td.name_data").first();
String name = nameData.text().trim();
String team = nameData.select("a.logo").first().attr("title");
team = team.substring(team.indexOf("(")+1, team.indexOf(")"));
String position = nameData.select("input[name=player_position]").first().val();
String playerUid = nameData.select("input[name=player_id]").first().val();
Player player = playerRepository.findByUid(Long.parseLong(playerUid));
if (player == null) {
playerRepository.save(
Player.builder()
.name(name)
.uid(Long.parseLong(playerUid))
.position(Position.fromCharacter(position))
.build());
}
String price = row.select("td[id~=.*_player_value]").first().text();
String points = row.select("td[title=IS Liigapörssi-pisteet]").first().text();
}
}
}
private static String buildUrlFromMap(String baseUrl, Map<String, String> params) {
String queryString = params.keySet().stream()
.map(key -> {
try {
return key + "=" + URLEncoder.encode(params.get(key), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return "Error: could not URL-encode value";
}).collect(Collectors.joining("&"));
return baseUrl + "?" + queryString;
}
}
|
osmoossi/tapsudraft
|
src/main/java/fi/ozzi/tapsudraft/service/PlayerFetchService.java
|
Java
|
mit
| 3,834 |
/*
* 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 com.github.sunnybat.paxchecker.setup.email;
import com.github.sunnybat.commoncode.email.EmailAddress;
import com.github.sunnybat.commoncode.email.account.EmailAccount;
import com.github.sunnybat.commoncode.preferences.PreferenceHandler;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.DefaultComboBoxModel;
import javax.swing.GroupLayout;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.LayoutStyle;
import javax.swing.WindowConstants;
import javax.swing.table.DefaultTableModel;
/**
*
* @author SunnyBat
*/
public class EmailSetupGUI extends javax.swing.JFrame {
private AuthenticationCallback myCallback = new AuthenticationCallback();
private AuthGmail authGmail = new AuthGmail(myCallback);
private AuthSMTP authSmtp = new AuthSMTP(myCallback);
private PreferenceHandler prefs;
private EmailAccount finalizedEmailAccount;
private boolean disableEmail = false;
private List<EmailAddress> savedEmailAddresses;
private boolean savedIsGmail;
/**
* Creates new form EmailUIWrapper
*
* @param prefs The Preferences to save email configuration settings to and load from
*/
public EmailSetupGUI(PreferenceHandler prefs) {
this.prefs = prefs;
initComponents();
customComponents();
}
private void customComponents() {
String smtpAddress = prefs.getStringPreference("EMAIL");
String emailString = prefs.getStringPreference("CELLNUM");
String emailType = prefs.getStringPreference("EMAILTYPE");
// TODO: we need to initialize everything here, including Send To
// addresses and the EmailAccount we're using
if (emailType != null && emailType.equalsIgnoreCase("SMTP")) {
JRBSMTP.setSelected(true);
setAuthPanel(authSmtp);
savedIsGmail = false;
if (smtpAddress != null) {
authSmtp.setEmailAddress(smtpAddress);
} else {
System.out.println("smtpIsNull");
}
authSmtp.recordCurrentFields();
} else {
JRBGmail.setSelected(true);
setAuthPanel(authGmail);
savedIsGmail = true;
if (emailType != null) { // Assumed to be Gmail
authGmail.authenticate();
}
authGmail.recordCurrentFields();
}
if (emailString != null) {
List<EmailAddress> addresses = EmailAddress.convertToList(emailString);
for (EmailAddress address : addresses) {
DefaultTableModel table = (DefaultTableModel) JTCellNumbers.getModel();
table.addRow(new Object[]{address.getCarrierName().equalsIgnoreCase("[Other]") ? address.getCompleteAddress() : address.getAddressBeginning(), address.getCarrierName()});
}
}
savedEmailAddresses = getCurrentEmails();
savedIsGmail = JRBGmail.isSelected();
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
int result = JOptionPane.showConfirmDialog(null,
"Would you like to save your changes?\r\nYes: Save Changes\r\nNo: Disable Email\r\nCancel: Discard changes\r\n[X] Button: Keep window open",
"Save Changes",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);
if (result == JOptionPane.YES_OPTION) {
saveChanges();
} else if (result == JOptionPane.NO_OPTION) {
disableEmail();
} else if (result == JOptionPane.CANCEL_OPTION) {
cancelChanges();
}
}
});
}
/**
* Gets the currently configured EmailAccount. This includes the email addresses currently
* configured to be sent to. The EmailAccount must be successfully authenticated, otherwise null
* will be returned.
*
* @return The EmailAccount configured, or null if not set up
*/
public EmailAccount getEmailAccount() {
if (disableEmail) {
return null;
}
EmailAccount account;
if (JRBGmail.isSelected() && authGmail.isAuthenticated()) {
account = authGmail.getEmailAccount();
} else if (JRBSMTP.isSelected() && authSmtp.isAuthenticated()) {
account = authSmtp.getEmailAccount();
} else {
return null;
}
// === Add emails to account ===
account.clearAllSendAddresses(); // TODO Check to make sure this is the right thing to do, or if there's a better way
DefaultTableModel tableModel = (DefaultTableModel) JTCellNumbers.getModel();
if (tableModel.getRowCount() == 0) {
return null;
} else {
for (int i = 0; i < tableModel.getRowCount(); i++) {
EmailAddress toAdd;
String emailBeginning = (String) tableModel.getValueAt(i, 0);
String emailCarrier = (String) tableModel.getValueAt(i, 1);
if (emailCarrier.equalsIgnoreCase("[Other]")) {
toAdd = new EmailAddress(emailBeginning);
} else {
toAdd = new EmailAddress(emailBeginning + EmailAddress.getCarrierExtension(emailCarrier));
}
account.addBccEmailAddress(toAdd);
}
}
finalizedEmailAccount = account;
return finalizedEmailAccount;
}
public String getEmailType() {
if (JRBGmail.isSelected() && authGmail.isAuthenticated()) {
return "Gmail API";
} else if (JRBSMTP.isSelected() && authSmtp.isAuthenticated()) {
return "SMTP";
} else {
return "Disabled";
}
}
/**
* Gets the semicolon-delimited String representing all of the email addresses configured.
*
* @return All the configured email addresses
*/
public String getEmailAddressesString() {
List<EmailAddress> addresses = getCurrentEmails();
StringBuilder allAddresses = new StringBuilder();
for (int i = 0; i < addresses.size(); i++) {
if (i > 0) {
allAddresses.append(";");
}
allAddresses.append(addresses.get(i).getCompleteAddress());
}
return allAddresses.toString();
}
private List<EmailAddress> getCurrentEmails() {
List<EmailAddress> ret = new ArrayList<>();
DefaultTableModel tableModel = (DefaultTableModel) JTCellNumbers.getModel();
for (int i = 0; i < tableModel.getRowCount(); i++) {
try {
EmailAddress toAdd;
String emailBeginning = (String) tableModel.getValueAt(i, 0);
String emailCarrier = (String) tableModel.getValueAt(i, 1);
if (emailCarrier.equalsIgnoreCase("[Other]")) {
toAdd = new EmailAddress(emailBeginning);
} else {
toAdd = new EmailAddress(emailBeginning + EmailAddress.getCarrierExtension(emailCarrier));
}
ret.add(toAdd);
} catch (IllegalArgumentException iae) {
System.out.println("Invalid email address: " + tableModel.getValueAt(i, 0) + tableModel.getValueAt(i, 1));
}
}
return ret;
}
private void addEmail() {
String cellNumber = JTFCellNumber.getText();
String carrier = JCBCarrier.getSelectedItem().toString();
if (!cellNumber.isEmpty()) {
if (cellNumber.contains("@")) { // Full email configured
carrier = "[Other]";
}
((DefaultTableModel) JTCellNumbers.getModel()).addRow(new Object[]{cellNumber, carrier});
JTFCellNumber.setText(null);
JCBCarrier.setSelectedIndex(0);
JTFCellNumber.requestFocus();
}
}
private void resetChanges() {
DefaultTableModel model = (DefaultTableModel) JTCellNumbers.getModel();
for (int i = model.getRowCount() - 1; i >= 0; i--) {
model.removeRow(i);
}
if (savedEmailAddresses != null) {
for (EmailAddress address : savedEmailAddresses) {
model.addRow(new Object[]{address.getAddressBeginning(), EmailAddress.getProvider(address.getAddressEnding())});
}
}
if (savedIsGmail) {
JRBGmail.setSelected(true);
setAuthPanel(authGmail);
} else {
JRBSMTP.setSelected(true);
setAuthPanel(authSmtp);
}
}
private void setAuthPanel(JPanel toUse) {
JPAuthInfo.removeAll();
JPAuthInfo.add(toUse);
JPAuthInfo.revalidate();
JPAuthInfo.repaint();
pack();
}
private void resetUserInputFields() {
JTPComponents.setSelectedIndex(0);
JTFCellNumber.setText(null);
JCBCarrier.setSelectedIndex(0);
}
private void updatePreferences() {
EmailAccount toSave = getEmailAccount();
if (!disableEmail && toSave != null) {
prefs.getPreferenceObject("EMAIL").setValue(toSave.getEmailAddress());
prefs.getPreferenceObject("CELLNUM").setValue(getEmailAddressesString());
prefs.getPreferenceObject("EMAILTYPE").setValue(getEmailType());
prefs.getPreferenceObject("EMAILENABLED").setValue(true);
} else {
prefs.getPreferenceObject("EMAIL").setValue(null);
prefs.getPreferenceObject("CELLNUM").setValue(null);
prefs.getPreferenceObject("EMAILTYPE").setValue(null);
prefs.getPreferenceObject("EMAILENABLED").setValue(false);
}
}
private void saveChanges() {
if (getCurrentEmails().isEmpty()) {
int result = JOptionPane.showConfirmDialog(null, "You have no Send To emails configured. This means emails will still be disabled.\r\nAre you sure you want to save your changes?\r\nPress Yes to save your changes, or No to add email addresses.",
"No Emails Input",
JOptionPane.YES_NO_OPTION,
JOptionPane.QUESTION_MESSAGE);
if (result == JOptionPane.NO_OPTION) {
JTPComponents.setSelectedComponent(JPSendTo);
return;
}
}
authGmail.recordCurrentFields();
authSmtp.recordCurrentFields();
savedEmailAddresses = getCurrentEmails();
savedIsGmail = JRBGmail.isSelected();
disableEmail = false;
setVisible(false);
resetUserInputFields();
updatePreferences();
}
private void cancelChanges() {
authGmail.resetChanges();
authSmtp.resetChanges();
resetChanges();
setVisible(false);
resetUserInputFields();
updatePreferences();
}
private void disableEmail() {
disableEmail = true;
authGmail.resetChanges();
authSmtp.resetChanges();
resetChanges();
setVisible(false);
resetUserInputFields();
updatePreferences();
}
/**
* This method is called from within the constructor to initialize the form. WARNING: Do NOT
* modify this code. The content of this method is always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
BGAuthType = new ButtonGroup();
JTPComponents = new JTabbedPane();
JPAuthentication = new JPanel();
JRBGmail = new JRadioButton();
JRBSMTP = new JRadioButton();
JPAuthInfo = new JPanel();
JPSendTo = new JPanel();
JTFCellNumber = new JTextField();
JBAddNumber = new JButton();
JCBCarrier = new JComboBox<>();
jLabel1 = new JLabel();
jScrollPane1 = new JScrollPane();
JTCellNumbers = new JTable();
JPFinish = new JPanel();
JBSaveChanges = new JButton();
JBCancelChanges = new JButton();
JBDisableEmail = new JButton();
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
setTitle("Email Setup");
setResizable(false);
BGAuthType.add(JRBGmail);
JRBGmail.setText("Gmail API");
JRBGmail.setToolTipText("<html>\n<i>English</i>\n<p width=\"500\">Authenticates with Google through your browser. Recommended.</p>\n<i>Tech</i>\n<p width=\"500\">Used for authenticating with Google via OAuth2.<br></p>\n</html>");
JRBGmail.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JRBGmailActionPerformed(evt);
}
});
BGAuthType.add(JRBSMTP);
JRBSMTP.setText("SMTP");
JRBSMTP.setToolTipText("<html>\n<i>English</i>\n<p width=\"500\">Authenticates with any email service. Not recommended.</p>\n<i>Tech</i>\n<p width=\"500\">Authenticates with any mailserver using SMTP. Issues with this have cropped up in the past, and it's hard to detect where the problem lies. My guess is ISPs or routers blocking SMTP traffic (insane), but I don't know for sure.</p>\n</html>");
JRBSMTP.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JRBSMTPActionPerformed(evt);
}
});
JPAuthInfo.setLayout(new BoxLayout(JPAuthInfo, BoxLayout.LINE_AXIS));
GroupLayout JPAuthenticationLayout = new GroupLayout(JPAuthentication);
JPAuthentication.setLayout(JPAuthenticationLayout);
JPAuthenticationLayout.setHorizontalGroup(JPAuthenticationLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(JPAuthenticationLayout.createSequentialGroup()
.addContainerGap()
.addComponent(JRBGmail)
.addGap(18, 18, 18)
.addComponent(JRBSMTP)
.addContainerGap(249, Short.MAX_VALUE))
.addComponent(JPAuthInfo, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
JPAuthenticationLayout.setVerticalGroup(JPAuthenticationLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(JPAuthenticationLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JPAuthenticationLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(JRBGmail)
.addComponent(JRBSMTP))
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(JPAuthInfo, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
JTPComponents.addTab("Authentication", JPAuthentication);
JTFCellNumber.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
JTFCellNumberKeyPressed(evt);
}
});
JBAddNumber.setText("Add Number");
JBAddNumber.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JBAddNumberActionPerformed(evt);
}
});
JBAddNumber.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
JBAddNumberKeyPressed(evt);
}
});
JCBCarrier.setModel(new DefaultComboBoxModel<>(new String[] { "AT&T (MMS)", "AT&T (SMS)", "Verizon", "Sprint", "T-Mobile", "U.S. Cellular", "Bell", "Rogers", "Fido", "Koodo", "Telus", "Virgin (CAN)", "Wind", "Sasktel", "[Other]" }));
JCBCarrier.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
JCBCarrierKeyPressed(evt);
}
});
jLabel1.setText("Cell Number");
JTCellNumbers.setModel(new DefaultTableModel(
new Object [][] {
},
new String [] {
"Cell Number", "Carrier"
}
) {
Class[] types = new Class [] {
String.class, String.class
};
boolean[] canEdit = new boolean [] {
false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
JTCellNumbers.setToolTipText("Delete emails by selecting them and pressing the DEL key");
JTCellNumbers.setColumnSelectionAllowed(true);
JTCellNumbers.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent evt) {
JTCellNumbersKeyPressed(evt);
}
});
jScrollPane1.setViewportView(JTCellNumbers);
GroupLayout JPSendToLayout = new GroupLayout(JPSendTo);
JPSendTo.setLayout(JPSendToLayout);
JPSendToLayout.setHorizontalGroup(JPSendToLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(JPSendToLayout.createSequentialGroup()
.addComponent(jLabel1)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(JTFCellNumber, GroupLayout.DEFAULT_SIZE, 147, Short.MAX_VALUE)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(JCBCarrier, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(JBAddNumber))
.addComponent(jScrollPane1, GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
);
JPSendToLayout.setVerticalGroup(JPSendToLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(GroupLayout.Alignment.TRAILING, JPSendToLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JPSendToLayout.createParallelGroup(GroupLayout.Alignment.BASELINE)
.addComponent(JTFCellNumber, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(JBAddNumber)
.addComponent(JCBCarrier, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, GroupLayout.DEFAULT_SIZE, 132, Short.MAX_VALUE))
);
JTPComponents.addTab("Send To", JPSendTo);
JBSaveChanges.setText("Save Changes");
JBSaveChanges.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JBSaveChangesActionPerformed(evt);
}
});
JBCancelChanges.setText("Cancel Changes");
JBCancelChanges.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JBCancelChangesActionPerformed(evt);
}
});
JBDisableEmail.setText("Disable Email");
JBDisableEmail.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JBDisableEmailActionPerformed(evt);
}
});
GroupLayout JPFinishLayout = new GroupLayout(JPFinish);
JPFinish.setLayout(JPFinishLayout);
JPFinishLayout.setHorizontalGroup(JPFinishLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(JPFinishLayout.createSequentialGroup()
.addContainerGap()
.addGroup(JPFinishLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(JBSaveChanges, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(JBCancelChanges, GroupLayout.DEFAULT_SIZE, 375, Short.MAX_VALUE)
.addComponent(JBDisableEmail, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addContainerGap())
);
JPFinishLayout.setVerticalGroup(JPFinishLayout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addGroup(GroupLayout.Alignment.TRAILING, JPFinishLayout.createSequentialGroup()
.addContainerGap()
.addComponent(JBSaveChanges)
.addGap(18, 18, 18)
.addComponent(JBCancelChanges)
.addGap(18, 18, 18)
.addComponent(JBDisableEmail)
.addContainerGap(56, Short.MAX_VALUE))
);
JTPComponents.addTab("Finish", JPFinish);
GroupLayout layout = new GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(JTPComponents)
);
layout.setVerticalGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
.addComponent(JTPComponents)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void JRBGmailActionPerformed(ActionEvent evt) {//GEN-FIRST:event_JRBGmailActionPerformed
setAuthPanel(authGmail);
}//GEN-LAST:event_JRBGmailActionPerformed
private void JRBSMTPActionPerformed(ActionEvent evt) {//GEN-FIRST:event_JRBSMTPActionPerformed
setAuthPanel(authSmtp);
}//GEN-LAST:event_JRBSMTPActionPerformed
private void JBAddNumberActionPerformed(ActionEvent evt) {//GEN-FIRST:event_JBAddNumberActionPerformed
addEmail();
}//GEN-LAST:event_JBAddNumberActionPerformed
private void JTCellNumbersKeyPressed(KeyEvent evt) {//GEN-FIRST:event_JTCellNumbersKeyPressed
if (evt.getKeyCode() == KeyEvent.VK_DELETE) {
int[] selectedIndeces = JTCellNumbers.getSelectedRows();
for (int i = selectedIndeces.length - 1; i >= 0; i--) { // Iterate from the bottom up
((DefaultTableModel) JTCellNumbers.getModel()).removeRow(selectedIndeces[i]);
}
} else if (evt.getKeyCode() == KeyEvent.VK_TAB) {
this.transferFocus();
evt.consume();
}
}//GEN-LAST:event_JTCellNumbersKeyPressed
private void JTFCellNumberKeyPressed(KeyEvent evt) {//GEN-FIRST:event_JTFCellNumberKeyPressed
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
addEmail();
}
}//GEN-LAST:event_JTFCellNumberKeyPressed
private void JCBCarrierKeyPressed(KeyEvent evt) {//GEN-FIRST:event_JCBCarrierKeyPressed
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
addEmail();
}
}//GEN-LAST:event_JCBCarrierKeyPressed
private void JBAddNumberKeyPressed(KeyEvent evt) {//GEN-FIRST:event_JBAddNumberKeyPressed
if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
addEmail();
}
}//GEN-LAST:event_JBAddNumberKeyPressed
private void JBSaveChangesActionPerformed(ActionEvent evt) {//GEN-FIRST:event_JBSaveChangesActionPerformed
saveChanges();
}//GEN-LAST:event_JBSaveChangesActionPerformed
private void JBCancelChangesActionPerformed(ActionEvent evt) {//GEN-FIRST:event_JBCancelChangesActionPerformed
cancelChanges();
}//GEN-LAST:event_JBCancelChangesActionPerformed
private void JBDisableEmailActionPerformed(ActionEvent evt) {//GEN-FIRST:event_JBDisableEmailActionPerformed
disableEmail();
}//GEN-LAST:event_JBDisableEmailActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private ButtonGroup BGAuthType;
private JButton JBAddNumber;
private JButton JBCancelChanges;
private JButton JBDisableEmail;
private JButton JBSaveChanges;
private JComboBox<String> JCBCarrier;
private JPanel JPAuthInfo;
private JPanel JPAuthentication;
private JPanel JPFinish;
private JPanel JPSendTo;
private JRadioButton JRBGmail;
private JRadioButton JRBSMTP;
private JTable JTCellNumbers;
private JTextField JTFCellNumber;
private JTabbedPane JTPComponents;
private JLabel jLabel1;
private JScrollPane jScrollPane1;
// End of variables declaration//GEN-END:variables
private class AuthenticationCallback implements Runnable {
private boolean nextEnabledState = false;
public void run() {
JBSaveChanges.setEnabled(nextEnabledState);
JBCancelChanges.setEnabled(nextEnabledState);
JBDisableEmail.setEnabled(nextEnabledState);
JRBGmail.setEnabled(nextEnabledState);
JRBSMTP.setEnabled(nextEnabledState);
nextEnabledState = !nextEnabledState; // Invert
}
}
}
|
SunnyBat/PAXChecker
|
src/main/java/com/github/sunnybat/paxchecker/setup/email/EmailSetupGUI.java
|
Java
|
mit
| 22,577 |
/* Generated By:JavaCC: Do not edit this line. ParseException.java Version 3.0 */
package org.cfeclipse.cfml.parser.cfscript;
/**
* This exception is thrown when parse errors are encountered.
* You can explicitly create objects of this exception type by
* calling the method generateParseException in the generated
* parser.
*
* You can modify this class to customize your error reporting
* mechanisms so long as you retain the public fields.
*/
public class ParseException extends Exception {
/**
* This constructor is used by the method "generateParseException"
* in the generated parser. Calling this constructor generates
* a new object of this type with the fields "currentToken",
* "expectedTokenSequences", and "tokenImage" set. The boolean
* flag "specialConstructor" is also set to true to indicate that
* this constructor was used to create this object.
* This constructor calls its super class with the empty string
* to force the "toString" method of parent class "Throwable" to
* print the error message in the form:
* ParseException: <result of getMessage>
*/
public ParseException(Token currentTokenVal,
int[][] expectedTokenSequencesVal,
String[] tokenImageVal
)
{
super("");
specialConstructor = true;
currentToken = currentTokenVal;
expectedTokenSequences = expectedTokenSequencesVal;
tokenImage = tokenImageVal;
}
/**
* The following constructors are for use by you for whatever
* purpose you can think of. Constructing the exception in this
* manner makes the exception behave in the normal way - i.e., as
* documented in the class "Throwable". The fields "errorToken",
* "expectedTokenSequences", and "tokenImage" do not contain
* relevant information. The JavaCC generated code does not use
* these constructors.
*/
public ParseException() {
super();
specialConstructor = false;
}
public ParseException(String message) {
super(message);
specialConstructor = false;
}
/**
* This variable determines which constructor was used to create
* this object and thereby affects the semantics of the
* "getMessage" method (see below).
*/
protected boolean specialConstructor;
/**
* This is the last token that has been consumed successfully. If
* this object has been created due to a parse error, the token
* followng this token will (therefore) be the first error token.
*/
public Token currentToken;
/**
* Each entry in this array is an array of integers. Each array
* of integers represents a sequence of tokens (by their ordinal
* values) that is expected at this point of the parse.
*/
public int[][] expectedTokenSequences;
/**
* This is a reference to the "tokenImage" array of the generated
* parser within which the parse error occurred. This array is
* defined in the generated ...Constants interface.
*/
public String[] tokenImage;
/**
* This method has the standard behavior when this object has been
* created using the standard constructors. Otherwise, it uses
* "currentToken" and "expectedTokenSequences" to generate a parse
* error message and returns it. If this object has been created
* due to a parse error, and you do not catch it (it gets thrown
* from the parser), then this method is called during the printing
* of the final stack trace, and hence the correct error message
* gets displayed.
*/
public String getMessage() {
if (!specialConstructor) {
return super.getMessage();
}
String expected = "";
int maxSize = 0;
for (int i = 0; i < expectedTokenSequences.length; i++) {
if (maxSize < expectedTokenSequences[i].length) {
maxSize = expectedTokenSequences[i].length;
}
for (int j = 0; j < expectedTokenSequences[i].length; j++) {
expected += tokenImage[expectedTokenSequences[i][j]] + " ";
}
if (expectedTokenSequences[i][expectedTokenSequences[i].length - 1] != 0) {
expected += "...";
}
expected += eol + " ";
}
String retval = "Encountered \"";
Token tok = currentToken.next;
for (int i = 0; i < maxSize; i++) {
if (i != 0) retval += " ";
if (tok.kind == 0) {
retval += tokenImage[0];
break;
}
retval += add_escapes(tok.image);
tok = tok.next;
}
retval += "\" at line " + currentToken.next.beginLine + ", column " + currentToken.next.beginColumn;
retval += "." + eol;
if (expectedTokenSequences.length == 1) {
retval += "Was expecting:" + eol + " ";
} else {
retval += "Was expecting one of:" + eol + " ";
}
retval += expected;
return retval;
}
/**
* The end of line string for this machine.
*/
protected String eol = System.getProperty("line.separator", "\n");
/**
* Used to convert raw characters to their escaped version
* when these raw version cannot be used as part of an ASCII
* string literal.
*/
protected String add_escapes(String str) {
StringBuffer retval = new StringBuffer();
char ch;
for (int i = 0; i < str.length(); i++) {
switch (str.charAt(i))
{
case 0 :
continue;
case '\b':
retval.append("\\b");
continue;
case '\t':
retval.append("\\t");
continue;
case '\n':
retval.append("\\n");
continue;
case '\f':
retval.append("\\f");
continue;
case '\r':
retval.append("\\r");
continue;
case '\"':
retval.append("\\\"");
continue;
case '\'':
retval.append("\\\'");
continue;
case '\\':
retval.append("\\\\");
continue;
default:
if ((ch = str.charAt(i)) < 0x20 || ch > 0x7e) {
String s = "0000" + Integer.toString(ch, 16);
retval.append("\\u" + s.substring(s.length() - 4, s.length()));
} else {
retval.append(ch);
}
continue;
}
}
return retval.toString();
}
}
|
cybersonic/org.cfeclipse.cfml
|
src/org/cfeclipse/cfml/parser/cfscript/ParseException.java
|
Java
|
mit
| 6,569 |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2013.12.23 at 08:29:00 AM CST
//
package ca.ieso.reports.schema.iomspublicplannedoutageday;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for ConfidentialityClass.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="ConfidentialityClass">
* <restriction base="{http://www.w3.org/2001/XMLSchema}string">
* <enumeration value="PUB"/>
* <enumeration value="CNF"/>
* <enumeration value="HCNF"/>
* <enumeration value="INT"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "ConfidentialityClass")
@XmlEnum
public enum ConfidentialityClass {
PUB,
CNF,
HCNF,
INT;
public String value() {
return name();
}
public static ConfidentialityClass fromValue(String v) {
return valueOf(v);
}
}
|
r24mille/IesoPublicReportBindings
|
src/main/java/ca/ieso/reports/schema/iomspublicplannedoutageday/ConfidentialityClass.java
|
Java
|
mit
| 1,298 |
package sprites;
public class Enemy extends Paddle
{
public Enemy(int x, int y)
{
super(x,y);
}
int updateFrameCounter = 0;
float moveDirection = 0;
public void update(float dt, Ball ball)
{
//if(++updateFrameCounter%3==0)
//{
updateFrameCounter = 0;
if(position.y < ball.position.y)
moveDirection = 1;
else if (position.y > ball.position.y)
moveDirection = -1;
else
moveDirection = 0;
//}
setVVelocity(moveDirection, dt);
position.add(velocity.x, velocity.y);
bounds.setPosition(position.x, position.y);
}
}
|
lightofanima/GameDevelopmentTutorial
|
Pong/core/src/sprites/Enemy.java
|
Java
|
mit
| 564 |
/*******************************************************************************
* Manchester Centre for Integrative Systems Biology
* University of Manchester
* Manchester M1 7ND
* United Kingdom
*
* Copyright (C) 2008 University of Manchester
*
* This program is released under the Academic Free License ("AFL") v3.0.
* (http://www.opensource.org/licenses/academic.php)
*******************************************************************************/
package org.mcisb.subliminal.metacyc;
import java.io.*;
import java.util.*;
import org.mcisb.subliminal.*;
import org.mcisb.subliminal.model.*;
import org.mcisb.subliminal.sbml.*;
import org.sbml.jsbml.*;
/**
* @author Neil Swainston
*/
public class MetaCycExtracter extends Extracter
{
/**
*
*/
private final static String COMPARTMENT_SUFFIX = "_CCO_"; //$NON-NLS-1$
/**
*
*/
private final static String MXN_REF_PREFIX = "metacyc:"; //$NON-NLS-1$
/**
*
* @param taxonomyId
* @param outFile
* @param metaCycDirectory
* @throws Exception
*/
public static void run( final String taxonomyId, final File outFile, final File metaCycDirectory ) throws Exception
{
final String taxonomyName = SubliminalUtils.getTaxonomyName( taxonomyId );
if( taxonomyName == null )
{
throw new UnsupportedOperationException( "MetaCyc data unavailable for NCBI Taxonomy id " + taxonomyId ); //$NON-NLS-1$
}
final SBMLDocument document = initDocument( taxonomyId );
run( taxonomyId, taxonomyName, document, metaCycDirectory, false );
XmlFormatter.getInstance().write( document, outFile );
SbmlFactory.getInstance().unregister();
}
/**
*
* @param taxonomyId
* @param outFile
* @throws Exception
*/
public static void run( final String taxonomyId, final File outFile ) throws Exception
{
final SBMLDocument document = initDocument( taxonomyId );
run( taxonomyId, document );
XmlFormatter.getInstance().write( document, outFile );
SbmlFactory.getInstance().unregister();
}
/**
*
* @param taxonomyId
* @param document
* @throws Exception
*/
public static void run( final String taxonomyId, final SBMLDocument document ) throws Exception
{
final String taxonomyName = SubliminalUtils.getTaxonomyName( taxonomyId );
if( taxonomyName == null )
{
throw new UnsupportedOperationException( "MetaCyc data unavailable for NCBI Taxonomy id " + taxonomyId ); //$NON-NLS-1$
}
final File tempDirectory = new File( System.getProperty( "java.io.tmpdir" ) ); //$NON-NLS-1$
run( taxonomyId, taxonomyName, document, new File( tempDirectory, taxonomyName ), true );
}
/**
*
* @param taxonomyId
* @param document
* @param metaCycDirectory
* @throws Exception
*/
private static void run( final String taxonomyId, final String taxonomyName, final SBMLDocument document, final File metaCycDirectory, final boolean deleteSource ) throws Exception
{
try
{
final File metaCycSource = MetaCycDownloader.getMetaCycSource( metaCycDirectory, taxonomyName );
final File sbml = SubliminalUtils.find( metaCycSource, "metabolic-reactions.sbml" ); //$NON-NLS-1$
if( sbml != null )
{
System.out.println( "MetaCyc: " + taxonomyName ); //$NON-NLS-1$
final MetaCycFactory metaCycFactory = initFactory( metaCycSource );
final SBMLDocument inDocument = new SBMLReader().readSBML( sbml );
final Model inModel = inDocument.getModel();
for( int l = 0; l < inModel.getNumReactions(); l++ )
{
final Reaction inReaction = inModel.getReaction( l );
final Reaction outReaction = addReaction( document.getModel(), inReaction, taxonomyId, metaCycFactory );
if( inReaction.isSetReversible() )
{
outReaction.setReversible( inReaction.getReversible() );
}
}
final Collection<Object[]> resources = new ArrayList<>();
resources.add( new Object[] { "http://identifiers.org/biocyc/" + metaCycFactory.getOrganismId(), CVTerm.Qualifier.BQB_IS_DESCRIBED_BY } ); //$NON-NLS-1$
resources.add( new Object[] { "http://identifiers.org/pubmed/10592180", CVTerm.Qualifier.BQB_IS_DESCRIBED_BY } ); //$NON-NLS-1$
addResources( inModel, resources );
}
if( deleteSource )
{
SubliminalUtils.delete( metaCycSource );
}
}
catch( FileNotFoundException e )
{
e.printStackTrace();
}
}
/**
*
* @param source
* @return MetaCycReactionsParser
*/
private static MetaCycFactory initFactory( final File source )
{
final File versionFile = SubliminalUtils.find( source, "version.dat" ); //$NON-NLS-1$
final File reactionsFile = SubliminalUtils.find( source, "reactions.dat" ); //$NON-NLS-1$
final File enzymesFile = SubliminalUtils.find( source, "enzymes.col" ); //$NON-NLS-1$
return new MetaCycFactory( versionFile, reactionsFile, enzymesFile );
}
/**
*
* @param outModel
* @param inReaction
* @param taxonomyId
* @param metaCycEnzymeFactory
* @param resources
* @return Reaction
* @throws Exception
*/
private static Reaction addReaction( final Model outModel, final Reaction inReaction, final String taxonomyId, final MetaCycFactory metaCycEnzymeFactory ) throws Exception
{
final String inReactionId = inReaction.getId();
Reaction outReaction = addReaction( outModel, getId( inReactionId ), DEFAULT_COMPARTMENT_ID );
if( outReaction == null )
{
outReaction = outModel.createReaction();
outReaction.setId( inReactionId );
outReaction.setName( inReaction.getName() );
for( int l = 0; l < inReaction.getNumReactants(); l++ )
{
final SpeciesReference inReactant = inReaction.getReactant( l );
final SpeciesReference outReactant = outReaction.createReactant();
final String speciesId = inReactant.getSpecies();
final Species outSpecies = addSpecies( outModel, getId( speciesId ), inReaction.getModel().getSpecies( speciesId ).getName(), DEFAULT_COMPARTMENT_ID, SubliminalUtils.SBO_SIMPLE_CHEMICAL );
outReactant.setSpecies( outSpecies.getId() );
outReactant.setStoichiometry( inReactant.getStoichiometry() );
}
for( int l = 0; l < inReaction.getNumProducts(); l++ )
{
final SpeciesReference inProduct = inReaction.getProduct( l );
final SpeciesReference outProduct = outReaction.createProduct();
final String speciesId = inProduct.getSpecies();
final Species outSpecies = addSpecies( outModel, getId( speciesId ), inReaction.getModel().getSpecies( speciesId ).getName(), DEFAULT_COMPARTMENT_ID, SubliminalUtils.SBO_SIMPLE_CHEMICAL );
outProduct.setSpecies( outSpecies.getId() );
outProduct.setStoichiometry( inProduct.getStoichiometry() );
}
}
final Map<String,Integer> enzymes = metaCycEnzymeFactory.getEnzymes( inReactionId );
final String[] enzymeIds = enzymes.keySet().toArray( new String[ enzymes.keySet().size() ] );
for( String enzymeId : enzymeIds )
{
final String formattedEnzymeId = "MetaCyc:" + MetaCycUtils.unencode( enzymeId ); //$NON-NLS-1$
final List<String[]> results = SubliminalUtils.searchUniProt( SubliminalUtils.encodeUniProtSearchTerm( formattedEnzymeId ) + "+AND+taxonomy:" + taxonomyId );//$NON-NLS-1$
addEnzymes( outReaction, results, SubliminalUtils.getNormalisedId( formattedEnzymeId ), enzymeId, new ArrayList<Object[]>() );
}
return outReaction;
}
/**
*
* @param id
* @return String
*/
private static String getId( final String id )
{
String formattedId = id;
if( formattedId.contains( COMPARTMENT_SUFFIX ) )
{
formattedId = formattedId.substring( 0, id.indexOf( COMPARTMENT_SUFFIX ) );
}
return MXN_REF_PREFIX + MetaCycUtils.unencode( formattedId );
}
/**
* @param args
* @throws Exception
*/
public static void main( String[] args ) throws Exception
{
if( args.length == 2 )
{
MetaCycExtracter.run( args[ 0 ], new File( args[ 1 ] ) );
}
else if( args.length == 3 )
{
MetaCycExtracter.run( args[ 0 ], new File( args[ 1 ] ), new File( args[ 2 ] ) );
}
}
}
|
mcisb/SuBliMinaLToolbox
|
src/main/java/org/mcisb/subliminal/metacyc/MetaCycExtracter.java
|
Java
|
mit
| 7,913 |
package com.stuffwithstuff.magpie.interpreter.builtin;
import com.stuffwithstuff.magpie.interpreter.Interpreter;
import com.stuffwithstuff.magpie.interpreter.Obj;
public interface BuiltInCallable {
Obj invoke(Interpreter interpreter, Obj thisObj, Obj arg);
}
|
munificent/magpie-optionally-typed
|
src/com/stuffwithstuff/magpie/interpreter/builtin/BuiltInCallable.java
|
Java
|
mit
| 263 |
package lol4j.protocol.dto.champion;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
/**
* Created by Aaron Corley on 12/10/13.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
public class ChampionDto {
private boolean active;
private boolean botEnabled;
private boolean botMmEnabled;
private boolean freeToPlay;
private long id;
private boolean rankedPlayEnabled;
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public boolean isBotEnabled() {
return botEnabled;
}
public void setBotEnabled(boolean botEnabled) {
this.botEnabled = botEnabled;
}
public boolean isBotMmEnabled() {
return botMmEnabled;
}
public void setBotMmEnabled(boolean botMmEnabled) {
this.botMmEnabled = botMmEnabled;
}
public boolean isFreeToPlay() {
return freeToPlay;
}
public void setFreeToPlay(boolean freeToPlay) {
this.freeToPlay = freeToPlay;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public boolean isRankedPlayEnabled() {
return rankedPlayEnabled;
}
public void setRankedPlayEnabled(boolean rankedPlayEnabled) {
this.rankedPlayEnabled = rankedPlayEnabled;
}
}
|
aaryn101/lol4j
|
src/main/java/lol4j/protocol/dto/champion/ChampionDto.java
|
Java
|
mit
| 1,387 |
package pl.garciapl.banknow.service;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;
import pl.garciapl.banknow.model.Transaction;
import pl.garciapl.banknow.service.exceptions.GenericBankNowException;
import pl.garciapl.banknow.service.exceptions.InsufficientFundsException;
/**
* TransactionService - interface for TransactionServiceImpl
*
* @author lukasz
*/
public interface TransactionService {
List<Transaction> getAllTransactions();
void makeDeposit(BigInteger account, BigDecimal amount);
void makeTransfer(BigInteger sender, BigInteger recipient, BigDecimal amount)
throws InsufficientFundsException, GenericBankNowException;
}
|
GarciaPL/BankNow
|
src/main/java/pl/garciapl/banknow/service/TransactionService.java
|
Java
|
mit
| 703 |
package eg.utils;
import java.io.File;
import java.awt.Toolkit;
/**
* Static system properties
*/
public class SystemParams {
/**
* True if the OS is Windows, false otherwise */
public static final boolean IS_WINDOWS;
/**
* The Java version */
public static final String JAVA_VERSION;
/**
* True if the Java version is higher than 8, false otherwise */
public static final boolean IS_JAVA_9_OR_HIGHER;
/**
* True if the Java version is 13 or higher, false otherwise */
public static final boolean IS_JAVA_13_OR_HIGHER;
/**
* The modifier mask for menu shortcuts */
public static final int MODIFIER_MASK;
/**
* The path to the '.eadgyth' directory in the user home
* directory */
public static final String EADGYTH_DATA_DIR;
static {
String os = System.getProperty("os.name").toLowerCase();
IS_WINDOWS = os.contains("win");
String userHome = System.getProperty("user.home");
EADGYTH_DATA_DIR = userHome + File.separator + ".eadgyth";
JAVA_VERSION = System.getProperty("java.version");
IS_JAVA_9_OR_HIGHER = !JAVA_VERSION.startsWith("1.8");
IS_JAVA_13_OR_HIGHER = IS_JAVA_9_OR_HIGHER
&& "13".compareTo(JAVA_VERSION) <= 0;
//
// up to Java 9:
MODIFIER_MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
//
// as of Java 10:
//MODIFIER_MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx();
}
/**
* Returns if the Eadgyth data directory '.eadgyth' exists
* in the user home directory
*
* @return true if the directory exists, false otherwise
* @see #EADGYTH_DATA_DIR
*/
public static boolean existsEadgythDataDir() {
return new File(EADGYTH_DATA_DIR).exists();
}
//
//--private--/
//
private SystemParams() {}
}
|
Eadgyth/Java-Programming-Editor
|
src/eg/utils/SystemParams.java
|
Java
|
mit
| 1,846 |
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;
// import org.apache.commons.cli.*;
class Dumper {
private static FileOutputStream fstream;
public Dumper(String filename) {
try {
fstream = new FileOutputStream(filename);
} catch (FileNotFoundException ex) {
Logger.getLogger(Dumper.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Dump byte array to a file
*
* @param dump byte array
* @param filename
*/
static void dump(byte[] dump, String filename) {
if (dump == null) {
return;
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(filename);
} catch (FileNotFoundException ex) {
Logger.getLogger(ST_decrypt.class.getName()).log(Level.SEVERE, null, ex);
}
try {
fos.write(dump, 0, dump.length);
fos.flush();
fos.close();
} catch (IOException ex) {
Logger.getLogger(ST_decrypt.class.getName()).log(Level.SEVERE, null, ex);
}
}
void append(byte[] b) {
try {
fstream.write(b);
} catch (IOException ex) {
Logger.getLogger(Dumper.class.getName()).log(Level.SEVERE, null, ex);
}
}
void close() {
try {
fstream.close();
} catch (IOException ex) {
Logger.getLogger(Dumper.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
class Crypto {
private static int d(final int n) {
final long n2 = n & 0xFFFFFFFFL;
return (int) ((n2 & 0x7F7F7F7FL) << 1 ^ ((n2 & 0xFFFFFFFF80808080L) >> 7) * 27L);
}
private static int a(final int n, final int n2) {
final long n3 = n & 0xFFFFFFFFL;
return (int) (n3 >> n2 * 8 | n3 << 32 - n2 * 8);
}
static int polynom2(int n) {
final int d3;
final int d2;
final int d = d(d2 = d(d3 = d(n)));
n ^= d;
return d3 ^ (d2 ^ d ^ a(d3 ^ n, 3) ^ a(d2 ^ n, 2) ^ a(n, 1));
}
static int polynom(int n) {
return (d(n) ^ a(n ^ d(n), 3) ^ a(n, 2) ^ a(n, 1));
}
}
public class ST_decrypt {
/**
* Encrypt or decrypt input file
*/
private static boolean encrypt;
private static String encryptionKey;
private static Dumper dumper;
public static void main(String[] args) {
// CommandLineParser parser = new DefaultParser();
// Options options = new Options();
// String help = "st_decrypt.jar [-e] -k <key> -i <input> -o <output>";
// options.addOption("k", "key", true, "encryption key");
// options.addOption("e", "encrypt", false, "encrypt binary");
// options.addOption("i", "input", true, "input file");
// options.addOption("o", "output", true, "output file");
// HelpFormatter formatter = new HelpFormatter();
// CommandLine opts = null;
// try {
// opts = parser.parse(options, args);
// if (opts.hasOption("key")
// && opts.hasOption("input")
// && opts.hasOption("output")) {
// encryptionKey = opts.getOptionValue("key");
// } else {
// formatter.printHelp(help, options);
// System.exit(1);
// }
// encrypt = opts.hasOption("encrypt");
// } catch (ParseException exp) {
// System.out.println(exp.getMessage());
// formatter.printHelp(help, options);
// System.exit(1);
// }
// String output = "/home/jonathan/stm_jig/usb_sniff/f2_5_dec_java.bin";
// String input = "/home/jonathan/stm_jig/usb_sniff/f2_5.bin";
// String output = "/home/jonathan/stm_jig/usb_sniff/16_encrypted";
// String input = "/home/jonathan/stm_jig/usb_sniff/16_unencrypted";
// String output = "/home/jonathan/stm_jig/usb_sniff/f2_5_dec_java_enc.bin";
// String input = "/home/jonathan/stm_jig/usb_sniff/f2_5_dec_java.bin";
// encryptionKey = "I am a key, wawawa";
// // encryptionKey = unHex("496CDB76964E46637CC0237ED87B6B7F");
// // encryptionKey = unHex("E757D2F9F122DEB3FB883ECC1AF4C688");
// // encryptionKey = unHex("8DBDA2460CD8069682D3E9BB755B7FB9");
// encryptionKey = unHex("5F4946053BD9896E8F4CE917A6D2F21A");
// encrypt=true;
encryptionKey = "best performance";
int dataLength = 30720;//(int)getFileLen("/home/jonathan/stm_jig/provisioning-jig/fw_update/fw_upgrade/f2_1.bin");
byte[] fw = new byte[dataLength];
byte[] key = new byte[16];//encryptionKey.getBytes();
byte[] data = new byte[dataLength];// {0xF7, 0x72, 0x44, 0xB3, 0xFC, 0x86, 0xE0, 0xDC, 0x20, 0xE1, 0x74, 0x2D, 0x3A, 0x29, 0x0B, 0xD2};
str_to_arr(encryptionKey, key);
readFileIntoArr(System.getProperty("user.dir") + "/f2_1.bin", data);
decrypt(data, fw, key, dataLength);
System.out.println(dataLength);
System.out.println(toHexStr(fw).length());
// Write out the decrypted fw for debugging
String outf = "fw_decrypted.bin";
dumper = new Dumper(outf);
dumper.dump(fw, outf);
dumper.close();
// fw now contains our decrypted firmware
// Make a key from the first 4 and last 12 bytes returned by f308
encryptionKey = "I am key, wawawa";
byte[] newKey = new byte[16];
byte[] f308 = new byte[16];
str_to_arr(encryptionKey, key);
readFileIntoArr("f303_bytes_4_12.bin", f308);
encrypt(f308, newKey, key, 16);
System.out.print("Using key: ");
System.out.println(toHexStr(newKey));
System.out.print("From bytes: ");
System.out.println(toHexStr(f308));
byte[] enc_fw = new byte[dataLength];
encrypt(fw, enc_fw, newKey, dataLength);
// System.out.println(toHexStr(enc_fw));
// Now for real
String outfile = "fw_re_encrypted.bin";
dumper = new Dumper(outfile);
dumper.dump(enc_fw, outfile);
dumper.close();
byte[] a = new byte[16];
byte[] ans = new byte[16];
str_to_arr(unHex("ffffffffffffffffffffffffd32700a5"), a);
encrypt(a, ans, newKey, 16);
System.out.println("Final 16 bytes: " + toHexStr(ans));
outfile = "version_thingee_16.bin";
dumper = new Dumper(outfile);
dumper.dump(ans, outfile);
dumper.close();
// dumper = new Dumper(output);
// dump_fw(input);
// dumper.close();
// System.out.println("Done!");
}
// ***************** MY Code functions ***************** JW
static void readFileIntoArr(String file, byte[] data){
FileInputStream fis = null;
try {
File f = new File(file);
fis = new FileInputStream(f);
} catch (Exception ex) {
System.out.print(file);
System.out.println("Invalid file name");
System.exit(1);
}
try (BufferedInputStream bufferedInputStream = new BufferedInputStream(fis)) {
long len = getFileLen(file);
bufferedInputStream.read(data);
} catch (IOException ex) {
Logger.getLogger(ST_decrypt.class.getName()).log(Level.SEVERE, null, ex);
}
}
static String toHexStr(byte[] B){
StringBuilder str = new StringBuilder();
for(int i = 0; i < B.length; i++){
str.append(String.format("%02x", B[i]));
}
return str.toString();
}
static String unHex(String arg) {
String str = "";
for(int i=0;i<arg.length();i+=2)
{
String s = arg.substring(i, (i + 2));
int decimal = Integer.parseInt(s, 16);
str = str + (char) decimal;
}
return str;
}
// *******************************************************
static long getFileLen(String file) {
long n2 = 0L;
FileInputStream fis = null;
try {
File f = new File(file);
fis = new FileInputStream(f);
} catch (Exception ex) {
}
try {
BufferedInputStream bufferedInputStream = new BufferedInputStream(fis);
while (true) {
int read;
try {
read = bufferedInputStream.read();
} catch (IOException ex) {
System.out.println("Failure opening file");
read = -1;
}
if (read == -1) {
break;
}
++n2;
}
bufferedInputStream.close();
} catch (IOException ex3) {
System.out.println("Failure getting firmware data");
}
return n2;
}
/**
*
* @param array firmware byte array
* @param n length
* @param n2 ??
* @return
*/
static long encodeAndWrite(final byte[] array, long n, final int n2) {
long a = 0L;
final byte[] array2 = new byte[4 * ((array.length + 3) / 4)]; // Clever hack to get multiple of fourwith padding
final byte[] array3 = new byte[16];
str_to_arr(encryptionKey, array3);
if (encrypt) {
encrypt(array, array2, array3, array.length);
} else {
decrypt(array, array2, array3, array.length);
}
/* Send chunk of data to device */
dumper.append(array2);
return a;
}
static long writeFirmware(final BufferedInputStream bufferedInputStream, final long n) {
long a = 0L;
final byte[] array = new byte[3072];
long n4 = 0L;
try {
while (n4 < n && a == 0L) {
final long n5;
if ((n5 = bufferedInputStream.read(array)) != -1L) {
encodeAndWrite(array, n4 + 134234112L, 3072);
n4 += n5;
}
}
} catch (IOException ex) {
System.out.println("Failure reading file: " + ex.getMessage());
System.exit(1);
}
return a;
}
static void dump_fw(String file) {
FileInputStream fis = null;
try {
File f = new File(file);
fis = new FileInputStream(f);
} catch (Exception ex) {
System.out.println("Invalid file name");
System.exit(1);
}
try (BufferedInputStream bufferedInputStream = new BufferedInputStream(fis)) {
long len = getFileLen(file);
writeFirmware(bufferedInputStream, len);
} catch (IOException ex) {
Logger.getLogger(ST_decrypt.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static int pack_u32(final int n, final int n2, final int n3, final int n4) {
return (n << 24 & 0xFF000000) + (n2 << 16 & 0xFF0000) + (n3 << 8 & 0xFF00) + (n4 & 0xFF);
}
private static int u32(final int n) {
return n >>> 24;
}
private static int u16(final int n) {
return n >> 16 & 0xFF;
}
private static int u8(final int n) {
return n >> 8 & 0xFF;
}
/**
* Converts the key from String to byte array
*
* @param s input string
* @param array destination array
*/
public static void str_to_arr(final String s, final byte[] array) {
final char[] charArray = s.toCharArray();
for (int i = 0; i < 16; ++i) {
array[i] = (byte) charArray[i];
}
}
private static void key_decode(final byte[] array, final int[] array2) { // core.a.a(byte[], byte[])
final int[] array3 = new int[4];
for (int i = 0; i < 4; ++i) {
array2[i] = (array3[i] = ByteBuffer.wrap(array).order(ByteOrder.LITTLE_ENDIAN).getInt(4 * i));
}
for (int j = 0; j < 10;) {
array3[0] ^= (int) (pack_u32(aes_x[u16(array3[3])], aes_x[u8(array3[3])], aes_x[array3[3] & 0xFF], aes_x[u32(array3[3])]) ^ rcon[j++]);
array3[1] ^= array3[0];
array3[2] ^= array3[1];
array3[3] ^= array3[2];
System.arraycopy(array3, 0, array2, 4 * j, 4);
}
}
/**
* Encrypt firmware file
*/
static void encrypt(final byte[] src, final byte[] dest, byte[] key, int len) {
final byte[] array3 = new byte[16];
int n = 0;
key_decode(key, mystery_key);
while (len > 0) {
key = null;
int n2;
if (len >= 16) {
key = Arrays.copyOfRange(src, n, n + 16);
n2 = 16;
} else if ((n2 = len) > 0) {
final byte[] array4 = new byte[16];
for (int j = 0; j < len; ++j) {
array4[j] = src[n + j];
}
for (int k = len; k < 16; ++k) {
array4[k] = (byte) Double.doubleToLongBits(Math.random());
}
key = array4;
}
if (len > 0) {
final int[] a = mystery_key;
final int[] tmp = new int[4];
int n3 = 10;
int n4 = 0;
for (int l = 0; l < 4; ++l) {
tmp[l] = (ByteBuffer.wrap(key).order(ByteOrder.LITTLE_ENDIAN).getInt(4 * l) ^ a[l + 0]);
}
n4 += 4;
do {
final int a2 = pack_u32(aes_x[u32(tmp[0])], aes_x[u16(tmp[1])], aes_x[u8(tmp[2])], aes_x[tmp[3] & 0xFF]);
final int a3 = pack_u32(aes_x[u32(tmp[1])], aes_x[u16(tmp[2])], aes_x[u8(tmp[3])], aes_x[tmp[0] & 0xFF]);
final int a4 = pack_u32(aes_x[u32(tmp[2])], aes_x[u16(tmp[3])], aes_x[u8(tmp[0])], aes_x[tmp[1] & 0xFF]);
final int a5 = pack_u32(aes_x[u32(tmp[3])], aes_x[u16(tmp[0])], aes_x[u8(tmp[1])], aes_x[tmp[2] & 0xFF]);
tmp[0] = (Crypto.polynom(a2) ^ a[n4]);
tmp[1] = (Crypto.polynom(a3) ^ a[n4 + 1]);
tmp[2] = (Crypto.polynom(a4) ^ a[n4 + 2]);
tmp[3] = (Crypto.polynom(a5) ^ a[n4 + 3]);
n4 += 4;
} while (--n3 != 1);
final int a6 = pack_u32(aes_x[u32(tmp[0])], aes_x[u16(tmp[1])], aes_x[u8(tmp[2])], aes_x[tmp[3] & 0xFF]);
final int a7 = pack_u32(aes_x[u32(tmp[1])], aes_x[u16(tmp[2])], aes_x[u8(tmp[3])], aes_x[tmp[0] & 0xFF]);
final int a8 = pack_u32(aes_x[u32(tmp[2])], aes_x[u16(tmp[3])], aes_x[u8(tmp[0])], aes_x[tmp[1] & 0xFF]);
final int a9 = pack_u32(aes_x[u32(tmp[3])], aes_x[u16(tmp[0])], aes_x[u8(tmp[1])], aes_x[tmp[2] & 0xFF]);
final int n5 = a6 ^ a[n4];
final int n6 = a7 ^ a[n4 + 1];
final int n7 = a8 ^ a[n4 + 2];
final int n8 = a9 ^ a[n4 + 3];
ByteBuffer.wrap(array3).order(ByteOrder.LITTLE_ENDIAN).putInt(n5);
ByteBuffer.wrap(array3).order(ByteOrder.LITTLE_ENDIAN).putInt(4, n6);
ByteBuffer.wrap(array3).order(ByteOrder.LITTLE_ENDIAN).putInt(8, n7);
ByteBuffer.wrap(array3).order(ByteOrder.LITTLE_ENDIAN).putInt(12, n8);
}
for (int i = 0; i < 16; ++i) {
dest[n + i] = array3[i];
}
len -= n2;
n += n2;
}
}
/**
* Decrypt firmware file
*
* @param src firmware file
* @param dest destination array
* @param key key
* @param len array.length
*/
static void decrypt(final byte[] src, final byte[] dest, byte[] key, int len) {
final byte[] array3 = new byte[16];
int n = 0;
key_decode(key, mystery_key);
while (len > 0) {
key = null;
int n2;
if (len >= 16) {
key = Arrays.copyOfRange(src, n, n + 16);
n2 = 16;
} else if ((n2 = len) > 0) {
final byte[] array4 = new byte[16];
for (int j = 0; j < len; ++j) {
array4[j] = src[n + j];
}
for (int k = len; k < 16; ++k) {
array4[k] = (byte) Double.doubleToLongBits(Math.random());
}
key = array4;
}
if (len > 0) {
final int[] a = mystery_key;
final int[] tmp = new int[4];
int n3 = 10;
int n4 = 40;
for (int l = 0; l < 4; ++l) {
tmp[l] = (ByteBuffer.wrap(key).order(ByteOrder.LITTLE_ENDIAN).getInt(4 * l) ^ a[l + 40]);
}
n4 -= 8;
do {
final int n5 = pack_u32(aes_y[u32(tmp[0])], aes_y[u16(tmp[3])], aes_y[u8(tmp[2])], aes_y[tmp[1] & 0xFF]) ^ a[n4 + 4];
final int n6 = pack_u32(aes_y[u32(tmp[1])], aes_y[u16(tmp[0])], aes_y[u8(tmp[3])], aes_y[tmp[2] & 0xFF]) ^ a[n4 + 5];
final int n7 = pack_u32(aes_y[u32(tmp[2])], aes_y[u16(tmp[1])], aes_y[u8(tmp[0])], aes_y[tmp[3] & 0xFF]) ^ a[n4 + 6];
final int n8 = pack_u32(aes_y[u32(tmp[3])], aes_y[u16(tmp[2])], aes_y[u8(tmp[1])], aes_y[tmp[0] & 0xFF]) ^ a[n4 + 7];
tmp[0] = Crypto.polynom2(n5);
tmp[1] = Crypto.polynom2(n6);
tmp[2] = Crypto.polynom2(n7);
tmp[3] = Crypto.polynom2(n8);
n4 -= 4;
} while (--n3 != 1);
final int n9 = pack_u32(aes_y[u32(tmp[0])], aes_y[u16(tmp[3])], aes_y[u8(tmp[2])], aes_y[tmp[1] & 0xFF]) ^ a[n4 + 4];
final int n10 = pack_u32(aes_y[u32(tmp[1])], aes_y[u16(tmp[0])], aes_y[u8(tmp[3])], aes_y[tmp[2] & 0xFF]) ^ a[n4 + 5];
final int n11 = pack_u32(aes_y[u32(tmp[2])], aes_y[u16(tmp[1])], aes_y[u8(tmp[0])], aes_y[tmp[3] & 0xFF]) ^ a[n4 + 6];
final int n12 = pack_u32(aes_y[u32(tmp[3])], aes_y[u16(tmp[2])], aes_y[u8(tmp[1])], aes_y[tmp[0] & 0xFF]) ^ a[n4 + 7];
ByteBuffer.wrap(array3).order(ByteOrder.LITTLE_ENDIAN).putInt(n9);
ByteBuffer.wrap(array3).order(ByteOrder.LITTLE_ENDIAN).putInt(4, n10);
ByteBuffer.wrap(array3).order(ByteOrder.LITTLE_ENDIAN).putInt(8, n11);
ByteBuffer.wrap(array3).order(ByteOrder.LITTLE_ENDIAN).putInt(12, n12);
}
for (int i = 0; i < n2; ++i) {
dest[n + i] = array3[i];
}
len -= n2;
n += n2;
}
}
static int[] mystery_key = new int[44];
static int[] aes_x = {
0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B,
0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0,
0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26,
0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,
0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2,
0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0,
0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED,
0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,
0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F,
0x50, 0x3C, 0x9F, 0xA8, 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5,
0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, 0xCD, 0x0C, 0x13, 0xEC,
0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,
0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14,
0xDE, 0x5E, 0x0B, 0xDB, 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C,
0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, 0xE7, 0xC8, 0x37, 0x6D,
0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,
0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F,
0x4B, 0xBD, 0x8B, 0x8A, 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E,
0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, 0xE1, 0xF8, 0x98, 0x11,
0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,
0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F,
0xB0, 0x54, 0xBB, 0x16
};
static int[] aes_y = {
0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E,
0x81, 0xF3, 0xD7, 0xFB, 0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87,
0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB, 0x54, 0x7B, 0x94, 0x32,
0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E,
0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49,
0x6D, 0x8B, 0xD1, 0x25, 0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16,
0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92, 0x6C, 0x70, 0x48, 0x50,
0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84,
0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05,
0xB8, 0xB3, 0x45, 0x06, 0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02,
0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B, 0x3A, 0x91, 0x11, 0x41,
0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73,
0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8,
0x1C, 0x75, 0xDF, 0x6E, 0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89,
0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B, 0xFC, 0x56, 0x3E, 0x4B,
0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4,
0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59,
0x27, 0x80, 0xEC, 0x5F, 0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D,
0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF, 0xA0, 0xE0, 0x3B, 0x4D,
0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61,
0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63,
0x55, 0x21, 0x0C, 0x7D
};
static long[] rcon = {
0x01000000L, 0x02000000L, 0x04000000L, 0x08000000L, 0x10000000L,
0x20000000L, 0x40000000L, 0xFFFFFFFF80000000L, 0x1B000000L, 0x36000000L
};
}
|
UCT-White-Lab/provisioning-jig
|
fw_update/ST_decrypt.java
|
Java
|
mit
| 22,664 |
/**
* Copyright (c) 2013 Andre Ricardo Schaffer
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.wiselenium.elements.component;
import java.util.List;
/**
* Represents a HTML Multiple Select.
*
* @author Andre Ricardo Schaffer
* @since 0.3.0
*/
public interface MultiSelect extends Component<MultiSelect> {
/**
* Deselects all options.
*
* @return This select instance to allow chain calls.
* @since 0.3.0
*/
MultiSelect deselectAll();
/**
* Deselects all options at the given indexes. This is done by examing the "index" attribute of
* an element, and not merely by counting.
*
* @param indexes The option at this index will be selected.
* @return This select element to allow chain calls.
* @since 0.3.0
*/
MultiSelect deselectByIndex(int... indexes);
/**
* Deselects all options that have a value matching the argument. That is, when given "foo" this
* would select an option like: <option value="foo">Bar</option>
*
* @param values The values to match against.
* @return This select element to allow chain calls.
* @since 0.3.0
*/
MultiSelect deselectByValue(String... values);
/**
* Deselects all options that display text matching the argument. That is, when given "Bar" this
* would select an option like: <option value="foo">Bar</option>
*
* @param texts The visible texts to match against.
* @return This select element to allow chain calls.
* @since 0.3.0
*/
MultiSelect deselectByVisibleText(String... texts);
/**
* Deselects some options of this select if not already deselected.
*
* @param options The options to be deselected.
* @return This select instance in order to allow chain calls.
* @since 0.3.0
*/
MultiSelect deselectOptions(Option... options);
/**
* Gets the options of this select.
*
* @return The options of this select.
* @since 0.3.0
*/
List<Option> getOptions();
/**
* Returns the selected options.
*
* @return The selected options.
* @since 0.3.0
*/
List<Option> getSelectedOptions();
/**
* Returns the selected values.
*
* @return The selected values.
* @since 0.3.0
*/
List<String> getSelectedValues();
/**
* Returns the selected visible texts.
*
* @return The selected visible texts.
* @since 0.3.0
*/
List<String> getSelectedVisibleTexts();
/**
* Selects all options.
*
* @return This select instance to allow chain calls.
* @since 0.3.0
*/
MultiSelect selectAll();
/**
* Selects all options at the given indexes. This is done by examing the "index" attribute of an
* element, and not merely by counting.
*
* @param indexes The option at this index will be selected.
* @return This select element to allow chain calls.
* @since 0.3.0
*/
MultiSelect selectByIndex(int... indexes);
/**
* Selects all options that have a value matching the argument. That is, when given "foo" this
* would select an option like: <option value="foo">Bar</option>
*
* @param values The values to match against.
* @return This select element to allow chain calls.
* @since 0.3.0
*/
MultiSelect selectByValue(String... values);
/**
* Selects all options that display text matching the argument. That is, when given "Bar" this
* would select an option like: <option value="foo">Bar</option>
*
* @param texts The visible texts to match against.
* @return This select element to allow chain calls.
* @since 0.3.0
*/
MultiSelect selectByVisibleText(String... texts);
/**
* Selects some options of this select if not already selected.
*
* @param options The options to be selected.
* @return This select instance in order to allow chain calls.
* @since 0.3.0
*/
MultiSelect selectOptions(Option... options);
}
|
wiselenium/wiselenium
|
wiselenium-elements/src/main/java/com/github/wiselenium/elements/component/MultiSelect.java
|
Java
|
mit
| 4,862 |
package lexek.wschat.db.dao;
import lexek.wschat.chat.e.EntityNotFoundException;
import lexek.wschat.chat.e.InvalidInputException;
import lexek.wschat.db.model.DataPage;
import lexek.wschat.db.model.UserData;
import lexek.wschat.db.model.UserDto;
import lexek.wschat.db.model.form.UserChangeSet;
import lexek.wschat.util.Pages;
import org.jooq.Condition;
import org.jooq.DSLContext;
import org.jooq.Record;
import org.jooq.exception.DataAccessException;
import org.jooq.impl.DSL;
import org.jvnet.hk2.annotations.Service;
import javax.inject.Inject;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import static lexek.wschat.db.jooq.tables.User.USER;
import static lexek.wschat.db.jooq.tables.Userauth.USERAUTH;
@Service
public class UserDao {
private final DSLContext ctx;
@Inject
public UserDao(DSLContext ctx) {
this.ctx = ctx;
}
public boolean tryChangeName(long id, String newName, boolean ignoreCheck) {
try {
Condition condition = USER.ID.equal(id);
if (!ignoreCheck) {
condition.and(USER.RENAME_AVAILABLE.equal(true));
}
return ctx
.update(USER)
.set(USER.NAME, newName)
.set(USER.RENAME_AVAILABLE, false)
.where(condition)
.execute() == 1;
} catch (DataAccessException e) {
throw new InvalidInputException("name", "NAME_TAKEN");
}
}
public UserDto getByNameOrEmail(String name) {
Record record = ctx
.select()
.from(USER)
.where(
USER.EMAIL.isNotNull(),
USER.NAME.equal(name).or(USER.EMAIL.equal(name)),
USER.EMAIL_VERIFIED.isTrue()
)
.fetchOne();
return UserDto.fromRecord(record);
}
public UserDto getByName(String name) {
Record record = ctx
.select()
.from(USER)
.where(USER.NAME.equal(name))
.fetchOne();
return UserDto.fromRecord(record);
}
public UserDto getById(long id) {
Record record = ctx
.select()
.from(USER)
.where(USER.ID.equal(id))
.fetchOne();
return UserDto.fromRecord(record);
}
public UserDto update(long id, UserChangeSet changeSet) {
Map<org.jooq.Field<?>, Object> changeMap = new HashMap<>();
if (changeSet.getBanned() != null) {
changeMap.put(USER.BANNED, changeSet.getBanned());
}
if (changeSet.getRenameAvailable() != null) {
changeMap.put(USER.RENAME_AVAILABLE, changeSet.getRenameAvailable());
}
if (changeSet.getName() != null) {
changeMap.put(USER.NAME, changeSet.getName());
}
if (changeSet.getRole() != null) {
changeMap.put(USER.ROLE, changeSet.getRole().toString());
}
UserDto userDto = null;
boolean success = ctx
.update(USER)
.set(changeMap)
.where(USER.ID.equal(id))
.execute() == 1;
if (success) {
Record record = ctx
.selectFrom(USER)
.where(USER.ID.equal(id))
.fetchOne();
userDto = UserDto.fromRecord(record);
}
return userDto;
}
public void setColor(long id, String color) {
ctx
.update(USER)
.set(USER.COLOR, color)
.where(USER.ID.equal(id))
.execute();
}
public DataPage<UserData> getAllPaged(int page, int pageLength) {
List<UserData> data = ctx
.select(
USER.ID, USER.NAME, USER.ROLE, USER.COLOR, USER.BANNED, USER.RENAME_AVAILABLE,
USER.EMAIL, USER.EMAIL_VERIFIED, USER.CHECK_IP,
DSL.groupConcat(USERAUTH.SERVICE).as("authServices"),
DSL.groupConcat(DSL.coalesce(USERAUTH.AUTH_NAME, "")).as("authNames")
)
.from(USER.join(USERAUTH).on(USER.ID.equal(USERAUTH.USER_ID)))
.groupBy(USER.ID)
.orderBy(USER.ID)
.limit(page * pageLength, pageLength)
.fetch()
.stream()
.map(record -> new UserData(
UserDto.fromRecord(record),
collectAuthServices(
record.getValue("authServices", String.class),
record.getValue("authNames", String.class)
)
))
.collect(Collectors.toList());
return new DataPage<>(data, page, Pages.pageCount(pageLength, ctx.fetchCount(USER)));
}
public DataPage<UserData> searchPaged(Integer page, int pageLength, String nameParam) {
List<UserData> data = ctx
.select(USER.ID, USER.NAME, USER.ROLE, USER.COLOR, USER.BANNED, USER.CHECK_IP,
USER.RENAME_AVAILABLE, USER.EMAIL, USER.EMAIL_VERIFIED,
DSL.groupConcat(USERAUTH.SERVICE).as("authServices"),
DSL.groupConcat(DSL.coalesce(USERAUTH.AUTH_NAME, "")).as("authNames"))
.from(USER.join(USERAUTH).on(USER.ID.equal(USERAUTH.USER_ID)))
.where(USER.NAME.like(nameParam, '!'))
.groupBy(USER.ID)
.orderBy(USER.ID)
.limit(page * pageLength, pageLength)
.fetch()
.stream()
.map(record -> new UserData(
UserDto.fromRecord(record),
collectAuthServices(
record.getValue("authServices", String.class),
record.getValue("authNames", String.class)
)
))
.collect(Collectors.toList());
return new DataPage<>(data, page,
Pages.pageCount(pageLength, ctx.fetchCount(USER, USER.NAME.like(nameParam, '!'))));
}
public List<UserDto> searchSimple(int pageLength, String nameParam) {
return ctx
.selectFrom(USER)
.where(USER.NAME.like(nameParam, '!'))
.groupBy(USER.ID)
.orderBy(USER.ID)
.limit(pageLength)
.fetch()
.stream()
.map(UserDto::fromRecord)
.collect(Collectors.toList());
}
public boolean delete(UserDto user) {
return ctx
.delete(USER)
.where(USER.ID.equal(user.getId()))
.execute() == 1;
}
public boolean checkName(String username) {
return ctx
.selectOne()
.from(USER)
.where(USER.NAME.equal(username))
.fetchOne() == null;
}
public UserData fetchData(long id) {
UserData result = null;
Record record = ctx
.select(USER.ID, USER.NAME, USER.ROLE, USER.COLOR, USER.BANNED, USER.RENAME_AVAILABLE, USER.EMAIL,
USER.EMAIL_VERIFIED, USER.CHECK_IP,
DSL.groupConcat(USERAUTH.SERVICE).as("authServices"),
DSL.groupConcat(DSL.coalesce(USERAUTH.AUTH_NAME, "")).as("authNames"))
.from(USER.join(USERAUTH).on(USER.ID.equal(USERAUTH.USER_ID)))
.where(USER.ID.equal(id))
.groupBy(USER.ID)
.fetchOne();
if (record != null) {
result = new UserData(
UserDto.fromRecord(record),
collectAuthServices(
record.getValue("authServices", String.class),
record.getValue("authNames", String.class)
)
);
}
return result;
}
public List<UserDto> getAdmins() {
return ctx
.select()
.from(USER)
.where(USER.ROLE.in("ADMIN", "SUPERADMIN"))
.fetch()
.stream()
.map(UserDto::fromRecord)
.collect(Collectors.toList());
}
public void setCheckIp(UserDto user, boolean value) {
int rows = ctx
.update(USER)
.set(USER.CHECK_IP, value)
.where(USER.ID.equal(user.getId()))
.execute();
if (rows == 0) {
throw new EntityNotFoundException("user");
}
}
private Map<String, String> collectAuthServices(String servicesString, String namesString) {
String[] authServices = servicesString.split(",", -1);
String[] authNames = namesString.split(",", -1);
Map<String, String> result = new HashMap<>();
for (int i = 0; i < authServices.length; ++i) {
result.put(authServices[i], authNames[i]);
}
return result;
}
}
|
lexek/chat
|
src/main/java/lexek/wschat/db/dao/UserDao.java
|
Java
|
mit
| 8,668 |
/*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.gradle.model.internal.core;
import com.google.common.base.Function;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import groovy.lang.Closure;
import org.gradle.api.Action;
import org.gradle.api.internal.ClosureBackedAction;
import org.gradle.api.specs.Specs;
import org.gradle.model.ModelSet;
import org.gradle.model.internal.core.rule.describe.ModelRuleDescriptor;
import org.gradle.model.internal.manage.instance.ManagedInstance;
import org.gradle.model.internal.type.ModelType;
import java.util.Collection;
import java.util.Iterator;
import static org.gradle.model.internal.core.NodePredicate.allLinks;
public class NodeBackedModelSet<T> implements ModelSet<T>, ManagedInstance {
private final String toString;
private final ModelType<T> elementType;
private final ModelRuleDescriptor descriptor;
private final MutableModelNode modelNode;
private final ModelViewState state;
private final ChildNodeInitializerStrategy<T> creatorStrategy;
private final ModelReference<T> elementTypeReference;
private Collection<T> elements;
public NodeBackedModelSet(String toString, ModelType<T> elementType, ModelRuleDescriptor descriptor, MutableModelNode modelNode, ModelViewState state, ChildNodeInitializerStrategy<T> creatorStrategy) {
this.toString = toString;
this.elementType = elementType;
this.elementTypeReference = ModelReference.of(elementType);
this.descriptor = descriptor;
this.modelNode = modelNode;
this.state = state;
this.creatorStrategy = creatorStrategy;
}
@Override
public MutableModelNode getBackingNode() {
return modelNode;
}
@Override
public ModelType<?> getManagedType() {
return ModelType.of(this.getClass());
}
@Override
public String toString() {
return toString;
}
@Override
public void create(final Action<? super T> action) {
state.assertCanMutate();
String name = String.valueOf(modelNode.getLinkCount(ModelNodes.withType(elementType)));
ModelPath childPath = modelNode.getPath().child(name);
final ModelRuleDescriptor descriptor = this.descriptor.append("create()");
NodeInitializer nodeInitializer = creatorStrategy.initializer(elementType, Specs.<ModelType<?>>satisfyAll());
ModelRegistration registration = ModelRegistrations.of(childPath, nodeInitializer)
.descriptor(descriptor)
.action(ModelActionRole.Initialize, NoInputsModelAction.of(ModelReference.of(childPath, elementType), descriptor, action))
.build();
modelNode.addLink(registration);
}
@Override
public void afterEach(Action<? super T> configAction) {
state.assertCanMutate();
modelNode.applyTo(allLinks(), ModelActionRole.Finalize, NoInputsModelAction.of(elementTypeReference, descriptor.append("afterEach()"), configAction));
}
@Override
public void beforeEach(Action<? super T> configAction) {
state.assertCanMutate();
modelNode.applyTo(allLinks(), ModelActionRole.Defaults, NoInputsModelAction.of(elementTypeReference, descriptor.append("afterEach()"), configAction));
}
@Override
public int size() {
state.assertCanReadChildren();
return modelNode.getLinkCount(ModelNodes.withType(elementType));
}
@Override
public boolean isEmpty() {
return size() == 0;
}
@Override
public boolean contains(Object o) {
return getElements().contains(o);
}
@Override
public Iterator<T> iterator() {
return getElements().iterator();
}
@Override
public Object[] toArray() {
return getElements().toArray();
}
@Override
public <T> T[] toArray(T[] a) {
return getElements().toArray(a);
}
@Override
public boolean add(T e) {
throw new UnsupportedOperationException();
}
@Override
public boolean remove(Object o) {
throw new UnsupportedOperationException();
}
@Override
public boolean containsAll(Collection<?> c) {
return getElements().containsAll(c);
}
@Override
public boolean addAll(Collection<? extends T> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean retainAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public boolean removeAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
// TODO - mix this in using decoration. Also validate closure parameter types, if declared
public void create(Closure<?> closure) {
create(ClosureBackedAction.of(closure));
}
public void afterEach(Closure<?> closure) {
afterEach(ClosureBackedAction.of(closure));
}
public void beforeEach(Closure<?> closure) {
beforeEach(ClosureBackedAction.of(closure));
}
private Collection<T> getElements() {
state.assertCanReadChildren();
if (elements == null) {
elements = Lists.newArrayList(
Iterables.transform(modelNode.getLinks(ModelNodes.withType(elementType)), new Function<MutableModelNode, T>() {
@Override
public T apply(MutableModelNode input) {
return input.asImmutable(elementType, descriptor).getInstance();
}
})
);
}
return elements;
}
}
|
HenryHarper/Acquire-Reboot
|
gradle/src/model-core/org/gradle/model/internal/core/NodeBackedModelSet.java
|
Java
|
mit
| 6,263 |
package mekanism.common.transmitters;
import mekanism.api.transmitters.DynamicNetwork;
import mekanism.api.transmitters.IGridTransmitter;
public abstract class Transmitter<A, N extends DynamicNetwork<A, N>> implements IGridTransmitter<A, N>
{
public N theNetwork = null;
public boolean orphaned = true;
@Override
public N getTransmitterNetwork()
{
return theNetwork;
}
@Override
public boolean hasTransmitterNetwork()
{
return !isOrphan() && getTransmitterNetwork() != null;
}
@Override
public void setTransmitterNetwork(N network)
{
if(theNetwork == network)
{
return;
}
if(world().isRemote && theNetwork != null)
{
theNetwork.transmitters.remove(this);
if(theNetwork.transmitters.isEmpty())
{
theNetwork.deregister();
}
}
theNetwork = network;
orphaned = theNetwork == null;
if(world().isRemote && theNetwork != null)
{
theNetwork.transmitters.add(this);
}
}
@Override
public int getTransmitterNetworkSize()
{
return hasTransmitterNetwork() ? getTransmitterNetwork().getSize() : 0;
}
@Override
public int getTransmitterNetworkAcceptorSize()
{
return hasTransmitterNetwork() ? getTransmitterNetwork().getAcceptorSize() : 0;
}
@Override
public String getTransmitterNetworkNeeded()
{
return hasTransmitterNetwork() ? getTransmitterNetwork().getNeededInfo() : "No Network";
}
@Override
public String getTransmitterNetworkFlow()
{
return hasTransmitterNetwork() ? getTransmitterNetwork().getFlowInfo() : "No Network";
}
@Override
public String getTransmitterNetworkBuffer()
{
return hasTransmitterNetwork() ? getTransmitterNetwork().getStoredInfo() : "No Network";
}
@Override
public double getTransmitterNetworkCapacity()
{
return hasTransmitterNetwork() ? getTransmitterNetwork().getCapacity() : getCapacity();
}
@Override
public boolean isOrphan()
{
return orphaned;
}
@Override
public void setOrphan(boolean nowOrphaned)
{
orphaned = nowOrphaned;
}
}
|
Microsoft/vsminecraft
|
minecraftpkg/MekanismModSample/src/main/java/mekanism/common/transmitters/Transmitter.java
|
Java
|
mit
| 1,976 |
package commenttemplate.expressions.exceptions;
/**
*
* @author thiago
*/
// @TODO: RuntimeException?
public class FunctionWithSameNameAlreadyExistsException extends RuntimeException {
/**
* Justa a custom mensage.
*
* @param msg A custom mensage.
*/
public FunctionWithSameNameAlreadyExistsException(String msg) {
super(msg);
}
}
|
thiagorabelo/CommentTemplate
|
src/commenttemplate/expressions/exceptions/FunctionWithSameNameAlreadyExistsException.java
|
Java
|
mit
| 351 |
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 Curt Binder
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package info.curtbinder.reefangel.phone;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.List;
import info.curtbinder.reefangel.wizard.SetupWizardActivity;
public class MainActivity extends AppCompatActivity
implements ActionBar.OnNavigationListener {
// public static final int REQUEST_EXIT = 1;
// public static final int RESULT_EXIT = 1024;
private static final String OPENED_KEY = "OPENED_KEY";
private static final String STATE_CHECKED = "DRAWER_CHECKED";
private static final String PREVIOUS_CHECKED = "PREVIOUS";
// do not switch selected profile when restoring the application state
private static boolean fRestoreState = false;
public final String TAG = MainActivity.class.getSimpleName();
private RAApplication raApp;
private String[] mNavTitles;
private Toolbar mToolbar;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private Boolean opened = null;
private int mOldPosition = -1;
private Boolean fCanExit = false;
private Fragment mHistoryContent = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
raApp = (RAApplication) getApplication();
raApp.raprefs.setDefaultPreferences();
// Set the Theme before the layout is instantiated
//Utils.onActivityCreateSetTheme(this, raApp.raprefs.getSelectedTheme());
setContentView(R.layout.activity_main);
// Check for first run
if (raApp.isFirstRun()) {
Intent i = new Intent(this, SetupWizardActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(i);
finish();
}
// Load any saved position
int position = 0;
if (savedInstanceState != null) {
position = savedInstanceState.getInt(STATE_CHECKED, 0);
Log.d(TAG, "Restore, position: " + position);
if (position == 3) {
// history fragment
mHistoryContent = getSupportFragmentManager().getFragment(savedInstanceState, "HistoryGraphFragment");
}
}
setupToolbar();
setupNavDrawer();
updateActionBar();
selectItem(position);
// launch a new thread to show the drawer on very first app launch
new Thread(new Runnable() {
@Override
public void run() {
opened = raApp.raprefs.getBoolean(OPENED_KEY, false);
if (!opened) {
mDrawerLayout.openDrawer(mDrawerList);
}
}
}).start();
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// get the checked item and subtract off one to get the actual position
// the same logic applies that is used in the DrawerItemClickedListener.onItemClicked
int position = mDrawerList.getCheckedItemPosition() - 1;
outState.putInt(STATE_CHECKED, position);
if (position == 3) {
getSupportFragmentManager().putFragment(outState, "HistoryGraphFragment", mHistoryContent);
}
}
@Override
protected void onResume() {
super.onResume();
fCanExit = false;
fRestoreState = true;
setNavigationList();
if (raApp.raprefs.isKeepScreenOnEnabled()) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
// last thing we do is display the changelog if necessary
// TODO add in a preference check for displaying changelog on app startup
raApp.displayChangeLog(this);
}
@Override
protected void onPause() {
super.onPause();
}
private void setupToolbar() {
mToolbar = (Toolbar) findViewById(R.id.toolbar);
mToolbar.setTitle("");
setSupportActionBar(mToolbar);
}
private void setupNavDrawer() {
// get the string array for the navigation items
mNavTitles = getResources().getStringArray(R.array.nav_items);
// locate the navigation drawer items in the layout
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// set a custom shadow that overlays the main content when the drawer
// opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
// add in the logo header
View header = getLayoutInflater().inflate(R.layout.drawer_list_header, null);
mDrawerList.addHeaderView(header, null, false);
// set the adapter for the navigation list view
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(this, R.layout.drawer_list_item,
mNavTitles);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// setup the toggling for the drawer
mDrawerToggle =
new MyDrawerToggle(this, mDrawerLayout, mToolbar,
R.string.drawer_open, R.string.drawer_close);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void setNavigationList() {
// set list navigation items
final ActionBar ab = getSupportActionBar();
Context context = ab.getThemedContext();
int arrayID;
if (raApp.isAwayProfileEnabled()) {
arrayID = R.array.profileLabels;
} else {
arrayID = R.array.profileLabelsHomeOnly;
}
ArrayAdapter<CharSequence> list =
ArrayAdapter.createFromResource(context, arrayID,
R.layout.support_simple_spinner_dropdown_item);
ab.setListNavigationCallbacks(list, this);
ab.setSelectedNavigationItem(raApp.getSelectedProfile());
}
private void updateActionBar() {
// update actionbar
final ActionBar ab = getSupportActionBar();
ab.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
}
@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
// only switch profiles when the user changes the navigation item,
// not when the navigation list state is restored
if (!fRestoreState) {
raApp.setSelectedProfile(itemPosition);
} else {
fRestoreState = false;
}
return true;
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
@Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// sync the toggle state after onRestoreInstanceState has occurred
mDrawerToggle.syncState();
}
@Override
public void onBackPressed() {
/*
When the back button is pressed, this function is called.
If the drawer is open, check it and cancel it here.
Calling super.onBackPressed() causes the BackStackChangeListener to be called
*/
// Log.d(TAG, "onBackPressed");
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
// Log.d(TAG, "drawer open, closing");
mDrawerLayout.closeDrawer(mDrawerList);
return;
}
if ( !fCanExit ) {
Toast.makeText(this, R.string.messageExitNotification, Toast.LENGTH_SHORT).show();
fCanExit = true;
Handler h = new Handler();
h.postDelayed(new Runnable() {
@Override
public void run() {
// Log.d(TAG, "Disabling exit flag");
fCanExit = false;
}
}, 2000);
return;
}
super.onBackPressed();
}
private void updateContent(int position) {
if (position != mOldPosition) {
// update the main content by replacing fragments
Fragment fragment;
switch (position) {
default:
case 0:
fragment = StatusFragment.newInstance();
break;
case 1:
fragment = MemoryFragment.newInstance(raApp.raprefs.useOldPre10MemoryLocations());
break;
case 2:
fragment = NotificationsFragment.newInstance();
break;
case 3:
//fragment = HistoryFragment.newInstance();
// TODO check the restoration of the fragment content
if (mHistoryContent != null ) {
fragment = mHistoryContent;
} else {
// mHistoryContent = HistoryGraphFragment.newInstance();
mHistoryContent = HistoryMultipleGraphFragment.newInstance();
fragment = mHistoryContent;
}
break;
case 4:
fragment = ErrorsFragment.newInstance();
break;
case 5:
fragment = DateTimeFragment.newInstance();
break;
}
Log.d(TAG, "UpdateContent: " + position);
FragmentTransaction ft =
getSupportFragmentManager().beginTransaction();
ft.replace(R.id.content_frame, fragment);
ft.commit();
mOldPosition = position;
}
}
public void selectItem(int position) {
// Log.d(TAG, "selectItem: " + position);
updateContent(position);
highlightItem(position);
mDrawerLayout.closeDrawer(mDrawerList);
}
public void highlightItem(int position) {
// Log.d(TAG, "highlightItem: " + position);
// since we are using a header for the list, the first
// item/position in the list is the header. our header is non-selectable
// so in order for us to have the proper item in our list selected, we must
// increase the position by 1. this same logic is applied to the
// DrawerItemClickedListener.onItemClicked
mDrawerList.setItemChecked(position + 1, true);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.global, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// pass the event to ActionBarDrawerToggle, if it returns true,
// then it has handled the app icon touch event
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// handle the rest of the action bar items here
switch (item.getItemId()) {
case R.id.action_settings:
Fragment f = getSupportFragmentManager().findFragmentById(R.id.content_frame);
if (f instanceof StatusFragment) {
// the current fragment is the status fragment
Log.d(TAG, "Status Fragment is current");
((StatusFragment) f).reloadPages();
}
startActivity(new Intent(this, SettingsActivity.class));
// startActivityForResult(new Intent(this, SettingsActivity.class), REQUEST_EXIT);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// @Override
// protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Log.d(TAG, "onActivityResult");
// if (requestCode == REQUEST_EXIT) {
// if (resultCode == RESULT_EXIT) {
// this.finish();
// }
// }
// }
// called whenever we call invalidateOptionsMenu()
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
/*
This function is called after invalidateOptionsMenu is called.
This happens when the Navigation drawer is opened and closed.
*/
boolean open = mDrawerLayout.isDrawerOpen(mDrawerList);
hideMenuItems(menu, open);
return super.onPrepareOptionsMenu(menu);
}
private void hideMenuItems(Menu menu, boolean open) {
// hide the menu item(s) when the drawer is open
// Refresh button on Status page
MenuItem mi = menu.findItem(R.id.action_refresh);
if ( mi != null )
mi.setVisible(!open);
// Add button on Notification page
mi = menu.findItem(R.id.action_add_notification);
if ( mi != null )
mi.setVisible(!open);
// Delete button on Notification page
mi = menu.findItem(R.id.action_delete_notification);
if ( mi != null )
mi.setVisible(!open);
// Delete button on Error page
mi = menu.findItem(R.id.menu_delete);
if ( mi != null )
mi.setVisible(!open);
// hide buttons on History / Chart page
mi = menu.findItem(R.id.action_configure_chart);
if (mi != null)
mi.setVisible(!open);
mi = menu.findItem(R.id.action_refresh_chart);
if (mi != null)
mi.setVisible(!open);
}
private class MyDrawerToggle extends ActionBarDrawerToggle {
public MyDrawerToggle(Activity activity, DrawerLayout drawerLayout,
Toolbar toolbar,
int openDrawerContentDescRes,
int closeDrawerContentDescRes) {
super(activity, drawerLayout, toolbar,
openDrawerContentDescRes, closeDrawerContentDescRes);
}
@Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
// Log.d(TAG, "DrawerClosed");
invalidateOptionsMenu();
if (opened != null && !opened) {
// drawer closed for the first time ever,
// set that it has been closed
opened = true;
raApp.raprefs.set(OPENED_KEY, true);
}
}
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
// getSupportActionBar().setTitle(R.string.app_name);
invalidateOptionsMenu();
}
}
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
@Override
public void onItemClick(
AdapterView<?> parent,
View view,
int position,
long id) {
// Perform action when a drawer item is selected
// Log.d(TAG, "onDrawerItemClick: " + position);
// when we have a list header, it counts as a position in the list
// the first position to be exact. so we have to decrease the
// position by 1 to get the proper item chosen in our list
selectItem(position - 1);
}
}
}
|
curtbinder/AndroidStatus
|
app/src/main/java/info/curtbinder/reefangel/phone/MainActivity.java
|
Java
|
mit
| 17,315 |
package org.workcraft.plugins.policy.commands;
import org.workcraft.commands.AbstractConversionCommand;
import org.workcraft.plugins.petri.Petri;
import org.workcraft.plugins.petri.VisualPetri;
import org.workcraft.plugins.policy.Policy;
import org.workcraft.plugins.policy.PolicyDescriptor;
import org.workcraft.plugins.policy.VisualPolicy;
import org.workcraft.plugins.policy.tools.PetriToPolicyConverter;
import org.workcraft.utils.Hierarchy;
import org.workcraft.utils.DialogUtils;
import org.workcraft.workspace.ModelEntry;
import org.workcraft.workspace.WorkspaceEntry;
import org.workcraft.utils.WorkspaceUtils;
public class PetriToPolicyConversionCommand extends AbstractConversionCommand {
@Override
public String getDisplayName() {
return "Policy Net";
}
@Override
public boolean isApplicableTo(WorkspaceEntry we) {
return WorkspaceUtils.isApplicableExact(we, Petri.class);
}
@Override
public ModelEntry convert(ModelEntry me) {
if (Hierarchy.isHierarchical(me)) {
DialogUtils.showError("Policy Net cannot be derived from a hierarchical Petri Net.");
return null;
}
final VisualPetri src = me.getAs(VisualPetri.class);
final VisualPolicy dst = new VisualPolicy(new Policy());
final PetriToPolicyConverter converter = new PetriToPolicyConverter(src, dst);
return new ModelEntry(new PolicyDescriptor(), converter.getDstModel());
}
}
|
tuura/workcraft
|
workcraft/PolicyPlugin/src/org/workcraft/plugins/policy/commands/PetriToPolicyConversionCommand.java
|
Java
|
mit
| 1,471 |
/*
* See LICENSE file in distribution for copyright and licensing information.
*/
package seph.lang;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* @author <a href="mailto:ola.bini@gmail.com">Ola Bini</a>
*/
public class TextTest {
@Test
public void is_a_seph_object() {
assertTrue("A Text should be a SephObject", new Text("foo") instanceof SephObject);
}
}// TextTest
|
seph-lang/seph
|
src/test/seph/lang/TextTest.java
|
Java
|
mit
| 412 |
//package org.grain.mongo;
//
//import static org.junit.Assert.assertEquals;
//
//import java.util.ArrayList;
//import java.util.List;
//import java.util.UUID;
//
//import org.bson.conversions.Bson;
//import org.junit.BeforeClass;
//import org.junit.Test;
//
//import com.mongodb.client.model.Filters;
//
//public class MongodbManagerTest {
//
// @BeforeClass
// public static void setUpBeforeClass() throws Exception {
// MongodbManager.init("172.27.108.73", 27017, "test", "test", "test", null);
// boolean result = MongodbManager.createCollection("test_table");
// if (!result) {
// System.out.println("创建test_table失败");
// }
// TestMongo testMongo = new TestMongo("111", "name");
// result = MongodbManager.insertOne("test_table", testMongo);
// if (!result) {
// System.out.println("插入TestMongo失败");
// }
// }
//
// @Test
// public void testCreateCollection() {
// boolean result = MongodbManager.createCollection("test_table1");
// assertEquals(true, result);
// }
//
// @Test
// public void testInsertOne() {
// TestMongo testMongo = new TestMongo(UUID.randomUUID().toString(), "name");
// boolean result = MongodbManager.insertOne("test_table", testMongo);
// assertEquals(true, result);
// }
//
// @Test
// public void testInsertMany() {
// TestMongo testMongo = new TestMongo(UUID.randomUUID().toString(), "name");
// TestMongo testMongo1 = new TestMongo(UUID.randomUUID().toString(), "name1");
// List<MongoObj> list = new ArrayList<>();
// list.add(testMongo);
// list.add(testMongo1);
// boolean result = MongodbManager.insertMany("test_table", list);
// assertEquals(true, result);
// }
//
// @Test
// public void testFind() {
// List<TestMongo> list = MongodbManager.find("test_table", null, TestMongo.class, 0, 0);
// assertEquals(true, list.size() > 0);
// }
//
// @Test
// public void testDeleteById() {
// TestMongo testMongo = new TestMongo("222", "name");
// boolean result = MongodbManager.insertOne("test_table", testMongo);
// Bson filter = Filters.and(Filters.eq("id", "222"));
// List<TestMongo> list = MongodbManager.find("test_table", filter, TestMongo.class, 0, 0);
// testMongo = list.get(0);
// result = MongodbManager.deleteById("test_table", testMongo);
// assertEquals(true, result);
// }
//
// @Test
// public void testUpdateById() {
// TestMongo testMongo = new TestMongo("333", "name");
// boolean result = MongodbManager.insertOne("test_table", testMongo);
// Bson filter = Filters.and(Filters.eq("id", "333"));
// List<TestMongo> list = MongodbManager.find("test_table", filter, TestMongo.class, 0, 0);
// testMongo = list.get(0);
// testMongo.setName("name" + UUID.randomUUID().toString());
// result = MongodbManager.updateById("test_table", testMongo);
// assertEquals(true, result);
// }
//
// @Test
// public void testCount() {
// long count = MongodbManager.count("test_table", null);
// assertEquals(true, count > 0);
// }
//
//}
|
dianbaer/grain
|
mongodb/src/test/java/org/grain/mongo/MongodbManagerTest.java
|
Java
|
mit
| 2,935 |
/**
* The MIT License
*
* Copyright (C) 2012 KK.Kon
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.jenkinsci.plugins.job_strongauth_simple;
import hudson.Launcher;
import hudson.Extension;
import hudson.util.FormValidation;
import hudson.model.AbstractBuild;
import hudson.model.BuildListener;
import hudson.model.AbstractProject;
import hudson.model.Cause;
import hudson.model.Result;
import hudson.model.Run;
import hudson.model.User;
import hudson.tasks.Builder;
import hudson.tasks.BuildStepDescriptor;
import hudson.triggers.TimerTrigger;
import hudson.util.RunList;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.QueryParameter;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.logging.Logger;
/**
* Sample {@link Builder}.
*
* <p>
* When the user configures the project and enables this builder,
* {@link DescriptorImpl#newInstance(StaplerRequest)} is invoked
* and a new {@link HelloWorldBuilder} is created. The created
* instance is persisted to the project configuration XML by using
* XStream, so this allows you to use instance fields (like {@link #name})
* to remember the configuration.
*
* <p>
* When a build is performed, the {@link #perform(AbstractBuild, Launcher, BuildListener)}
* method will be invoked.
*
* @author KK.Kon
*/
public class JobStrongAuthSimpleBuilder extends Builder {
// default expireTimeInHours
private static final int DEFAULT_EXPIRE_TIME_IN_HOURS = 16;
private Integer getEffectiveExpireTime( final Integer jobValue, final Integer globalValue )
{
if ( null == jobValue && null == globalValue )
{
return DEFAULT_EXPIRE_TIME_IN_HOURS;
}
Integer value = null;
{
if ( null != globalValue )
{
value = globalValue;
}
if ( null != jobValue )
{
value = jobValue;
}
}
return value;
}
private Set<String> makeAuthUsers( final String jobUsers, final boolean useGlobalUsers, final String globalUsers )
{
if ( null == jobUsers && null == globalUsers )
{
return Collections.emptySet();
}
Set<String> set = new HashSet<String>();
if ( null != jobUsers )
{
final String[] users = jobUsers.split(",");
if ( null != users )
{
for ( final String userRaw : users )
{
if ( null != userRaw )
{
final String userTrimed = userRaw.trim();
if ( null != userTrimed )
{
set.add( userTrimed );
}
}
}
}
}
if ( useGlobalUsers )
{
final String[] users = globalUsers.split(",");
if ( null != users )
{
for ( final String userRaw : users )
{
if ( null != userRaw )
{
final String userTrimed = userRaw.trim();
if ( null != userTrimed )
{
set.add( userTrimed );
}
}
}
}
}
return set;
}
private String getUserNameFromCause( final Cause cause )
{
// UserCause deprecated 1.428
Class<?> clazz = null;
Object retval = null;
{
Method method = null;
try
{
clazz = Class.forName("hudson.model.Cause$UserIdCause");
}
catch ( ClassNotFoundException e )
{
}
if ( null != clazz )
{
try
{
method = cause.getClass().getMethod( "getUserName", new Class<?>[]{} );
}
catch ( SecurityException e)
{
}
catch ( NoSuchMethodException e )
{
}
if ( null != method )
{
try
{
retval = method.invoke( cause, new Object[]{} );
}
catch ( IllegalAccessException e )
{
}
catch ( IllegalArgumentException e )
{
}
catch ( InvocationTargetException e )
{
}
}
}
}
if ( null != retval )
{
if ( retval instanceof String )
{
return (String)retval;
}
}
{
Method method = null;
try
{
clazz = Class.forName("hudson.model.Cause$UserCause");
}
catch ( ClassNotFoundException e )
{
}
if ( null != clazz )
{
try
{
method = cause.getClass().getMethod( "getUserName", new Class<?>[]{} );
}
catch ( SecurityException e)
{
}
catch ( NoSuchMethodException e )
{
}
if ( null != method )
{
try
{
retval = method.invoke( cause, new Object[]{} );
}
catch ( IllegalAccessException e )
{
}
catch ( IllegalArgumentException e )
{
}
catch ( InvocationTargetException e )
{
}
}
}
}
if ( null != retval )
{
if ( retval instanceof String )
{
return (String)retval;
}
}
LOGGER.severe( "unknown cause" );
return null;
}
private Cause getCauseFromRun( final Run run )
{
if ( null == run )
{
return null;
}
Class<?> clazz = null;
{
try
{
clazz = Class.forName("hudson.model.Cause$UserIdCause");
if ( null != clazz )
{
// getCause since 1.362
final Cause cause = run.getCause( clazz );
if ( null != cause )
{
return cause;
}
}
}
catch ( ClassNotFoundException e )
{
}
}
{
try
{
clazz = Class.forName("hudson.model.Cause$UserCause");
if ( null != clazz )
{
final Cause cause = run.getCause( clazz );
if ( null != cause )
{
return cause;
}
}
}
catch ( ClassNotFoundException e )
{
}
}
return null;
}
private final String jobUsers;
private final boolean useGlobalUsers;
private final Integer jobMinAuthUserNum;
private final boolean useJobExpireTime;
private final Integer jobExpireTimeInHours;
//private final boolean buildKickByTimerTrigger;
// Fields in config.jelly must match the parameter names in the "DataBoundConstructor"
@DataBoundConstructor
public JobStrongAuthSimpleBuilder(
final String jobUsers
, final boolean useGlobalUsers
, final Integer jobMinAuthUserNum
, final boolean useJobExpireTime
, final Integer jobExpireTimeInHours
// , final boolean buildKickByTimerTrigger
)
{
this.jobUsers = jobUsers;
this.useGlobalUsers = useGlobalUsers;
this.jobMinAuthUserNum = jobMinAuthUserNum;
this.useJobExpireTime = useJobExpireTime;
this.jobExpireTimeInHours = jobExpireTimeInHours;
//this.buildKickByTimerTrigger = buildKickByTimerTrigger;
}
/**
* We'll use this from the <tt>config.jelly</tt>.
*/
public String getJobUsers() {
return jobUsers;
}
public boolean getUseGlobalUsers() {
return useGlobalUsers;
}
public Integer getJobMinAuthUserNum() {
return jobMinAuthUserNum;
}
public boolean getUseJobExpireTime() {
return useJobExpireTime;
}
public Integer getJobExpireTimeInHours() {
return jobExpireTimeInHours;
}
// public Integer getBuildKickByTimerTrigger() {
// return buildKickByTimerTrigger;
// }
@Override
public boolean perform(AbstractBuild build, Launcher launcher, BuildListener listener) {
// This is where you 'build' the project.
final PrintStream log = listener.getLogger();
{
final String jenkinsVersion = build.getHudsonVersion();
if ( 0 < "1.374".compareTo(jenkinsVersion) )
{
log.println( "jenkins version old. need 1.374 over. Caused by `" + getDescriptor().getDisplayName() + "`" );
build.setResult(Result.FAILURE);
return false;
}
}
{
final Cause cause = getCauseFromRun( build );
if ( null == cause )
{
log.println( "internal error. getCauseFromRun failed. Caused by `" + getDescriptor().getDisplayName() + "`" );
build.setResult(Result.FAILURE);
return false;
}
else
{
final String userName = getUserNameFromCause(cause);
log.println( "userName=" + userName );
if ( null == userName )
{
log.println( "internal error. getUserNameFromCause failed. Caused by `" + getDescriptor().getDisplayName() + "`" );
build.setResult(Result.FAILURE);
return false;
}
else
{
if ( 0 < userName.length() )
{
if ( 0 == "anonymous".compareToIgnoreCase(userName) )
{
build.setResult( Result.ABORTED );
log.println( "reject `anonymous` user's build. Caused by `" + getDescriptor().getDisplayName() + "`" );
return false;
}
}
}
}
}
boolean currentBuildCauseByTimerTrigger = false;
{
final Cause cause = build.getCause(TimerTrigger.TimerTriggerCause.class);
if ( null != cause )
{
if ( cause instanceof TimerTrigger.TimerTriggerCause )
{
final TimerTrigger.TimerTriggerCause causeTimer = (TimerTrigger.TimerTriggerCause)cause;
if ( null != causeTimer )
{
currentBuildCauseByTimerTrigger = true;
}
}
}
}
final Calendar calStart = Calendar.getInstance();
// This also shows how you can consult the global configuration of the builder
final Integer expireTimeInHours = getEffectiveExpireTime( jobExpireTimeInHours, getDescriptor().getExpireTimeInHours() );
LOGGER.finest("expireTimeInHours="+expireTimeInHours+".");
final Set<String> authUsers = makeAuthUsers( this.jobUsers, this.useGlobalUsers, getDescriptor().getUsers() );
LOGGER.finest( "authUsers=" + authUsers );
build.setResult(Result.SUCCESS);
// 1.374 457315f40fb803391f5367d1ac3d50459a6f5020
RunList runList = build.getProject().getBuilds();
LOGGER.finest( "runList=" + runList );
final int currentNumber = build.getNumber();
final Set<String> listUsers = new HashSet<String>();
Calendar calLastBuild = calStart;
for ( final Object r : runList )
{
if ( null == r )
{
continue;
}
if ( r instanceof Run )
{
final Run run = (Run)r;
LOGGER.finest("run: " + run );
/*
// skip current build
if ( currentNumber <= run.getNumber() )
{
log.println( "skip current." );
continue;
}
*/
final Result result = run.getResult();
LOGGER.finest( " result: " + result );
if ( Result.SUCCESS.ordinal == result.ordinal )
{
if ( run.getNumber() < currentNumber )
{
break;
}
}
final Calendar calRun = run.getTimestamp();
if ( this.getUseJobExpireTime() )
{
final long lDistanceInMillis = calLastBuild.getTimeInMillis() - calRun.getTimeInMillis();
final long lDistanceInSeconds = lDistanceInMillis / (1000);
final long lDistanceInMinutes = lDistanceInSeconds / (60);
final long lDistanceInHours = lDistanceInMinutes / (60);
LOGGER.finest( " lDistanceInHours=" + lDistanceInHours );
if ( expireTimeInHours < lDistanceInHours )
{
LOGGER.finest( " expireTimeInHours=" + expireTimeInHours + ",lDistanceInHours=" + lDistanceInHours );
break;
}
}
final Cause cause = getCauseFromRun( run );
if ( null == cause )
{
log.println( "internal error. getCauseFromRun failed. Caused by `" + getDescriptor().getDisplayName() + "`" );
build.setResult(Result.FAILURE);
return false;
}
else
{
final String userName = getUserNameFromCause(cause);
LOGGER.finest( " usercause:" + userName );
if ( null == userName )
{
log.println( "internal error. getUserNameFromCause failed. Caused by `" + getDescriptor().getDisplayName() + "`" );
build.setResult(Result.FAILURE);
return false;
}
else
{
if ( 0 < userName.length() )
{
if ( 0 != "anonymous".compareToIgnoreCase(userName) )
{
listUsers.add( userName );
if ( authUsers.contains( userName ) )
{
calLastBuild = run.getTimestamp();
}
}
}
}
}
}
} // for RunList
LOGGER.finest( "listUsers=" + listUsers );
boolean strongAuth = false;
{
int count = 0;
for ( Iterator<String> it = listUsers.iterator(); it.hasNext(); )
{
final String user = it.next();
if ( null != user )
{
if ( authUsers.contains( user ) )
{
count += 1;
}
}
}
LOGGER.finest( "count=" + count );
if ( null == jobMinAuthUserNum )
{
final int authUserCount = authUsers.size();
LOGGER.finest( "authUserCount=" + authUserCount );
if ( authUserCount <= count )
{
strongAuth = true;
}
}
else
{
LOGGER.finest( "jobMinAuthUserNum=" + jobMinAuthUserNum );
if ( jobMinAuthUserNum.intValue() <= count )
{
strongAuth = true;
}
}
}
if ( strongAuth )
{
boolean doBuild = false;
{
// if ( buildKickByTimerTrigger )
// {
// if ( currentBuildCauseByTimerTrigger )
// {
// // no build
// }
// else
// {
// doBuild = true;
// }
// }
// else
{
doBuild = true;
}
}
if ( doBuild )
{
build.setResult(Result.SUCCESS);
return true;
}
}
log.println( "stop build. number of authed people does not satisfy. Caused by `" + getDescriptor().getDisplayName() + "`" );
build.setResult(Result.NOT_BUILT);
return false;
}
// Overridden for better type safety.
// If your plugin doesn't really define any property on Descriptor,
// you don't have to do this.
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl)super.getDescriptor();
}
/**
* Descriptor for {@link JobStrongAuthSimpleBuilder}. Used as a singleton.
* The class is marked as public so that it can be accessed from views.
*
* <p>
* See <tt>src/main/resources/hudson/plugins/job_strongauth_simple/JobStrongAuthSimpleBuilder/*.jelly</tt>
* for the actual HTML fragment for the configuration screen.
*/
@Extension // This indicates to Jenkins that this is an implementation of an extension point.
public static final class DescriptorImpl extends BuildStepDescriptor<Builder> {
/**
* To persist global configuration information,
* simply store it in a field and call save().
*
* <p>
* If you don't want fields to be persisted, use <tt>transient</tt>.
*/
private Integer expireTimeInHours;
private String users;
public DescriptorImpl() {
load();
{
final Collection<User> userAll = User.getAll();
for ( final User user : userAll )
{
LOGGER.finest( "Id: " + user.getId() );
LOGGER.finest( "DisplayName: " + user.getDisplayName() );
LOGGER.finest( "FullName: " + user.getFullName() );
}
}
}
/**
* Performs on-the-fly validation of the form field 'users'.
*
* @param value
* This parameter receives the value that the user has typed.
* @return
* Indicates the outcome of the validation. This is sent to the browser.
*/
public FormValidation doCheckUsers(@QueryParameter String value)
throws IOException, ServletException {
if ( 0 == value.length() )
{
return FormValidation.ok();
}
final String invalidUser = checkUsers( value );
if ( null != invalidUser )
{
return FormValidation.error("Invalid user: " + invalidUser );
}
return FormValidation.ok();
}
/**
* Performs on-the-fly validation of the form field 'expireTimeInHours'.
*
* @param value
* This parameter receives the value that the user has typed.
* @return
* Indicates the outcome of the validation. This is sent to the browser.
*/
public FormValidation doCheckExpireTimeInHours(@QueryParameter String value)
throws IOException, ServletException {
// if (value.length() == 0)
// return FormValidation.warning("Please set expire time");
if ( 0 == value.length() )
{
return FormValidation.ok();
}
try
{
int intValue = Integer.parseInt(value);
if ( intValue < 0 )
{
return FormValidation.error("Please set positive value");
}
}
catch ( NumberFormatException e )
{
return FormValidation.error("Please set numeric value");
}
return FormValidation.ok();
}
/**
* Performs on-the-fly validation of the form field 'jobExpireTimeInHours'.
*
* @param value
* This parameter receives the value that the user has typed.
* @return
* Indicates the outcome of the validation. This is sent to the browser.
*/
public FormValidation doCheckJobExpireTimeInHours(@QueryParameter String value)
throws IOException, ServletException {
// if (value.length() == 0)
// return FormValidation.warning("Please set expire time");
if ( 0 == value.length() )
{
return FormValidation.ok();
}
try
{
int intValue = Integer.parseInt(value);
if ( intValue < 0 )
{
return FormValidation.error("Please set positive value");
}
}
catch ( NumberFormatException e )
{
return FormValidation.error("Please set numeric value");
}
return FormValidation.ok();
}
/**
* Performs on-the-fly validation of the form field 'jobUsers'.
*
* @param value
* This parameter receives the value that the user has typed.
* @return
* Indicates the outcome of the validation. This is sent to the browser.
*/
public FormValidation doCheckJobUsers(@QueryParameter String value)
throws IOException, ServletException {
if ( 0 == value.length() )
{
return FormValidation.ok();
}
final String invalidUser = checkUsers( value );
if ( null != invalidUser )
{
return FormValidation.error("Invalid user@job: " + invalidUser );
}
return FormValidation.ok();
}
/**
* Performs on-the-fly validation of the form field 'jobMinAuthUserNum'.
*
* @param value
* This parameter receives the value that the user has typed.
* @return
* Indicates the outcome of the validation. This is sent to the browser.
*/
public FormValidation doCheckJobMinAuthUserNum(@QueryParameter String value)
throws IOException, ServletException {
if ( 0 == value.length() )
{
return FormValidation.ok();
}
try
{
int intValue = Integer.parseInt(value);
if ( intValue < 0 )
{
return FormValidation.error("Please set positive value");
}
}
catch ( NumberFormatException e )
{
return FormValidation.error("Please set numeric value");
}
return FormValidation.ok();
}
public boolean isApplicable(Class<? extends AbstractProject> aClass) {
// Indicates that this builder can be used with all kinds of project types
return true;
}
/**
* This human readable name is used in the configuration screen on job.
*/
public String getDisplayName() {
return "StrongAuthSimple for Job";
}
@Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
// To persist global configuration information,
// set that to properties and call save().
//expireTimeInHours = formData.getInt("expireTimeInHours"); // invoke 500 error
if ( formData.containsKey("expireTimeInHours") )
{
final String value = formData.getString("expireTimeInHours");
if ( null != value )
{
if ( 0 < value.length() )
{
try
{
expireTimeInHours = Integer.parseInt(value);
}
catch ( NumberFormatException e )
{
LOGGER.warning( e.toString() );
return false;
}
}
}
}
if ( formData.containsKey("users") )
{
users = formData.getString("users");
}
// ^Can also use req.bindJSON(this, formData);
// (easier when there are many fields; need set* methods for this, like setUseFrench)
save();
return super.configure(req,formData);
}
/**
* This method returns true if the global configuration says we should speak French.
*
* The method name is bit awkward because global.jelly calls this method to determine
* the initial state of the checkbox by the naming convention.
*/
public Integer getExpireTimeInHours() {
return expireTimeInHours;
}
public String getUsers() {
return users;
}
public String checkUsers( final String value )
{
if ( null == value )
{
return null;
}
final Collection<User> userAll = User.getAll();
String invalidUser = null;
if ( null != userAll )
{
final String[] inputUsers = value.split(",");
if ( null == inputUsers )
{
final String userTrimed = value.trim();
boolean validUser = false;
for ( final User user : userAll )
{
if ( null != user )
{
final String dispName = user.getDisplayName();
if ( null != dispName )
{
if ( 0 == userTrimed.compareTo(dispName) )
{
validUser = true;
break;
}
}
}
} // for userAll
if ( validUser )
{
// nothing
}
else
{
invalidUser = userTrimed;
}
}
else
{
for ( final String userRaw : inputUsers )
{
if ( null != userRaw )
{
final String userTrimed = userRaw.trim();
boolean validUser = false;
for ( final User user : userAll )
{
if ( null != user )
{
final String dispName = user.getDisplayName();
if ( null != dispName )
{
if ( 0 == userTrimed.compareTo(dispName) )
{
validUser = true;
break;
}
}
}
} // for userAll
if ( validUser )
{
// nothing
}
else
{
invalidUser = userTrimed;
}
if ( null != invalidUser )
{
break;
}
}
}
}
}
return invalidUser;
}
}
private static final Logger LOGGER = Logger.getLogger(JobStrongAuthSimpleBuilder.class.getName());
}
|
kkkon/job-strongauth-simple-plugin
|
src/main/java/org/jenkinsci/plugins/job_strongauth_simple/JobStrongAuthSimpleBuilder.java
|
Java
|
mit
| 31,334 |
/*
* The MIT License
*
* Copyright 2016 Matthias.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package de.lutana.easyflickrbackup;
import com.flickr4java.flickr.photos.Size;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class ImageSizes {
private Map<Integer,String> suffix;
public ImageSizes() {
suffix = new HashMap<>();
suffix.put(Size.SQUARE, "_s");
suffix.put(Size.SQUARE_LARGE, "_q");
suffix.put(Size.THUMB, "_t");
suffix.put(Size.SMALL, "_m");
suffix.put(Size.SMALL_320, "_n");
suffix.put(Size.MEDIUM, "");
suffix.put(Size.MEDIUM_640, "_z");
suffix.put(Size.MEDIUM_800, "_c");
suffix.put(Size.LARGE, "_b");
suffix.put(Size.LARGE_1600, "_h");
suffix.put(Size.LARGE_2048, "_k");
suffix.put(Size.ORIGINAL, "_o");
}
public String getSuffix(int size) {
try {
return suffix.get(size);
} catch(Exception e) {
return null;
}
}
}
|
lutana-de/easyflickrbackup
|
src/main/java/de/lutana/easyflickrbackup/ImageSizes.java
|
Java
|
mit
| 2,063 |
/**
* Copyright (c) 2011 Prashant Dighe
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
package com.example.demo.model.impl;
import java.util.HashMap;
import java.util.Map;
import com.example.demo.model.RegisteredDriver;
/**
*
* @author Prashant Dighe
*
*/
public class RegisteredDriverImpl implements RegisteredDriver {
public RegisteredDriverImpl() {}
public RegisteredDriverImpl(Map<String, Object> map) {
_name = (String)map.get("name");
_age = (Integer)map.get("age");
}
@Override
public String getName() {
return _name;
}
@Override
public void setName(String name) {
_name = name;
}
@Override
public int getAge() {
return _age;
}
@Override
public void setAge(int age) {
_age = age;
}
public Map<String, Object> toMap() {
Map<String, Object> map = new HashMap<String, Object>();
map.put("name", _name);
map.put("age", _age);
return map;
}
private String _name = null;
private int _age = 0;
private static final long serialVersionUID = 1L;
}
|
pdd/mongoj
|
test/src/java/custom/com/example/demo/model/impl/RegisteredDriverImpl.java
|
Java
|
mit
| 2,066 |
package nl.astraeus.jdbc;
import org.junit.Assert;
import org.junit.Test;
/**
* User: rnentjes
* Date: 4/13/12
* Time: 10:55 PM
*/
public class JdbcStatisticTest {
@Test
public void test() {
Assert.assertTrue(true);
}
}
|
rnentjes/Simple-jdbc-statistics
|
test/nl/astraeus/jdbc/JdbcStatisticTest.java
|
Java
|
mit
| 246 |
package com.mdg.droiders.samagra.shush;
import android.Manifest;
import android.app.NotificationManager;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesNotAvailableException;
import com.google.android.gms.common.GooglePlayServicesRepairableException;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.PlaceBuffer;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.location.places.ui.PlacePicker;
import com.mdg.droiders.samagra.shush.data.PlacesContract;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LoaderManager.LoaderCallbacks<Cursor>{
//constants
private static final String LOG_TAG = "MainActivity";
private static final int PERMISSIONS_REQUEST_FINE_LOCATION = 111;
private static final int PLACE_PICKER_REQUEST = 1;
//member variables
private PlaceListAdapter mAdapter;
private RecyclerView mRecyclerView;
private Button addPlaceButton;
private GoogleApiClient mClient;
private Geofencing mGeofencing;
private boolean mIsEnabled;
private CheckBox mRingerPermissionCheckBox;
/**
* Called when the activity is starting.
*
* @param savedInstanceState Bundle that contains the data provided to onSavedInstanceState
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = (RecyclerView) findViewById(R.id.places_list_recycler_view);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new PlaceListAdapter(this,null);
mRecyclerView.setAdapter(mAdapter);
mRingerPermissionCheckBox = (CheckBox) findViewById(R.id.ringer_permissions_checkbox);
mRingerPermissionCheckBox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onRingerPermissionsClicked();
}
});
Switch onOffSwitch = (Switch) findViewById(R.id.enable_switch);
mIsEnabled = getPreferences(MODE_PRIVATE).getBoolean(getString(R.string.setting_enabled),false);
onOffSwitch.setChecked(mIsEnabled);
onOffSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putBoolean(getString(R.string.setting_enabled),isChecked);
editor.commit();
if (isChecked) mGeofencing.registerAllGeofences();
else mGeofencing.unRegisterAllGeofences();
}
});
addPlaceButton = (Button) findViewById(R.id.add_location_button);
addPlaceButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
onAddPlaceButtonClicked();
}
});
mClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.addApi(Places.GEO_DATA_API)
.enableAutoManage(this,this)
.build();
mGeofencing = new Geofencing(mClient,this);
}
/**
* Button click event handler for the add place button.
*/
private void onAddPlaceButtonClicked() {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)!=PackageManager.PERMISSION_GRANTED){
Toast.makeText(this, getString(R.string.need_location_permission_message), Toast.LENGTH_SHORT).show();
return;
}
Toast.makeText(this, getString(R.string.location_permissions_granted_message), Toast.LENGTH_SHORT).show();
try {
PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
Intent placePickerIntent = builder.build(this);
startActivityForResult(placePickerIntent,PLACE_PICKER_REQUEST);
} catch (GooglePlayServicesRepairableException e) {
e.printStackTrace();
} catch (GooglePlayServicesNotAvailableException e) {
e.printStackTrace();
}
}
/***
* Called when the Place Picker Activity returns back with a selected place (or after canceling)
*
* @param requestCode The request code passed when calling startActivityForResult
* @param resultCode The result code specified by the second activity
* @param data The Intent that carries the result data.
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode==PLACE_PICKER_REQUEST&&resultCode==RESULT_OK){
Place place = PlacePicker.getPlace(this,data);
if (place==null){
Log.i(LOG_TAG,"No place selected");
return;
}
String placeName = place.getName().toString();
String placeAddress = place.getAddress().toString();
String placeId = place.getId();
ContentValues values = new ContentValues();
values.put(PlacesContract.PlaceEntry.COLUMN_PLACE_ID,placeId);
getContentResolver().insert(PlacesContract.PlaceEntry.CONTENT_URI,values);
refreshPlacesData();
}
}
@Override
protected void onResume() {
super.onResume();
//initialise location permissions checkbox
CheckBox locationPermissionsCheckBox = (CheckBox) findViewById(R.id.location_permission_checkbox);
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
locationPermissionsCheckBox.setChecked(false);
}
else {
locationPermissionsCheckBox.setChecked(true);
locationPermissionsCheckBox.setEnabled(false);
}
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT>=24 && !notificationManager.isNotificationPolicyAccessGranted()){
mRingerPermissionCheckBox.setChecked(false);
}
else {
mRingerPermissionCheckBox.setChecked(true);
mRingerPermissionCheckBox.setEnabled(false);
}
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return null;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
/**
* Called when the google API client is successfully connected.
* @param bundle Bundle of data provided to the clients by google play services.
*/
@Override
public void onConnected(@Nullable Bundle bundle) {
Log.i(LOG_TAG,"Api connection successful");
Toast.makeText(this, "onConnected", Toast.LENGTH_SHORT).show();
refreshPlacesData();
}
/**
* Called when the google API client is suspended
* @param cause The reason for the disconnection. Defined by the constant CAUSE_*.
*/
@Override
public void onConnectionSuspended(int cause) {
Log.i(LOG_TAG,"API Client connection suspended.");
}
/**
* Called when the google API client failed to connect to the PlayServices.
* @param connectionResult A coonectionResult that can be used to solve the error.
*/
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Log.i(LOG_TAG,"API Connection client suspended.");
Toast.makeText(this, "onConectionFailed", Toast.LENGTH_SHORT).show();
}
public void refreshPlacesData(){
Uri uri = PlacesContract.PlaceEntry.CONTENT_URI;
Cursor dataCursor = getContentResolver().query(uri,
null,
null,
null,null,null);
if (dataCursor==null||dataCursor.getCount()==0) return;
List<String> placeIds = new ArrayList<String>();
while (dataCursor.moveToNext()){
placeIds.add(dataCursor.getString(dataCursor.getColumnIndex(PlacesContract.PlaceEntry.COLUMN_PLACE_ID)));
}
PendingResult<PlaceBuffer> placeBufferPendingResult = Places.GeoDataApi.getPlaceById(mClient,
placeIds.toArray(new String[placeIds.size()]));
placeBufferPendingResult.setResultCallback(new ResultCallback<PlaceBuffer>() {
@Override
public void onResult(@NonNull PlaceBuffer places) {
mAdapter.swapPlaces(places);
mGeofencing.updateGeofencesList(places);
if (mIsEnabled) mGeofencing.registerAllGeofences();
}
});
}
private void onRingerPermissionsClicked(){
Intent intent = null;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
intent = new Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
}
startActivity(intent);
}
public void onLocationPermissionClicked (View view){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_FINE_LOCATION);
}
}
|
samagra14/Shush
|
app/src/main/java/com/mdg/droiders/samagra/shush/MainActivity.java
|
Java
|
mit
| 10,861 |
package jenkins.plugins.http_request;
import static com.google.common.base.Preconditions.checkArgument;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import javax.annotation.Nonnull;
import org.kohsuke.stapler.AncestorInPath;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
import org.kohsuke.stapler.QueryParameter;
import com.cloudbees.plugins.credentials.common.AbstractIdCredentialsListBoxModel;
import com.cloudbees.plugins.credentials.common.StandardCredentials;
import com.cloudbees.plugins.credentials.common.StandardListBoxModel;
import com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials;
import com.cloudbees.plugins.credentials.domains.URIRequirementBuilder;
import com.google.common.base.Strings;
import com.google.common.collect.Range;
import com.google.common.collect.Ranges;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.init.InitMilestone;
import hudson.init.Initializer;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.Item;
import hudson.model.Items;
import hudson.model.TaskListener;
import hudson.security.ACL;
import hudson.tasks.BuildStepDescriptor;
import hudson.tasks.Builder;
import hudson.util.FormValidation;
import hudson.util.ListBoxModel;
import hudson.util.ListBoxModel.Option;
import jenkins.plugins.http_request.auth.BasicDigestAuthentication;
import jenkins.plugins.http_request.auth.FormAuthentication;
import jenkins.plugins.http_request.util.HttpClientUtil;
import jenkins.plugins.http_request.util.HttpRequestNameValuePair;
/**
* @author Janario Oliveira
*/
public class HttpRequest extends Builder {
private @Nonnull String url;
private Boolean ignoreSslErrors = DescriptorImpl.ignoreSslErrors;
private HttpMode httpMode = DescriptorImpl.httpMode;
private String httpProxy = DescriptorImpl.httpProxy;
private Boolean passBuildParameters = DescriptorImpl.passBuildParameters;
private String validResponseCodes = DescriptorImpl.validResponseCodes;
private String validResponseContent = DescriptorImpl.validResponseContent;
private MimeType acceptType = DescriptorImpl.acceptType;
private MimeType contentType = DescriptorImpl.contentType;
private String outputFile = DescriptorImpl.outputFile;
private Integer timeout = DescriptorImpl.timeout;
private Boolean consoleLogResponseBody = DescriptorImpl.consoleLogResponseBody;
private Boolean quiet = DescriptorImpl.quiet;
private String authentication = DescriptorImpl.authentication;
private String requestBody = DescriptorImpl.requestBody;
private List<HttpRequestNameValuePair> customHeaders = DescriptorImpl.customHeaders;
@DataBoundConstructor
public HttpRequest(@Nonnull String url) {
this.url = url;
}
@Nonnull
public String getUrl() {
return url;
}
public Boolean getIgnoreSslErrors() {
return ignoreSslErrors;
}
@DataBoundSetter
public void setIgnoreSslErrors(Boolean ignoreSslErrors) {
this.ignoreSslErrors = ignoreSslErrors;
}
public HttpMode getHttpMode() {
return httpMode;
}
@DataBoundSetter
public void setHttpMode(HttpMode httpMode) {
this.httpMode = httpMode;
}
public String getHttpProxy() {
return httpProxy;
}
@DataBoundSetter
public void setHttpProxy(String httpProxy) {
this.httpProxy = httpProxy;
}
public Boolean getPassBuildParameters() {
return passBuildParameters;
}
@DataBoundSetter
public void setPassBuildParameters(Boolean passBuildParameters) {
this.passBuildParameters = passBuildParameters;
}
@Nonnull
public String getValidResponseCodes() {
return validResponseCodes;
}
@DataBoundSetter
public void setValidResponseCodes(String validResponseCodes) {
this.validResponseCodes = validResponseCodes;
}
public String getValidResponseContent() {
return validResponseContent;
}
@DataBoundSetter
public void setValidResponseContent(String validResponseContent) {
this.validResponseContent = validResponseContent;
}
public MimeType getAcceptType() {
return acceptType;
}
@DataBoundSetter
public void setAcceptType(MimeType acceptType) {
this.acceptType = acceptType;
}
public MimeType getContentType() {
return contentType;
}
@DataBoundSetter
public void setContentType(MimeType contentType) {
this.contentType = contentType;
}
public String getOutputFile() {
return outputFile;
}
@DataBoundSetter
public void setOutputFile(String outputFile) {
this.outputFile = outputFile;
}
public Integer getTimeout() {
return timeout;
}
@DataBoundSetter
public void setTimeout(Integer timeout) {
this.timeout = timeout;
}
public Boolean getConsoleLogResponseBody() {
return consoleLogResponseBody;
}
@DataBoundSetter
public void setConsoleLogResponseBody(Boolean consoleLogResponseBody) {
this.consoleLogResponseBody = consoleLogResponseBody;
}
public Boolean getQuiet() {
return quiet;
}
@DataBoundSetter
public void setQuiet(Boolean quiet) {
this.quiet = quiet;
}
public String getAuthentication() {
return authentication;
}
@DataBoundSetter
public void setAuthentication(String authentication) {
this.authentication = authentication;
}
public String getRequestBody() {
return requestBody;
}
@DataBoundSetter
public void setRequestBody(String requestBody) {
this.requestBody = requestBody;
}
public List<HttpRequestNameValuePair> getCustomHeaders() {
return customHeaders;
}
@DataBoundSetter
public void setCustomHeaders(List<HttpRequestNameValuePair> customHeaders) {
this.customHeaders = customHeaders;
}
@Initializer(before = InitMilestone.PLUGINS_STARTED)
public static void xStreamCompatibility() {
Items.XSTREAM2.aliasField("logResponseBody", HttpRequest.class, "consoleLogResponseBody");
Items.XSTREAM2.aliasField("consoleLogResponseBody", HttpRequest.class, "consoleLogResponseBody");
Items.XSTREAM2.alias("pair", HttpRequestNameValuePair.class);
}
protected Object readResolve() {
if (customHeaders == null) {
customHeaders = DescriptorImpl.customHeaders;
}
if (validResponseCodes == null || validResponseCodes.trim().isEmpty()) {
validResponseCodes = DescriptorImpl.validResponseCodes;
}
if (ignoreSslErrors == null) {
//default for new job false(DescriptorImpl.ignoreSslErrors) for old ones true to keep same behavior
ignoreSslErrors = true;
}
if (quiet == null) {
quiet = false;
}
return this;
}
private List<HttpRequestNameValuePair> createParams(EnvVars envVars, AbstractBuild<?, ?> build, TaskListener listener) throws IOException {
Map<String, String> buildVariables = build.getBuildVariables();
if (buildVariables.isEmpty()) {
return Collections.emptyList();
}
PrintStream logger = listener.getLogger();
logger.println("Parameters: ");
List<HttpRequestNameValuePair> l = new ArrayList<>();
for (Map.Entry<String, String> entry : buildVariables.entrySet()) {
String value = envVars.expand(entry.getValue());
logger.println(" " + entry.getKey() + " = " + value);
l.add(new HttpRequestNameValuePair(entry.getKey(), value));
}
return l;
}
String resolveUrl(EnvVars envVars,
AbstractBuild<?, ?> build, TaskListener listener) throws IOException {
String url = envVars.expand(getUrl());
if (Boolean.TRUE.equals(getPassBuildParameters()) && getHttpMode() == HttpMode.GET) {
List<HttpRequestNameValuePair> params = createParams(envVars, build, listener);
if (!params.isEmpty()) {
url = HttpClientUtil.appendParamsToUrl(url, params);
}
}
return url;
}
List<HttpRequestNameValuePair> resolveHeaders(EnvVars envVars) {
final List<HttpRequestNameValuePair> headers = new ArrayList<>();
if (contentType != null && contentType != MimeType.NOT_SET) {
headers.add(new HttpRequestNameValuePair("Content-type", contentType.getContentType().toString()));
}
if (acceptType != null && acceptType != MimeType.NOT_SET) {
headers.add(new HttpRequestNameValuePair("Accept", acceptType.getValue()));
}
for (HttpRequestNameValuePair header : customHeaders) {
String headerName = envVars.expand(header.getName());
String headerValue = envVars.expand(header.getValue());
boolean maskValue = headerName.equalsIgnoreCase("Authorization") ||
header.getMaskValue();
headers.add(new HttpRequestNameValuePair(headerName, headerValue, maskValue));
}
return headers;
}
String resolveBody(EnvVars envVars,
AbstractBuild<?, ?> build, TaskListener listener) throws IOException {
String body = envVars.expand(getRequestBody());
if (Strings.isNullOrEmpty(body) && Boolean.TRUE.equals(getPassBuildParameters())) {
List<HttpRequestNameValuePair> params = createParams(envVars, build, listener);
if (!params.isEmpty()) {
body = HttpClientUtil.paramsToString(params);
}
}
return body;
}
FilePath resolveOutputFile(EnvVars envVars, AbstractBuild<?,?> build) {
if (outputFile == null || outputFile.trim().isEmpty()) {
return null;
}
String filePath = envVars.expand(outputFile);
FilePath workspace = build.getWorkspace();
if (workspace == null) {
throw new IllegalStateException("Could not find workspace to save file outputFile: " + outputFile);
}
return workspace.child(filePath);
}
@Override
public boolean perform(AbstractBuild<?,?> build, Launcher launcher, BuildListener listener)
throws InterruptedException, IOException
{
EnvVars envVars = build.getEnvironment(listener);
for (Map.Entry<String, String> e : build.getBuildVariables().entrySet()) {
envVars.put(e.getKey(), e.getValue());
}
HttpRequestExecution exec = HttpRequestExecution.from(this, envVars, build,
this.getQuiet() ? TaskListener.NULL : listener);
launcher.getChannel().call(exec);
return true;
}
@Extension
public static final class DescriptorImpl extends BuildStepDescriptor<Builder> {
public static final boolean ignoreSslErrors = false;
public static final HttpMode httpMode = HttpMode.GET;
public static final String httpProxy = "";
public static final Boolean passBuildParameters = false;
public static final String validResponseCodes = "100:399";
public static final String validResponseContent = "";
public static final MimeType acceptType = MimeType.NOT_SET;
public static final MimeType contentType = MimeType.NOT_SET;
public static final String outputFile = "";
public static final int timeout = 0;
public static final Boolean consoleLogResponseBody = false;
public static final Boolean quiet = false;
public static final String authentication = "";
public static final String requestBody = "";
public static final List <HttpRequestNameValuePair> customHeaders = Collections.<HttpRequestNameValuePair>emptyList();
public DescriptorImpl() {
load();
}
@SuppressWarnings("rawtypes")
@Override
public boolean isApplicable(Class<? extends AbstractProject> aClass) {
return true;
}
@Override
public String getDisplayName() {
return "HTTP Request";
}
public ListBoxModel doFillHttpModeItems() {
return HttpMode.getFillItems();
}
public ListBoxModel doFillAcceptTypeItems() {
return MimeType.getContentTypeFillItems();
}
public ListBoxModel doFillContentTypeItems() {
return MimeType.getContentTypeFillItems();
}
public ListBoxModel doFillAuthenticationItems(@AncestorInPath Item project,
@QueryParameter String url) {
return fillAuthenticationItems(project, url);
}
public static ListBoxModel fillAuthenticationItems(Item project, String url) {
if (project == null || !project.hasPermission(Item.CONFIGURE)) {
return new StandardListBoxModel();
}
List<Option> options = new ArrayList<>();
for (BasicDigestAuthentication basic : HttpRequestGlobalConfig.get().getBasicDigestAuthentications()) {
options.add(new Option("(deprecated - use Jenkins Credentials) " +
basic.getKeyName(), basic.getKeyName()));
}
for (FormAuthentication formAuthentication : HttpRequestGlobalConfig.get().getFormAuthentications()) {
options.add(new Option(formAuthentication.getKeyName()));
}
AbstractIdCredentialsListBoxModel<StandardListBoxModel, StandardCredentials> items = new StandardListBoxModel()
.includeEmptyValue()
.includeAs(ACL.SYSTEM,
project, StandardUsernamePasswordCredentials.class,
URIRequirementBuilder.fromUri(url).build());
items.addMissing(options);
return items;
}
public static List<Range<Integer>> parseToRange(String value) {
List<Range<Integer>> validRanges = new ArrayList<Range<Integer>>();
String[] codes = value.split(",");
for (String code : codes) {
String[] fromTo = code.trim().split(":");
checkArgument(fromTo.length <= 2, "Code %s should be an interval from:to or a single value", code);
Integer from;
try {
from = Integer.parseInt(fromTo[0]);
} catch (NumberFormatException nfe) {
throw new IllegalArgumentException("Invalid number "+fromTo[0]);
}
Integer to = from;
if (fromTo.length != 1) {
try {
to = Integer.parseInt(fromTo[1]);
} catch (NumberFormatException nfe) {
throw new IllegalArgumentException("Invalid number "+fromTo[1]);
}
}
checkArgument(from <= to, "Interval %s should be FROM less than TO", code);
validRanges.add(Ranges.closed(from, to));
}
return validRanges;
}
public FormValidation doCheckValidResponseCodes(@QueryParameter String value) {
return checkValidResponseCodes(value);
}
public static FormValidation checkValidResponseCodes(String value) {
if (value == null || value.trim().isEmpty()) {
return FormValidation.ok();
}
try {
parseToRange(value);
} catch (IllegalArgumentException iae) {
return FormValidation.error("Response codes expected is wrong. "+iae.getMessage());
}
return FormValidation.ok();
}
}
}
|
martinda/http-request-plugin
|
src/main/java/jenkins/plugins/http_request/HttpRequest.java
|
Java
|
mit
| 15,118 |
package by.bsuir.verkpavel.adb.data;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import by.bsuir.verkpavel.adb.data.entity.Account;
import by.bsuir.verkpavel.adb.data.entity.Client;
import by.bsuir.verkpavel.adb.data.entity.Deposit;
import by.bsuir.verkpavel.adb.data.entity.TransactionsInfo;
//MAYBE Remove this facade and use separate class or add three getInstance methods
public class DataProvider {
private static DataProvider instance;
private Connection connection;
private ClientProvider clientProvider;
private DepositProvider depositProvider;
private AccountProvider accountProvider;
private static final String DB_PATH = "jdbc:mysql://localhost:3306/bank_users?useUnicode=true&characterEncoding=utf8";
private static final String DB_USER_NAME = "root";
private static final String DB_PASSWORD = "123456";
private DataProvider() {
try {
Class.forName("com.mysql.jdbc.Driver");
this.connection = DriverManager.getConnection(DB_PATH, DB_USER_NAME, DB_PASSWORD);
this.clientProvider = ClientProvider.getInstance(connection);
this.depositProvider = DepositProvider.getInstance(connection);
this.accountProvider = AccountProvider.getInstance(connection);
} catch (ClassNotFoundException e) {
System.out.println("DB driver not found");
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
};
public static DataProvider getInstance() {
if (instance == null) {
instance = new DataProvider();
}
return instance;
}
public ArrayList<String> getCityList() {
return clientProvider.getCityList();
}
public ArrayList<String> getFamilyStatuses() {
return clientProvider.getFamilyStatuses();
}
public ArrayList<String> getNationalitys() {
return clientProvider.getNationalitys();
}
public ArrayList<String> getDisabilitys() {
return clientProvider.getDisabilitys();
}
public String saveClient(Client client) {
return clientProvider.saveClient(client);
}
public String updateClient(Client client) {
return clientProvider.updateClient(client);
}
public ArrayList<Client> getAllClients() {
return clientProvider.getAllClients();
}
public void deleteClient(Client client) {
clientProvider.deleteClient(client);
}
public ArrayList<String> getUserFullNames() {
return clientProvider.getUserFullNames();
}
public ArrayList<String> getCurrency() {
return depositProvider.getCurrency();
}
public ArrayList<String> getDepositTypeList() {
return depositProvider.getDepositTypeList();
}
public String saveDeposit(Deposit deposit) {
return depositProvider.saveDeposit(deposit);
}
public ArrayList<Deposit> getAllDeposits() {
return depositProvider.getAllDeposits();
}
public void updateDepositEndDate(Deposit deposit, String newDate) {
depositProvider.updateDepositEndDate(deposit, newDate);
}
public ArrayList<Account> getAllAccounts() {
return accountProvider.getAllAccounts();
}
public void addTransaction(Account from, Account to, double sum, int currency) {
try {
accountProvider.addTransaction(from, to, sum, currency);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void addMonoTransaction(Account from, Account to, double sum, int currency) {
try {
accountProvider.addMonoTransaction(from, to, sum, currency);
} catch (SQLException e) {
e.printStackTrace();
}
}
public Account[] getAccountByDeposit(Deposit deposit) {
return accountProvider.getAccountByDeposit(deposit);
}
public Account getCashBoxAccount() {
return accountProvider.getCashBoxAccount();
}
public void createAccountsByDeposit(Deposit deposit) {
accountProvider.createAccountByDeposit(deposit);
}
public Account getFDBAccount() {
return accountProvider.getFDBAccount();
}
public ArrayList<TransactionsInfo> getTransatcionsByAccount(Account account) {
return accountProvider.getTransactionByAccount(account);
}
public ArrayList<Deposit> getAllActiveDeposits() {
return depositProvider.getAllActiveDeposits();
}
public void disableDeposit(Deposit deposit) {
depositProvider.disableDeposit(deposit);
}
}
|
VerkhovtsovPavel/BSUIR_Labs
|
Labs/ADB/ADB-2/src/by/bsuir/verkpavel/adb/data/DataProvider.java
|
Java
|
mit
| 4,665 |
package com.lfk.justweengine.Utils.tools;
import android.content.Context;
import android.content.SharedPreferences;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 简化Sp存储的工具类
*
* @author liufengkai
*/
public class SpUtils {
public SpUtils() {
/* cannot be instantiated */
throw new UnsupportedOperationException("cannot be instantiated");
}
/**
* Sp文件名
*/
public static final String FILE_NAME = "share_data";
/**
* 保存数据的方法,添加具体数据类型
*
* @param context
* @param key
* @param object
*/
public static void put(Context context, String key, Object object) {
SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
// 判断数据类型
if (object instanceof String) {
editor.putString(key, (String) object);
} else if (object instanceof Integer) {
editor.putInt(key, (Integer) object);
} else if (object instanceof Boolean) {
editor.putBoolean(key, (Boolean) object);
} else if (object instanceof Float) {
editor.putFloat(key, (Float) object);
} else if (object instanceof Long) {
editor.putLong(key, (Long) object);
} else {
editor.putString(key, object.toString());
}
SharedPreferencesCompat.apply(editor);
}
/**
* 获取保存数据的方法,添加具体数据类型
*
* @param context
* @param key
* @param defaultObject
* @return object
*/
public static Object get(Context context, String key, Object defaultObject) {
SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
if (defaultObject instanceof String) {
return sp.getString(key, (String) defaultObject);
} else if (defaultObject instanceof Integer) {
return sp.getInt(key, (Integer) defaultObject);
} else if (defaultObject instanceof Boolean) {
return sp.getBoolean(key, (Boolean) defaultObject);
} else if (defaultObject instanceof Float) {
return sp.getFloat(key, (Float) defaultObject);
} else if (defaultObject instanceof Long) {
return sp.getLong(key, (Long) defaultObject);
}
return null;
}
/**
* 存放数组
*
* @param context
* @param list
* @param key
*/
public static void putList(Context context, List list, String key) {
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < list.size(); i++) {
JSONObject object = new JSONObject();
try {
object.put(i + "", list.get(i));
jsonArray.put(object);
} catch (JSONException e) {
e.printStackTrace();
}
}
put(context, key, jsonArray.toString());
}
/**
* 获取数组
*
* @param context
* @param key
* @return list
*/
public static List getList(Context context, String key) {
List list = new ArrayList();
try {
JSONArray jsonArray = new JSONArray((String) get(context, key, ""));
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
list.add(i, object.getString(i + ""));
}
} catch (JSONException e) {
e.printStackTrace();
}
return list;
}
/**
* 存入哈希表
*
* @param context
* @param map
* @param key
*/
public static void putMap(Context context, Map<?, ?> map, String key) {
JSONArray jsonArray = new JSONArray();
Set set = map.entrySet();
Iterator iterator = set.iterator();
for (int i = 0; i < map.size(); i++) {
Map.Entry mapEntry = (Map.Entry) iterator.next();
try {
JSONObject object = new JSONObject();
object.put("key", mapEntry.getKey());
object.put("value", mapEntry.getValue());
jsonArray.put(object);
} catch (JSONException e) {
e.printStackTrace();
}
}
put(context, key, jsonArray.toString());
}
/**
* 读取哈希表
*
* @param context
* @param key
* @return map
*/
public static Map getMap(Context context, String key) {
Map map = new HashMap();
try {
JSONArray jsonArray = new JSONArray((String) get(context, key, ""));
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject object = jsonArray.getJSONObject(i);
map.put(object.getString("key"), object.getString("value"));
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return map;
}
/**
* 移除某个key值已经对应的值
*
* @param context
* @param key
*/
public static void remove(Context context, String key) {
SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.remove(key);
SharedPreferencesCompat.apply(editor);
}
/**
* 清除所有数据
*
* @param context
*/
public static void clear(Context context) {
SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.clear();
SharedPreferencesCompat.apply(editor);
}
/**
* 查询某个key是否存在
*
* @param context
* @param key
* @return
*/
public static boolean contains(Context context, String key) {
SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
return sp.contains(key);
}
/**
* 返回所有的键值对
*
* @param context
* @return map
*/
public static Map<String, ?> getAll(Context context) {
SharedPreferences sp = context.getSharedPreferences(FILE_NAME,
Context.MODE_PRIVATE);
return sp.getAll();
}
/**
* 解决SharedPreferencesCompat.apply方法的兼容类
*
* @author liufengkai
*/
private static class SharedPreferencesCompat {
private static final Method sApplyMethod = findApplyMethod();
/**
* 反射查找apply的方法
*
* @return method
*/
@SuppressWarnings({"unchecked", "rawtypes"})
private static Method findApplyMethod() {
try {
Class clz = SharedPreferences.Editor.class;
return clz.getMethod("apply");
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
return null;
}
/**
* 如果找到则使用apply执行,否则使用commit
*
* @param editor
*/
public static void apply(SharedPreferences.Editor editor) {
try {
if (sApplyMethod != null) {
sApplyMethod.invoke(editor);
return;
}
} catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
editor.commit();
}
}
}
|
Sonnydch/dzwfinal
|
AndroidFinal/engine/src/main/java/com/lfk/justweengine/Utils/tools/SpUtils.java
|
Java
|
mit
| 8,126 |
import processing.core.*;
import processing.data.*;
import processing.event.*;
import processing.opengl.*;
import ddf.minim.spi.*;
import ddf.minim.signals.*;
import ddf.minim.*;
import ddf.minim.analysis.*;
import ddf.minim.ugens.*;
import ddf.minim.effects.*;
import codeanticode.syphon.*;
import java.util.HashMap;
import java.util.ArrayList;
import java.io.File;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
public class ANTES01 extends PApplet {
//
//////////
//
// WRAP
// Syphon/minim/fun000
//
// V.00 paraelfestival"ANTES"
// feelGoodSoftwareporGuillermoGonz\u00e1lezIrigoyen
//
//////////
//
//VARIABLES DE CONFIGURACI\u00d3N
//Tama\u00f1o de la pantalla , proporciones y tweak
boolean pCompleta = false; //salidas a proyector 1024X768
boolean pCambiable= true;
int pPantalla = 4;
int pP,pW,pH;
//Syphon
SyphonServer server;
String nombreServer = "ANTES01";
//Audio
Minim minim;
AudioInput in0;
//
// ...
//LINEA
Linea lin,lin1;
int[] coloresAntes = { 0xff2693FF, 0xffEF3B63 , 0xffFFFFFB, 0xff000000};
int numColor = 1;
boolean hay;
int alfa = 255;
boolean moverL = false;
boolean moverH = false;
int xIL = 0;
int yIL = 10;
int intA = 50;
int sepLR = 5;
int anchoL = 0;
int anchoR = 0;
int anchoS = 1;
int distMov = 1;
//FONDO
boolean fondo = true;
boolean textura = true;
boolean sinCuadricula = true;
int R = 85;
int G = 85;
int B = 85;
int A = 10;
//CONTROLES
boolean sumar = true;
int paso = 2;
//##SETUP##
//
public void setup()
{
//CANVAS
pP = (pCompleta == true)? 1 : pPantalla;
size(displayWidth/pP, displayHeight/pP, P3D);
pW=width;pH=height;
frame.setResizable(pCambiable);
//SYPHON SERVER
server = new SyphonServer(this, nombreServer);
//AUDIO
minim = new Minim(this);
in0 = minim.getLineIn();
//
// ...
yIL = height/2;
lin = new Linea(xIL, yIL, coloresAntes[numColor], alfa);
lin1 = new Linea(xIL, yIL-50, coloresAntes[numColor+1], alfa);
}
//##DRAW##
//
public void draw()
{
pW=width;
pH=height;
if(fondo){ background(coloresAntes[2]); }
int normi;
pushMatrix();
for(int i = 0; i < pW; i++)
{
normi=i;
if(i>1024||i==1024){ normi = PApplet.parseInt(norm(i,0,1024)); }
lin.conectarHorizontal(i, normi, intA, sepLR, anchoL, anchoR, anchoS, coloresAntes[numColor], alfa);
}
if(moverL==true){ lin.moverVertical(moverL, distMov, moverH);
lin1.moverVertical(moverL, distMov, moverH); }
popMatrix();
//fondo
if(textura){ pushMatrix(); fondodePapel(R,G,B,A,sinCuadricula); popMatrix(); }
//SYPHON SERVER
server.sendScreen();
}
//
//##CONTROLES##
//
public void keyPressed()
{
char k = key;
switch(k)
{
////////////////////////////////////////////
////////////////////////////////////////////
//controles//
case '<':
sumar = !sumar;
print("sumar :",sumar,"\n");
print("paso :",paso,"\n");
print("___________________\n");
break;
case '0':
break;
case '1':
fondo=!fondo;
print("fondo :",fondo,"\n");
print("___________________\n");
break;
case '2':
sinCuadricula=!sinCuadricula;
print("sinCuadricula :",sinCuadricula,"\n");
print("___________________\n");
break;
case '3':
textura=!textura;
print("textura :",textura,"\n");
print("___________________\n");
break;
case 'z':
paso--;
paso = (paso>255)?255:paso;
paso = (paso<0)?0:paso;
print("paso :",paso,"\n");
print("___________________\n");
break;
case 'x':
paso++;
paso = (paso>255)?255:paso;
paso = (paso<0)?0:paso;
print("paso :",paso,"\n");
print("___________________\n");
break;
////////////////////////////////////////////
////////////////////////////////////////////
//fondo//
case 'q':
if(sumar==true)
{
R+=paso;
R = (R>255)?255:R;
R = (R<0)?0:R;
} else {
R-=paso;
R = (R>255)?255:R;
R = (R<0)?0:R;
}
print("Rojo :",R,"\n");
print("___________________\n");
break;
case 'w':
if(sumar==true)
{
G+=paso;
G = (G>255)?255:G;
G = (G<0)?0:G;
} else {
G-=paso;
G = (G>255)?255:G;
G = (G<0)?0:G;
}
print("Verde :",G,"\n");
print("___________________\n");
break;
case 'e':
if(sumar==true)
{
B+=paso;
B = (B>255)?255:B;
B = (B<0)?0:B;
} else {
B-=paso;
B = (B>255)?255:B;
B = (B<0)?0:B;
}
print("Azul :",B,"\n");
print("___________________\n");
break;
case 'a':
if(sumar==true)
{
A+=paso;
A = (A>255)?255:A;
A = (A<0)?0:A;
} else {
A-=paso;
A = (A>255)?255:A;
A = (A<0)?0:A;
}
print("Grano Papel :",A,"\n");
print("___________________\n");
break;
case 's':
break;
////////////////////////////////////////////
////////////////////////////////////////////
//Linea//
case 'r':
numColor+=1;
hay = (numColor > coloresAntes.length || numColor == coloresAntes.length)? false : true;
numColor = (hay)? numColor : 0;
print("numColor :",numColor,"\n");
print("___________________\n");
break;
case 't':
if(sumar==true)
{
anchoL+=paso;
anchoL = (anchoL>1000)?1000:anchoL;
anchoL = (anchoL<0)?0:anchoL;
} else {
anchoL-=paso;
anchoL = (anchoL>1000)?1000:anchoL;
anchoL = (anchoL<0)?0:anchoL;
}
print("Ancho canal izquierdo :",anchoL,"\n");
print("___________________\n");
break;
case 'y':
if(sumar==true)
{
anchoR+=paso;
anchoR = (anchoR>1000)?1000:anchoR;
anchoR = (anchoR<0)?0:anchoR;
} else {
anchoR-=paso;
anchoR = (anchoR>1000)?1000:anchoR;
anchoR = (anchoR<0)?0:anchoR;
}
print("Ancho canal derecho :",anchoR,"\n");
print("___________________\n");
break;
case 'f':
moverL = !moverL;
print("Mover Linea :",moverL,"\n");
print("___________________\n");
break;
case 'g':
moverH = !moverH;
print("Mover distancia horizontal :",moverH,"\n");
print("___________________\n");
break;
case 'h':
if(sumar==true)
{
sepLR+=paso;
sepLR = (anchoR>1000)?1000:sepLR;
sepLR = (anchoR<0)?0:sepLR;
} else {
sepLR-=paso;
sepLR = (anchoR>1000)?1000:sepLR;
sepLR = (anchoR<0)?10:anchoR;
}
print("Separaci\u00f3n canales :",sepLR,"\n");
print("___________________\n");
break;
case 'v':
if(sumar==true)
{
intA+=paso;
intA = (intA>1000)?1000:intA;
intA = (intA<0)?0:intA;
} else {
intA-=paso;
intA = (intA>1000)?1000:intA;
intA = (intA<0)?0:intA;
}
print("intencidad respuesta input :",intA,"\n");
print("___________________\n");
break;
case 'b':
if(sumar==true)
{
distMov+=paso;
distMov = (distMov>1000)?1000:distMov;
distMov = (distMov<0)?0:distMov;
} else {
distMov-=paso;
distMov = (distMov>1000)?1000:distMov;
distMov = (distMov<0)?0:distMov;
}
print("distMov :",distMov,"\n");
print("___________________\n");
break;
case 'n':
if(sumar==true)
{
anchoS+=paso;
anchoS = (anchoS>1000)?1000:anchoS;
anchoS = (anchoS<0)?0:anchoS;
} else {
anchoS-=paso;
anchoS = (anchoS>1000)?1000:anchoS;
anchoS = (anchoS<0)?0:anchoS;
}
print("distMov :",anchoS,"\n");
print("___________________\n");
break;
////////////////////////////////////////////
////////////////////////////////////////////
//RESETS 7 8 9//
case '9':
numColor = 1;
alfa = 255;
moverL = false;
moverH = false;
xIL = 0;
yIL = 10;
intA = 50;
sepLR = 5;
anchoL = 0;
anchoR = 0;
anchoS = 1;
distMov = 1;
fondo = true;
textura = true;
sinCuadricula = true;
R = 85;
G = 85;
B = 85;
A = 10;
break;
case '8':
numColor = 1;
alfa = 255;
moverL = false;
moverH = false;
xIL = 0;
yIL = 10;
intA = 50;
sepLR = 5;
anchoL = 0;
anchoR = 0;
anchoS = 1;
distMov = 1;
break;
case '7':
fondo = false;
textura = true;
sinCuadricula = true;
R = 85;
G = 85;
B = 85;
A = 10;
break;
//
//DEFAULT
default:
break;
}
}
//
//##FONDO
//
public void fondodePapel(int R, int G, int B, int A, boolean sinCuadricula)
{
if(sinCuadricula){ noStroke(); }
for (int i = 0; i<width; i+=2)
{
for (int j = 0; j<height; j+=2)
{
fill(random(R-10, R+10),random(G-10, G+10),random(B-10, B+10), random(A*2.5f,A*3));
rect(i, j, 2, 2);
}
}
for (int i = 0; i<30; i++)
{
fill(random(R/2, R+R/2), random(A*2.5f, A*3));
rect(random(0, width-2), random(0, height-2), random(1, 3), random(1, 3));
}
}
//
//##OVER##
//
public boolean sketchFullScreen() { return pCompleta; }
class Linea
{
int x, y, largo, colorLinea, a;
Linea(int X, int Y, int COLORLINEA, int A)
{
x=X;
y=Y;
colorLinea=COLORLINEA;
a=A;
}
public void conectarHorizontal(int I, int NORMI, int INTEN, int DISTI, int A1, int A2 , float GROSLIN, int COLORLINEA, int A)
{
stroke(COLORLINEA, A);
strokeWeight(GROSLIN);
line( y+in0.left.get(NORMI)*INTEN, x+I, y+A1+in0.left.get(NORMI)*INTEN, x+I+1);
line( y+DISTI+in0.right.get(NORMI)*INTEN, x+I, y+A2+DISTI+in0.right.get(NORMI)*INTEN, x+I+1);
}
public void conectarVertical(int I, int NORMI, int INTEN, int DISTI, int A1, int A2 , float GROSLIN, int COLORLINEA, int A)
{
stroke(COLORLINEA, A);
strokeWeight(GROSLIN);
line( y+in0.left.get(NORMI)*INTEN, x+I, y+A1+in0.left.get(NORMI)*INTEN, x+I+1);
line( y+DISTI+in0.right.get(NORMI)*INTEN, x+I+1, y+A2+DISTI+in0.right.get(NORMI)*INTEN, x+I);
}
public void moverVertical(boolean MOVER, int CUANTO, boolean WIDTH)
{
if(MOVER == true)
{
y+=CUANTO;
int distancia = (WIDTH == true) ? width : height;
if(y>distancia)
{
y=0;
}
}
}
}
static public void main(String[] passedArgs) {
String[] appletArgs = new String[] { "ANTES01" };
if (passedArgs != null) {
PApplet.main(concat(appletArgs, passedArgs));
} else {
PApplet.main(appletArgs);
}
}
}
|
joseflamas/zet
|
variaciones/antesFestival/ANTES01/build-tmp/source/ANTES01.java
|
Java
|
mit
| 11,561 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package au.com.scds.agric.dom.simple;
import java.util.List;
import org.apache.isis.applib.annotation.DomainService;
import org.apache.isis.applib.annotation.NatureOfService;
import org.apache.isis.applib.query.QueryDefault;
import org.apache.isis.applib.services.registry.ServiceRegistry2;
import org.apache.isis.applib.services.repository.RepositoryService;
@DomainService(
nature = NatureOfService.DOMAIN,
repositoryFor = SimpleObject.class
)
public class SimpleObjectRepository {
public List<SimpleObject> listAll() {
return repositoryService.allInstances(SimpleObject.class);
}
public List<SimpleObject> findByName(final String name) {
return repositoryService.allMatches(
new QueryDefault<>(
SimpleObject.class,
"findByName",
"name", name));
}
public SimpleObject create(final String name) {
final SimpleObject object = new SimpleObject(name);
serviceRegistry.injectServicesInto(object);
repositoryService.persist(object);
return object;
}
@javax.inject.Inject
RepositoryService repositoryService;
@javax.inject.Inject
ServiceRegistry2 serviceRegistry;
}
|
Stephen-Cameron-Data-Services/isis-agri
|
dom/src/main/java/au/com/scds/agric/dom/simple/SimpleObjectRepository.java
|
Java
|
mit
| 2,086 |
/*
* FILE: S3Operator
* Copyright (c) 2015 - 2019 GeoSpark Development Team
*
* 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.datasyslab.geosparkviz.utils;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.Bucket;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.S3Object;
import org.apache.log4j.Logger;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class S3Operator
{
private AmazonS3 s3client;
public final static Logger logger = Logger.getLogger(S3Operator.class);
public S3Operator(String regionName, String accessKey, String secretKey)
{
Regions region = Regions.fromName(regionName);
BasicAWSCredentials awsCreds = new BasicAWSCredentials(accessKey, secretKey);
s3client = AmazonS3ClientBuilder.standard().withRegion(region).withCredentials(new AWSStaticCredentialsProvider(awsCreds)).build();
logger.info("[GeoSparkViz][Constructor] Initialized a S3 client");
}
public boolean createBucket(String bucketName)
{
Bucket bucket = s3client.createBucket(bucketName);
logger.info("[GeoSparkViz][createBucket] Created a bucket: " + bucket.toString());
return true;
}
public boolean deleteImage(String bucketName, String path)
{
s3client.deleteObject(bucketName, path);
logger.info("[GeoSparkViz][deleteImage] Deleted an image if exist");
return true;
}
public boolean putImage(String bucketName, String path, BufferedImage rasterImage)
throws IOException
{
deleteImage(bucketName, path);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ImageIO.write(rasterImage, "png", outputStream);
byte[] buffer = outputStream.toByteArray();
InputStream inputStream = new ByteArrayInputStream(buffer);
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(buffer.length);
s3client.putObject(new PutObjectRequest(bucketName, path, inputStream, metadata));
inputStream.close();
outputStream.close();
logger.info("[GeoSparkViz][putImage] Put an image");
return true;
}
public BufferedImage getImage(String bucketName, String path)
throws Exception
{
logger.debug("[GeoSparkViz][getImage] Start");
S3Object s3Object = s3client.getObject(bucketName, path);
InputStream inputStream = s3Object.getObjectContent();
BufferedImage rasterImage = ImageIO.read(inputStream);
inputStream.close();
s3Object.close();
logger.info("[GeoSparkViz][getImage] Got an image");
return rasterImage;
}
}
|
Sarwat/GeoSpark
|
viz/src/main/java/org/datasyslab/geosparkviz/utils/S3Operator.java
|
Java
|
mit
| 3,664 |
package pttravis;
import java.util.List;
public class ScoreElementalDef implements ScoreItems {
public ScoreElementalDef() {
}
@Override
public String getName() {
return "Elemental Def";
}
@Override
public float score(List<Item> items) {
if( items == null ) return 0;
float score = 0;
for( Item item : items ){
if( item != null){
score += item.getFire() + item.getLightning() + item.getMagic();
}
}
return score;
}
@Override
public float score(Item[] items) {
if( items == null || items.length < 6 ) return 0;
float score = 0;
for( Item item : items ){
if( item != null){
score += item.getFire() + item.getLightning() + item.getMagic();
}
}
return score;
}
}
|
pttravis/ds-armor
|
src/pttravis/ScoreElementalDef.java
|
Java
|
mit
| 726 |
package zornco.reploidcraft.network;
import net.minecraft.entity.Entity;
import net.minecraft.server.MinecraftServer;
import net.minecraft.world.WorldServer;
import zornco.reploidcraft.ReploidCraft;
import zornco.reploidcraft.entities.EntityRideArmor;
import zornco.reploidcraft.utils.RiderState;
import io.netty.buffer.ByteBuf;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
import cpw.mods.fml.common.network.simpleimpl.MessageContext;
import cpw.mods.fml.relauncher.Side;
public class MessageRideArmor implements IMessage, IMessageHandler<MessageRideArmor, IMessage> {
public float moveForward = 0.0F;
public float moveStrafe = 0.0F;
public boolean jump = false;
public boolean sneak = false;
public boolean dash = false;
public boolean punch = false;
public int ID = 0;
public int dimension = 0;
public MessageRideArmor() {}
public MessageRideArmor(EntityRideArmor rideArmor, Entity entity) {
if(rideArmor != null && entity != null){
RiderState rs = ReploidCraft.proxy.getRiderState(entity);
if (null != rs)
{
moveStrafe = rs.getMoveStrafe();
moveForward = rs.getMoveForward();
jump = rs.isJump();
sneak = rs.isSneak();
}
ID = rideArmor.getEntityId();
dimension = rideArmor.dimension;
}
}
@Override
public IMessage onMessage(MessageRideArmor message, MessageContext ctx) {
RiderState rs = new RiderState();
rs.setMoveForward(message.moveForward);
rs.setMoveStrafe(message.moveStrafe);
rs.setJump(message.jump);
rs.setSneak(message.sneak);
Entity armor = getEntityByID(message.ID, message.dimension);
if( armor != null && armor instanceof EntityRideArmor)
{
((EntityRideArmor)armor).setRiderState(rs);
}
return null;
}
@Override
public void fromBytes(ByteBuf buf) {
moveForward = buf.readFloat();
moveStrafe = buf.readFloat();
jump = buf.readBoolean();
sneak = buf.readBoolean();
dash = buf.readBoolean();
punch = buf.readBoolean();
ID = buf.readInt();
dimension = buf.readInt();
}
@Override
public void toBytes(ByteBuf buf) {
buf.writeFloat(moveForward);
buf.writeFloat(moveStrafe);
buf.writeBoolean(jump);
buf.writeBoolean(sneak);
buf.writeBoolean(dash);
buf.writeBoolean(punch);
buf.writeInt(ID);
buf.writeInt(dimension);
}
public Entity getEntityByID(int entityId, int dimension)
{
Entity targetEntity = null;
if (Side.SERVER == FMLCommonHandler.instance().getEffectiveSide())
{
WorldServer worldserver = MinecraftServer.getServer().worldServerForDimension(dimension);
targetEntity = worldserver.getEntityByID(entityId);
}
if ((null != targetEntity) && ((targetEntity instanceof EntityRideArmor)))
{
return (EntityRideArmor)targetEntity;
}
return null;
}
}
|
ZornTaov/ReploidCraft
|
src/main/java/zornco/reploidcraft/network/MessageRideArmor.java
|
Java
|
mit
| 2,840 |
package info.bati11.otameshi.dbflute.allcommon;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.dbflute.Entity;
import org.dbflute.hook.CommonColumnAutoSetupper;
/**
* The basic implementation of the auto set-upper of common column.
* @author DBFlute(AutoGenerator)
*/
public class ImplementedCommonColumnAutoSetupper implements CommonColumnAutoSetupper {
// =====================================================================================
// Definition
// ==========
/** The logger instance for this class. (NotNull) */
private static final Logger _log = LoggerFactory.getLogger(ImplementedCommonColumnAutoSetupper.class);
// =====================================================================================
// Set up
// ======
/** {@inheritDoc} */
public void handleCommonColumnOfInsertIfNeeds(Entity targetEntity) {
}
/** {@inheritDoc} */
public void handleCommonColumnOfUpdateIfNeeds(Entity targetEntity) {
}
// =====================================================================================
// Logging
// =======
protected boolean isInternalDebugEnabled() {
return DBFluteConfig.getInstance().isInternalDebug() && _log.isDebugEnabled();
}
protected void logSettingUp(EntityDefinedCommonColumn entity, String keyword) {
_log.debug("...Setting up column columns of " + entity.asTableDbName() + " before " + keyword);
}
}
|
bati11/otameshi-webapp
|
spring4+dbflute/src/main/java/info/bati11/otameshi/dbflute/allcommon/ImplementedCommonColumnAutoSetupper.java
|
Java
|
mit
| 1,934 |
package com.winterwell.depot;
import java.util.Map;
import org.junit.Test;
import com.winterwell.depot.merge.Merger;
import com.winterwell.es.client.ESConfig;
import com.winterwell.es.client.ESHttpClient;
import com.winterwell.gson.FlexiGson;
import com.winterwell.utils.Dep;
import com.winterwell.utils.Utils;
import com.winterwell.utils.containers.ArrayMap;
public class ESStoreTest {
@Test
public void testSimple() {
Dep.setIfAbsent(FlexiGson.class, new FlexiGson());
Dep.setIfAbsent(Merger.class, new Merger());
Dep.setIfAbsent(ESConfig.class, new ESConfig());
ESConfig esconfig = Dep.get(ESConfig.class);
if ( ! Dep.has(ESHttpClient.class)) Dep.setSupplier(ESHttpClient.class, false, ESHttpClient::new);
Dep.setIfAbsent(DepotConfig.class, new DepotConfig());
ArrayMap artifact = new ArrayMap("a", "apple", "b", "bee");
Desc desc = new Desc("test-simple", Map.class);
ESDepotStore store = new ESDepotStore();
store.init();
store.put(desc, artifact);
Utils.sleep(1500);
Object got = store.get(desc);
assert Utils.equals(artifact, got) : got;
}
}
|
sodash/open-code
|
winterwell.depot/test/com/winterwell/depot/ESStoreTest.java
|
Java
|
mit
| 1,093 |
package it.gvnn.slackcast.search;
import java.util.ArrayList;
public class PodcastDataResponse extends ArrayList<Podcast> {
}
|
gvnn/slackcast
|
app/src/main/java/it/gvnn/slackcast/search/PodcastDataResponse.java
|
Java
|
mit
| 129 |
package com.iyzipay.model.subscription.enumtype;
public enum SubscriptionUpgradePeriod {
NOW(1),
NEXT_PERIOD(2);
private final Integer value;
SubscriptionUpgradePeriod(Integer value) {
this.value = value;
}
public Integer getValue() {
return value;
}
}
|
iyzico/iyzipay-java
|
src/main/java/com/iyzipay/model/subscription/enumtype/SubscriptionUpgradePeriod.java
|
Java
|
mit
| 302 |
package bolianeducation.bolianchild.view;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.andview.refreshview.XRefreshView;
import com.google.gson.reflect.TypeToken;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import bolianeducation.bolianchild.R;
import bolianeducation.bolianchild.adapter.ReplyAdapter;
import bolianeducation.bolianchild.api.BLService;
import bolianeducation.bolianchild.camera.CameraActivity;
import bolianeducation.bolianchild.camera.PopupWindowHelper;
import bolianeducation.bolianchild.custom.ProgressDialog;
import bolianeducation.bolianchild.manager.ActivityManage;
import bolianeducation.bolianchild.manager.InfoManager;
import bolianeducation.bolianchild.modle.CommentResponse;
import bolianeducation.bolianchild.modle.PageEntity;
import bolianeducation.bolianchild.modle.ReplyEntity;
import bolianeducation.bolianchild.modle.ResponseEntity;
import bolianeducation.bolianchild.utils.GsonUtils;
import bolianeducation.bolianchild.utils.LogManager;
import bolianeducation.bolianchild.utils.ToastUtil;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static bolianeducation.bolianchild.KeyList.IKEY_REPLY_ENTITY;
import static bolianeducation.bolianchild.KeyList.IKEY_TITLE;
/**
* Created by admin on 2017/8/10.
* 某个评论的所有回复页
*/
public class ReplyActivity extends CameraActivity {
@BindView(R.id.recycler_view)
RecyclerView recyclerView;
@BindView(R.id.xrefreshview)
XRefreshView xRefreshView;
@BindView(R.id.tv_right)
TextView tvRight;
@BindView(R.id.et_content)
EditText etContent;
List<ReplyEntity> replyList = new ArrayList();
int pageNo = 1;
int pageSize = 15;
ReplyAdapter adapter;
CommentResponse.Comment taskReply;
String title;
private ProgressDialog mDialog;
PopupWindowHelper popupWindowHelper;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reply);
ButterKnife.bind(this);
if (getIntent() != null) {
taskReply = (CommentResponse.Comment) getIntent().getSerializableExtra(IKEY_REPLY_ENTITY);
title = getIntent().getStringExtra(IKEY_TITLE);
}
init();
}
@Override
public void onPicture(File pictureFile, String picturePath, Bitmap pictureBitmap) {
if (picturePath == null) return;
requestUploadImg(pictureFile);
}
//定义Handler对象
private Handler handler = new Handler() {
@Override
//当有消息发送出来的时候就执行Handler的这个方法
public void handleMessage(Message msg) {
super.handleMessage(msg);
//处理UI
requestAddReply((List) msg.obj);
}
};
ArrayList<String> imgIds = new ArrayList<>();
/**
* 上传图片
*/
private void requestUploadImg(final File file) {
mDialog.show();
imgIds.clear();
new Thread() {
@Override
public void run() {
//你要执行的方法
Call<ResponseEntity> uploadImg = BLService.getHeaderService().uploadImg(BLService.createFilePart("imgFile", file));
try {
ResponseEntity body = uploadImg.execute().body();
if (body != null) {
imgIds.add(body.getEntityId());
}
LogManager.e("tag", GsonUtils.toJson(body));
} catch (IOException e) {
e.printStackTrace();
}
//执行完毕后给handler发送消息
Message message = new Message();
message.obj = imgIds;
handler.sendMessage(message);
}
}.start();
}
private void init() {
//前个页面携带
setTitle(title);
setTvBackVisible(true);
tvRight.setVisibility(View.VISIBLE);
tvRight.setText(R.string.report);
mDialog = ProgressDialog.createDialog(context, "正在上传图片");
initPopupWindow();
xRefreshView.setAutoRefresh(true);
xRefreshView.setPullLoadEnable(true);
xRefreshView.setAutoLoadMore(false);
xRefreshView.setPinnedTime(500);
xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
@Override
public void onRefresh(boolean isPullDown) {
pageNo = 1;
requestAllReplyList();
}
@Override
public void onLoadMore(boolean isSilence) {
// if (pageNo >= dataBeanX.getTotalPages()) {
// return;
// }
pageNo++;
requestAllReplyList();
}
});
recyclerView.setLayoutManager(new LinearLayoutManager(this));
replyList.add(new ReplyEntity());//占位头部
adapter = new ReplyAdapter(context, taskReply, replyList);
recyclerView.setAdapter(adapter);
}
/**
* 初始化点击头像后的PopupWindow
*/
public void initPopupWindow() {
popupWindowHelper = new PopupWindowHelper(context);
popupWindowHelper.initPopup();
//拍照
popupWindowHelper.setOnTakePhotoListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openCamera();
}
});
//从相册选择
popupWindowHelper.setTakeAlbumListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openAlbum();
}
});
}
PageEntity pageEntity;
//请求某条评论的所有回复
private void requestAllReplyList() {
Call<ResponseEntity> commentList = BLService.getHeaderService().getAllReplyById(taskReply.getId(), pageNo, pageSize);
commentList.enqueue(new Callback<ResponseEntity>() {
@Override
public void onResponse(Call<ResponseEntity> call, Response<ResponseEntity> response) {
ResponseEntity body = response.body();
LogManager.e("tag", GsonUtils.toJson(body));
if (body == null) return;
pageEntity = GsonUtils.fromJson(GsonUtils.toJson(body.getData()), new TypeToken<PageEntity<ReplyEntity>>() {
}.getType());
updateUI();
}
@Override
public void onFailure(Call<ResponseEntity> call, Throwable t) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (pageNo > 1) {
pageNo--;
}
onLoadComplete();
}
});
}
});
}
//更新UI
private void updateUI() {
runOnUiThread(new Runnable() {
@Override
public void run() {
//设置刷新
// if (pageNo >= dataBeanX.getTotalPages()) {
// xRefreshView.setPullLoadEnable(true);
// } else {
// xRefreshView.setPullLoadEnable(false);
// }
if (pageNo == 1) {
replyList.clear();
replyList.add(new ReplyEntity());//占位头部
}
onLoadComplete();
if (pageEntity.getData() == null) return;
replyList.addAll(pageEntity.getData());
adapter.notifyDataSetChanged();
}
});
}
//加载完毕
protected void onLoadComplete() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
// ToastUtil.showToast(CommunityWelfareActivity.this, "刷新首页数据了啊。。。");
xRefreshView.stopRefresh();
xRefreshView.stopLoadMore();
}
}, 500);
}
String content;
@OnClick({R.id.iv_send, R.id.tv_send, R.id.tv_right})
void onClick(View v) {
switch (v.getId()) {
case R.id.iv_send:
if (popupWindowHelper.isShowing()) {
popupWindowHelper.dismiss();
} else {
popupWindowHelper.show(v);
}
break;
case R.id.tv_send:
content = etContent.getText().toString();
if (TextUtils.isEmpty(content)) {
ToastUtil.showToast(this, "请输入回复内容");
return;
}
requestAddReply(null);
break;
case R.id.tv_right:
//举报
ActivityManage.startReportActivity(this, taskReply.getId());
break;
}
}
/**
* 请求添加评论
*/
private void requestAddReply(List<String> imgs) {
final ReplyEntity replyEntity = new ReplyEntity();
replyEntity.setTaskActionId(taskReply.getId());
replyEntity.setReplyTime(System.currentTimeMillis());
replyEntity.setContent(content);
replyEntity.setUserId(InfoManager.getUserId());
replyEntity.setAttachmentList(imgs);
Call<ResponseEntity> addReply = BLService.getHeaderService().addReply(replyEntity);
addReply.enqueue(new Callback<ResponseEntity>() {
@Override
public void onResponse(Call<ResponseEntity> call, Response<ResponseEntity> response) {
mDialog.dismiss();
ResponseEntity body = response.body();
if (body == null) return;
ToastUtil.showToast(ReplyActivity.this, body.getErrorMessage());
pageNo = 1;
requestAllReplyList();//刷新数据
etContent.setText("");
hideKeyBoard();
}
@Override
public void onFailure(Call<ResponseEntity> call, Throwable t) {
mDialog.dismiss();
ToastUtil.showToast(context, t.getMessage());
}
});
}
@Override
public void onDestroy() {
super.onDestroy();
if (mDialog != null) {
mDialog.dismiss();
}
if (popupWindowHelper != null) {
popupWindowHelper.dismiss();
}
}
}
|
iamlisa0526/bolianeducation-child
|
app/src/main/java/bolianeducation/bolianchild/view/ReplyActivity.java
|
Java
|
mit
| 11,068 |
package com.devicehive.client.impl.rest.providers;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.devicehive.client.impl.Constants;
import com.devicehive.client.impl.json.GsonFactory;
import com.devicehive.client.impl.util.Messages;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.nio.charset.Charset;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;
/**
* Provider that converts hive entity to JSON and JSON to hive entity
*/
@Provider
public class JsonRawProvider implements MessageBodyWriter<JsonObject>, MessageBodyReader<JsonObject> {
@Override
public boolean isReadable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return MediaType.APPLICATION_JSON_TYPE.getType().equals(mediaType.getType()) && MediaType
.APPLICATION_JSON_TYPE.getSubtype().equals(mediaType.getSubtype());
}
@Override
public JsonObject readFrom(Class<JsonObject> type, Type genericType, Annotation[] annotations, MediaType mediaType,
MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
throws IOException, WebApplicationException {
JsonElement element = new JsonParser().parse(new InputStreamReader(entityStream,
Charset.forName(Constants.CURRENT_CHARSET)));
if (element.isJsonObject()) {
return element.getAsJsonObject();
}
throw new IOException(Messages.NOT_A_JSON);
}
@Override
public boolean isWriteable(Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType) {
return MediaType.APPLICATION_JSON_TYPE.getType().equals(mediaType.getType()) && MediaType
.APPLICATION_JSON_TYPE.getSubtype().equals(mediaType.getSubtype());
}
@Override
public long getSize(JsonObject jsonObject, Class<?> type, Type genericType, Annotation[] annotations,
MediaType mediaType) {
return 0;
}
@Override
public void writeTo(JsonObject jsonObject, Class<?> type, Type genericType, Annotation[] annotations,
MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
throws IOException, WebApplicationException {
Gson gson = GsonFactory.createGson();
Writer writer = null;
try {
writer = new OutputStreamWriter(entityStream, Charset.forName(Constants.CURRENT_CHARSET));
gson.toJson(jsonObject, writer);
} finally {
if (writer != null) {
writer.flush();
}
}
}
}
|
lekster/devicehive-java
|
client/src/main/java/com/devicehive/client/impl/rest/providers/JsonRawProvider.java
|
Java
|
mit
| 3,161 |
package uk.co.edgeorgedev.lumber;
/**
* Root of Logging interface
* @author edgeorge
* @version 1.0
* @since 2014-06-23
*/
public interface Stump {
/** Log a verbose message */
void v(Class<?> clazz, String message);
void v(Class<?> clazz, Throwable th);
//v,d,i,w,e,wtf
}
|
ed-george/Lumber
|
src/uk/co/edgeorgedev/lumber/Stump.java
|
Java
|
mit
| 294 |
package br.eti.mertz.wkhtmltopdf.wrapper.params;
import java.util.ArrayList;
import java.util.List;
public class Params {
private List<Param> params;
public Params() {
this.params = new ArrayList<Param>();
}
public void add(Param param) {
params.add(param);
}
public void add(Param... params) {
for (Param param : params) {
add(param);
}
}
public List<String> getParamsAsStringList() {
List<String> commandLine = new ArrayList<String>();
for (Param p : params) {
commandLine.add(p.getKey());
String value = p.getValue();
if (value != null) {
commandLine.add(p.getValue());
}
}
return commandLine;
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (Param param : params) {
sb.append(param);
}
return sb.toString();
}
}
|
eamonfoy/trello-to-markdown
|
src/main/java/br/eti/mertz/wkhtmltopdf/wrapper/params/Params.java
|
Java
|
mit
| 982 |
package uk.co.lucelle;
import org.springframework.web.bind.annotation.*;
@RestController
public class Controller {
@RequestMapping("/")
public @ResponseBody String index(@RequestBody String data) {
// echo
return data;
}
}
|
jonathonadler/ziplet-base64-test
|
src/main/java/uk/co/lucelle/Controller.java
|
Java
|
mit
| 256 |
/*
* Created on Apr 28, 2005
*/
package jsrl.net;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import jsrl.LoadLibrary;
/**
* JavaPing
* Java Bindings for the SRL Library's Ping Logic
*/
public class JavaPing implements Runnable, PingListener
{
public static final int ECHO_REPLY = 0;
public static final int DESTINATION_UNREACHABLE = 3;
// local listener
protected PingListener _listener = null;
protected boolean _is_running = false;
private static JavaPing __javaping_singleton = null;
protected boolean _has_rawsockets = false;
static
{
LoadLibrary.Load();
__javaping_singleton = new JavaPing();
}
/** returns an instance of the Java Ping Utility
* @throws SocketException */
public static JavaPing getInstance()
{
return __javaping_singleton;
}
private JavaPing()
{
_has_rawsockets = begin();
}
public synchronized void startListening(PingListener listener) throws SocketException
{
if (!_has_rawsockets)
throw new SocketException("permission denied attempting to create raw socket!");
_listener = listener;
new Thread(this).start();
}
public synchronized void stopListening()
{
_is_running = false;
}
public boolean isListening()
{
return _is_running;
}
protected int counter = 0;
public int receivedCount()
{
return counter;
}
/** main method for performing reads */
public void run()
{
counter = 0;
_is_running = true;
while (_is_running)
{
try
{
_listener.ping_result(pong(100));
++counter;
}
catch (SocketTimeoutException e)
{
}
catch (SocketException e)
{
}
}
_listener = null;
}
static final PingResult DUMMY_RESULT = new PingResult();
public void clearIncoming()
{
_pong(0, DUMMY_RESULT);
}
public PingResult pingpong(String address, int seq, int msg_size, int time_out) throws SocketTimeoutException
{
return pingpong(address, seq, msg_size, time_out, 200);
}
public PingResult pingpong(String address, int seq, int msg_size, int time_out, int ttl) throws SocketTimeoutException
{
PingResult result = new PingResult();
if (!_pingpong(address, seq, msg_size, time_out, ttl, result))
{
throw new java.net.SocketTimeoutException("receiving echo reply timed out after "
+ time_out);
}
return result;
}
public synchronized void ping(String address, int seq, int msg_size)
{
ping(address, seq, msg_size, 200);
}
/** send a ICMP Echo Request to the specified ip */
public native void ping(String address, int seq, int msg_size, int ttl);
/**pthread
* recv a ICMP Echo Reply
* @param time_out in milliseconds
* @throws SocketTimeoutException
*/
public PingResult pong(int time_out) throws SocketException, SocketTimeoutException
{
if (!_has_rawsockets)
throw new SocketException("permission denied attempting to create raw socket!");
PingResult result = new PingResult();
if (!_pong(time_out, result))
{
throw new java.net.SocketTimeoutException("receiving echo reply timeout after "
+ time_out);
}
return result;
}
/** closes the Java Ping utility free resources */
public void close()
{
synchronized (JavaPing.class)
{
if (__javaping_singleton != null)
{
end();
__javaping_singleton = null;
}
}
}
/** initialize our cpp code */
private native boolean begin();
/** native call for ping reply */
private native boolean _pong(int timeout, PingResult result);
/** native call that will use ICMP.dll on windows */
private native boolean _pingpong(String address, int seq, int msg_size, int timeout, int ttl, PingResult result);
/** free pinger resources */
public native void end();
public void ping_result(PingResult result)
{
if (result.type == ECHO_REPLY)
{
System.out.println("Reply from: " + result.from + " icmp_seq=" + result.seq + " bytes: " + result.bytes + " time=" + result.rtt + " TTL=" + result.ttl);
}
else if (result.type == DESTINATION_UNREACHABLE)
{
System.out.println("DESTINATION UNREACHABLE icmp_seq=" + result.seq);
}
else
{
System.out.println("unknown icmp packet received");
}
}
public static void main(String[] args) throws InterruptedException, UnknownHostException, SocketTimeoutException
{
if (args.length == 0)
{
System.out.println("usage: ping host [options]");
return;
}
String address = "127.0.0.1";
int count = 5;
int size = 56;
int delay = 1000;
for (int i = 0; i < args.length; ++i)
{
if (args[i].compareToIgnoreCase("-c") == 0)
{
++i;
if (i < args.length) count = Integer.parseInt(args[i]);
}
else if (args[i].compareToIgnoreCase("-s") == 0)
{
++i;
if (i < args.length) size = Integer.parseInt(args[i]);
}
else if (args[i].compareToIgnoreCase("-d") == 0)
{
++i;
if (i < args.length) delay = Integer.parseInt(args[i]);
}
else
{
address = args[i];
}
}
System.out.println("count: " + count + " size: " + size + " delay: " + delay);
address = InetAddress.getByName(address).getHostAddress();
JavaPing pingman;
pingman = getInstance();
//pingman.startListening(pingman);
//Thread.sleep(100);
for (int i = 0; i < count; ++i)
{
pingman.ping_result(pingman.pingpong(address, i, size, 500));
Thread.sleep(delay);
}
if (pingman.receivedCount() < count)
System.out.println("DID NOT RECEIVE REPLIES FOR SOME PACKETS!");
pingman.end();
}
}
|
311labs/SRL
|
java/src/jsrl/net/JavaPing.java
|
Java
|
mit
| 5,558 |
package com.xcode.mobile.smilealarm.alarmpointmanager;
import android.content.Context;
import java.io.IOException;
import java.sql.Date;
import java.sql.Time;
import java.util.Calendar;
import java.util.HashMap;
import com.xcode.mobile.smilealarm.DataHelper;
import com.xcode.mobile.smilealarm.DateTimeHelper;
import com.xcode.mobile.smilealarm.R;
public class RisingPlanHandler {
private static final int VALID_CODE = 1;
private static final int INVALID_CODE_EXP = 2;
private static final int INVALID_CODE_EXP_SOONER_AVG = 3;
private static final int INVALID_CODE_EXP_AVG_TOO_FAR = 4;
private static final int INVALID_CODE_EXP_AVG_TOO_NEAR = 5;
private static final int INVALID_CODE_STARTDATE_BEFORE_THE_DAY_AFTER_TOMORROW = 6;
private static final int[] ListOfDescreasingMinutes = new int[]{-1, 2, 5, 10, 15, 18, 20};
private HashMap<Date, AlarmPoint> _risingPlan;
private int _currentStage;
private Date _theDateBefore;
private Time _theWakingTimeBefore;
private Time _expWakingTime;
private int _checkCode;
public static int Connect(Context ctx) {
AlarmPointListHandler aplh_RisingPlan = new AlarmPointListHandler(true);
AlarmPointListHandler aplh_AlarmPoint = new AlarmPointListHandler(false);
return aplh_AlarmPoint.overwriteAlarmPointList(aplh_RisingPlan.getCurrentList(), ctx);
}
public int createRisingPlan(Time avgWakingTime, Time expWakingTime, Date startDate, Context ctx)
throws IOException {
_checkCode = checkParameters(avgWakingTime, expWakingTime, startDate);
if (_checkCode != VALID_CODE)
return _checkCode;
_risingPlan = new HashMap<Date, AlarmPoint>();
_currentStage = 1;
_theDateBefore = new Date(DateTimeHelper.GetTheDateBefore(startDate));
_theWakingTimeBefore = avgWakingTime;
_expWakingTime = expWakingTime;
AlarmPoint ap0 = new AlarmPoint(_theDateBefore);
ap0.setColor();
_risingPlan.put(ap0.getSQLDate(), ap0);
while (DateTimeHelper.DurationTwoSQLTime(_theWakingTimeBefore,
_expWakingTime) >= ListOfDescreasingMinutes[_currentStage]) {
generateRisingPlanInCurrentStage();
_currentStage++;
}
generateTheLastAlarmPoint();
DataHelper.getInstance().saveAlarmPointListToData(true, _risingPlan);
return ReturnCode.OK;
}
public String getNotificationFromErrorCode(Context ctx) {
switch (_checkCode) {
case INVALID_CODE_EXP:
return ctx.getString(R.string.not_ExpTime);
case INVALID_CODE_EXP_SOONER_AVG:
return ctx.getString(R.string.not_AvgTime);
case INVALID_CODE_EXP_AVG_TOO_FAR:
return ctx.getString(R.string.not_AvgExpTooLong);
case INVALID_CODE_EXP_AVG_TOO_NEAR:
return ctx.getString(R.string.not_AvgExpTooShort);
case INVALID_CODE_STARTDATE_BEFORE_THE_DAY_AFTER_TOMORROW:
return ctx.getString(R.string.not_StrDate);
default:
return "invalid Code";
}
}
private int checkParameters(Time avgTime, Time expTime, Date startDate) {
if (!isAfterTomorrow(startDate))
return INVALID_CODE_STARTDATE_BEFORE_THE_DAY_AFTER_TOMORROW;
if (DateTimeHelper.CompareTo(avgTime, expTime) < 0)
return INVALID_CODE_EXP_SOONER_AVG;
Time BeginExpTime = new Time(DateTimeHelper.GetSQLTime(5, 0));
Time EndExpTime = new Time(DateTimeHelper.GetSQLTime(8, 0));
if (DateTimeHelper.CompareTo(expTime, BeginExpTime) < 0 || DateTimeHelper.CompareTo(expTime, EndExpTime) > 0) {
return INVALID_CODE_EXP;
}
int maxMinutes = 875;
int minMinutes = 20;
if (DateTimeHelper.DurationTwoSQLTime(avgTime, expTime) > maxMinutes)
return INVALID_CODE_EXP_AVG_TOO_FAR;
if (DateTimeHelper.DurationTwoSQLTime(avgTime, expTime) < minMinutes)
return INVALID_CODE_EXP_AVG_TOO_NEAR;
return VALID_CODE;
}
private void generateRisingPlanInCurrentStage() {
int daysInStage = 10;
if (ListOfDescreasingMinutes[_currentStage] == 15)
daysInStage = 15;
for (int i = 0; i < daysInStage && DateTimeHelper.DurationTwoSQLTime(_theWakingTimeBefore,
_expWakingTime) >= ListOfDescreasingMinutes[_currentStage]; i++) {
// WakingTime
Date currentDate = new Date(DateTimeHelper.GetTheNextDate(_theDateBefore));
AlarmPoint ap = new AlarmPoint(currentDate);
ap.setColor();
Time currentWakingTime = DateTimeHelper.GetSQLTime(_theWakingTimeBefore,
-(ListOfDescreasingMinutes[_currentStage]));
ap.setTimePoint(currentWakingTime, 1);
// SleepingTime
Time sleepingTimeBefore = getSleepingTime(currentWakingTime);
AlarmPoint apBefore = _risingPlan.get(_theDateBefore);
apBefore.setTimePoint(sleepingTimeBefore, 2);
// put
_risingPlan.put(apBefore.getSQLDate(), apBefore);
_risingPlan.put(ap.getSQLDate(), ap);
// reset before
_theDateBefore = currentDate;
_theWakingTimeBefore = currentWakingTime;
}
}
private void generateTheLastAlarmPoint() {
// WakingTime
Date currentDate = new Date(DateTimeHelper.GetTheNextDate(_theDateBefore));
AlarmPoint ap = new AlarmPoint(currentDate);
ap.setColor();
Time currentWakingTime = _expWakingTime;
ap.setTimePoint(currentWakingTime, 1);
// SleepingTime
Time sleepingTimeBefore = getSleepingTime(currentWakingTime);
AlarmPoint apBefore = _risingPlan.get(_theDateBefore);
apBefore.setTimePoint(sleepingTimeBefore, 2);
// put
_risingPlan.put(apBefore.getSQLDate(), apBefore);
_risingPlan.put(ap.getSQLDate(), ap);
// reset before
_theDateBefore = currentDate;
_theWakingTimeBefore = currentWakingTime;
}
private Time getSleepingTime(Time wakingTime) {
// wakingTime - 11 PM of thedaybefore > 8 hours => 11 PM
// <=> if wakingTime >= 7 AM
// or wakingTime >= 7AM => 11PM
// 6AM <= wakingTime < 7AM => 10:30 PM
// 5AM <= wakingTime < 6AM => 10 PM
Time SevenAM = new Time(DateTimeHelper.GetSQLTime(7, 0));
Time SixAM = new Time(DateTimeHelper.GetSQLTime(6, 0));
Time FiveAM = new Time(DateTimeHelper.GetSQLTime(5, 0));
Time EleventPM = new Time(DateTimeHelper.GetSQLTime(23, 0));
Time Ten30PM = new Time(DateTimeHelper.GetSQLTime(22, 30));
Time TenPM = new Time(DateTimeHelper.GetSQLTime(22, 0));
if (DateTimeHelper.CompareTo(wakingTime, SevenAM) >= 0) {
return EleventPM;
}
if (DateTimeHelper.CompareTo(wakingTime, SevenAM) < 0 && DateTimeHelper.CompareTo(wakingTime, SixAM) >= 0) {
return Ten30PM;
}
if (DateTimeHelper.CompareTo(wakingTime, SixAM) < 0 && DateTimeHelper.CompareTo(wakingTime, FiveAM) >= 0) {
return TenPM;
}
return null;
}
private Boolean isAfterTomorrow(Date startDate) {
Date today = new Date(Calendar.getInstance().getTimeInMillis());
Date tomorrow = new Date(DateTimeHelper.GetTheNextDate(today));
return (DateTimeHelper.CompareTo(startDate, tomorrow) > 0);
}
}
|
anhnguyenbk/XCODE-MOBILE-APPS-DEV
|
SmileAlarm/app/src/main/java/com/xcode/mobile/smilealarm/alarmpointmanager/RisingPlanHandler.java
|
Java
|
mit
| 7,754 |
package ny2.ats.model.tool;
import java.util.function.BiPredicate;
/**
* 取引条件計算の演算子のクラスです
*/
public enum TradeConditionOperator {
EQUAL((d1, d2) -> Double.compare(d1, d2) == 0, null, "="),
LESS((d1, d2) -> d1 < d2, null, "<"),
LESS_EQUAL((d1, d2) -> d1 <= d2, null, "<="),
GRATER((d1, d2) -> d1 > d2, null, ">"),
GRATER_EQUAL((d1, d2) -> d1 >= d2, null, ">="),
BETWEEN((d1, d2) -> d1 >= d2, (d1, d2) -> d1 <= d2, " between "),
WITHOUT((d1, d2) -> d1 < d2, (d1, d2) -> d1 > d2, " without ");
// //////////////////////////////////////
// Field
// //////////////////////////////////////
private BiPredicate<Double, Double> biPredicate;
private BiPredicate<Double, Double> biPredicate2;
private String expression;
private TradeConditionOperator(BiPredicate<Double, Double> biPredicate, BiPredicate<Double, Double> biPredicate2, String expression) {
this.biPredicate = biPredicate;
this.expression = expression;
}
// //////////////////////////////////////
// Method
// //////////////////////////////////////
/**
* 2種類のBiPredicateを持つかどうかを返します<br>
* BETWEEN, WITHOUT のみtrueを返します
* @return
*/
public boolean hasTwoPredicate() {
if (biPredicate2 != null) {
return true;
} else {
return false;
}
}
public BiPredicate<Double, Double> getBiPredicate() {
return biPredicate;
}
public BiPredicate<Double, Double> getBiPredicate2() {
return biPredicate2;
}
public String getExpression() {
return expression;
}
}
|
Naoki-Yatsu/FX-AlgorithmTrading
|
ats/src/main/java/ny2/ats/model/tool/TradeConditionOperator.java
|
Java
|
mit
| 1,710 |
package com.fragmobile;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}
|
Pinablink/FragMobile
|
FragMobile/app/src/test/java/com/fragmobile/ExampleUnitTest.java
|
Java
|
mit
| 408 |
class LinkedList {
public static void main(String[] a) {
System.out.println(new LL().Start());
}
}
class Element {
int Age;
int Salary;
boolean Married;
public boolean Init(int v_Age, int v_Salary, boolean v_Married) {
Age = v_Age;
Salary = v_Salary;
Married = v_Married;
return true;
}
public int GetAge() {
return Age;
}
public int GetSalary() {
return Salary;
}
public boolean GetMarried() {
return Married;
}
public boolean Equal(Element other) {
boolean ret_val;
int aux01;
int aux02;
int nt;
ret_val = true;
aux01 = other.GetAge();
if (!(this.Compare(aux01, Age)))
ret_val = false;
else
{
aux02 = other.GetSalary();
if (!(this.Compare(aux02, Salary)))
ret_val = false;
else
if (Married)
if (!(other.GetMarried()))
ret_val = false;
else
nt = 0;
else
if (other.GetMarried())
ret_val = false;
else
nt = 0;
}
return ret_val;
}
public boolean Compare(int num1, int num2) {
boolean retval;
int aux02;
retval = false;
aux02 = num2 + 1;
if (num1 < num2)
retval = false;
else
if (!(num1 < aux02))
retval = false;
else
retval = true;
return retval;
}
}
class List {
Element elem;
List next;
boolean end;
public boolean Init() {
end = true;
return true;
}
public boolean InitNew(Element v_elem, List v_next, boolean v_end) {
end = v_end;
elem = v_elem;
next = v_next;
return true;
}
public List Insert(Element new_elem) {
boolean ret_val;
List aux03;
List aux02;
aux03 = this;
aux02 = new List();
ret_val = aux02.InitNew(new_elem, aux03, false);
return aux02;
}
public boolean SetNext(List v_next) {
next = v_next;
return true;
}
public List Delete(Element e) {
List my_head;
boolean ret_val;
boolean aux05;
List aux01;
List prev;
boolean var_end;
Element var_elem;
int aux04;
int nt;
my_head = this;
ret_val = false;
aux04 = 0 - 1;
aux01 = this;
prev = this;
var_end = end;
var_elem = elem;
while (!(var_end) && !(ret_val))
{
if (e.Equal(var_elem))
{
ret_val = true;
if (aux04 < 0)
{
my_head = aux01.GetNext();
}
else
{
System.out.println(0 - 555);
aux05 = prev.SetNext(aux01.GetNext());
System.out.println(0 - 555);
}
}
else
nt = 0;
if (!(ret_val))
{
prev = aux01;
aux01 = aux01.GetNext();
var_end = aux01.GetEnd();
var_elem = aux01.GetElem();
aux04 = 1;
}
else
nt = 0;
}
return my_head;
}
public int Search(Element e) {
int int_ret_val;
List aux01;
Element var_elem;
boolean var_end;
int nt;
int_ret_val = 0;
aux01 = this;
var_end = end;
var_elem = elem;
while (!(var_end))
{
if (e.Equal(var_elem))
{
int_ret_val = 1;
}
else
nt = 0;
aux01 = aux01.GetNext();
var_end = aux01.GetEnd();
var_elem = aux01.GetElem();
}
return int_ret_val;
}
public boolean GetEnd() {
return end;
}
public Element GetElem() {
return elem;
}
public List GetNext() {
return next;
}
public boolean Print() {
List aux01;
boolean var_end;
Element var_elem;
aux01 = this;
var_end = end;
var_elem = elem;
while (!(var_end))
{
System.out.println(var_elem.GetAge());
aux01 = aux01.GetNext();
var_end = aux01.GetEnd();
var_elem = aux01.GetElem();
}
return true;
}
}
class LL {
public int Start() {
List head;
List last_elem;
boolean aux01;
Element el01;
Element el02;
Element el03;
last_elem = new List();
aux01 = last_elem.Init();
head = last_elem;
aux01 = head.Init();
aux01 = head.Print();
el01 = new Element();
aux01 = el01.Init(25, 37000, false);
head = head.Insert(el01);
aux01 = head.Print();
System.out.println(10000000);
el01 = new Element();
aux01 = el01.Init(39, 42000, true);
el02 = el01;
head = head.Insert(el01);
aux01 = head.Print();
System.out.println(10000000);
el01 = new Element();
aux01 = el01.Init(22, 34000, false);
head = head.Insert(el01);
aux01 = head.Print();
el03 = new Element();
aux01 = el03.Init(27, 34000, false);
System.out.println(head.Search(el02));
System.out.println(head.Search(el03));
System.out.println(10000000);
el01 = new Element();
aux01 = el01.Init(28, 35000, false);
head = head.Insert(el01);
aux01 = head.Print();
System.out.println(2220000);
head = head.Delete(el02);
aux01 = head.Print();
System.out.println(33300000);
head = head.Delete(el01);
aux01 = head.Print();
System.out.println(44440000);
return 0;
}
}
|
team-compilers/compilers
|
MiniJava/results/SamplesCorrect/LinkedList/code.java
|
Java
|
mit
| 6,548 |
package me.mrdaniel.npcs.actions;
import javax.annotation.Nonnull;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.action.TextActions;
import org.spongepowered.api.text.format.TextColors;
import me.mrdaniel.npcs.catalogtypes.actiontype.ActionTypes;
import me.mrdaniel.npcs.io.NPCFile;
import me.mrdaniel.npcs.managers.ActionResult;
import ninja.leaping.configurate.ConfigurationNode;
public class ActionGoto extends Action {
private int next;
public ActionGoto(@Nonnull final ConfigurationNode node) { this(node.getNode("Next").getInt(0)); }
public ActionGoto(final int next) {
super(ActionTypes.GOTO);
this.next = next;
}
public void setNext(final int next) { this.next = next; }
@Override
public void execute(final Player p, final NPCFile file, final ActionResult result) {
result.setNextAction(this.next);
}
@Override
public void serializeValue(final ConfigurationNode node) {
node.getNode("Next").setValue(this.next);
}
@Override
public Text getLine(final int index) {
return Text.builder().append(Text.of(TextColors.GOLD, "Goto: "),
Text.builder().append(Text.of(TextColors.AQUA, this.next))
.onHover(TextActions.showText(Text.of(TextColors.YELLOW, "Change")))
.onClick(TextActions.suggestCommand("/npc action edit " + index + " goto <goto>")).build()).build();
}
}
|
Daniel12321/NPCs
|
src/main/java/me/mrdaniel/npcs/actions/ActionGoto.java
|
Java
|
mit
| 1,403 |
package com.binaryedu.web.controllers;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
public class SignUpSuccessController implements Controller
{
protected final Log logger = LogFactory.getLog(this.getClass());
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
logger.info("Returning Sign Up Success View");
return new ModelAndView("signupSuccess");
}
}
|
parambirs/binaryedu
|
src/main/java/com/binaryedu/web/controllers/SignUpSuccessController.java
|
Java
|
mit
| 782 |
package com.playtika.test.dynamodb;
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.boot.autoconfigure.AutoConfigurations;
import org.springframework.boot.test.context.runner.ApplicationContextRunner;
import org.testcontainers.containers.Container;
public class DisableDynamoDBTest {
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(AutoConfigurations.of(
EmbeddedDynamoDBBootstrapConfiguration.class,
EmbeddedDynamoDBDependenciesAutoConfiguration.class));
@Test
public void contextLoads() {
contextRunner
.withPropertyValues(
"embedded.dynamodb.enabled=false"
)
.run((context) -> Assertions.assertThat(context)
.hasNotFailed()
.doesNotHaveBean(Container.class)
.doesNotHaveBean("dynamodbDependencyPostProcessor"));
}
}
|
Playtika/testcontainers-spring-boot
|
embedded-dynamodb/src/test/java/com/playtika/test/dynamodb/DisableDynamoDBTest.java
|
Java
|
mit
| 1,055 |
package com.github.mikhailerofeev.scholarm.local.services;
import android.app.Application;
import com.github.mikhailerofeev.scholarm.api.entities.Question;
import com.github.mikhailerofeev.scholarm.local.entities.QuestionImpl;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.inject.Inject;
import java.io.*;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
/**
* @author m-erofeev
* @since 22.08.14
*/
public class QuestionsManager {
private final Application application;
private List<QuestionImpl> questions;
private Long maxId;
@Inject
public QuestionsManager(Application application) {
this.application = application;
}
public List<Question> getQuestions(Set<String> questionThemesAndSubthemesNames) {
List<Question> ret = new ArrayList<>();
for (QuestionImpl question : questions) {
if (questionThemesAndSubthemesNames.contains(question.getThemeName())) {
ret.add(question);
}
}
return ret;
}
@Inject
public synchronized void init() {
System.out.println("init QuestionsManager");
System.out.println("our dir: " + application.getApplicationContext().getFilesDir());
maxId = 0L;
File dataFile = getDataFile();
if (!dataFile.exists()) {
System.out.println(dataFile.getAbsolutePath() + " not exists");
if (!tryToLoadAssets()) {
questions = new ArrayList<>();
}
return;
}
FileReader fileReader;
try {
fileReader = new FileReader(dataFile);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
readQuestions(fileReader);
}
private void readQuestions(Reader fileReader) {
Type type = new TypeToken<List<QuestionImpl>>() {
}.getType();
questions = new Gson().fromJson(fileReader, type);
for (QuestionImpl question : questions) {
if (maxId < question.getId()) {
maxId = question.getId();
}
}
}
private boolean tryToLoadAssets() {
if (application.getAssets() == null) {
return false;
}
try {
Reader inputStreamReader = new InputStreamReader(application.getAssets().open("database.json"));
readQuestions(inputStreamReader);
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
public synchronized void addQuestions(List<QuestionImpl> questionsToAdd) {
for (QuestionImpl question : questionsToAdd) {
question.setId(maxId++);
this.questions.add(question);
}
File dataFile = getDataFile();
dataFile.delete();
try {
if (!dataFile.createNewFile()) {
throw new RuntimeException("can't create file");
}
String questionsStr = new Gson().toJson(this.questions);
FileWriter writer = new FileWriter(dataFile);
writer.append(questionsStr);
writer.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private File getDataFile() {
File filesDir = application.getApplicationContext().getFilesDir();
return new File(filesDir.getAbsolutePath() + "database.json");
}
}
|
Whoosh/schalarm
|
localdb/src/main/java/com/github/mikhailerofeev/scholarm/local/services/QuestionsManager.java
|
Java
|
mit
| 3,530 |
/*
* Copyright (C) 2011-2012 Dr. John Lindsay <jlindsay@uoguelph.ca>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package plugins;
import java.util.Date;
import whitebox.geospatialfiles.WhiteboxRaster;
import whitebox.interfaces.WhiteboxPlugin;
import whitebox.interfaces.WhiteboxPluginHost;
/**
* This tool calculates the average slope gradient (i.e., slope steepness in degrees) of the flowpaths that run through each grid cell in an input digital elevation model (DEM) to the upslope divide cells.
*
* @author Dr. John Lindsay email: jlindsay@uoguelph.ca
*/
public class AverageSlopeToDivide implements WhiteboxPlugin {
private WhiteboxPluginHost myHost = null;
private String[] args;
// Constants
private static final double LnOf2 = 0.693147180559945;
/**
* Used to retrieve the plugin tool's name. This is a short, unique name
* containing no spaces.
*
* @return String containing plugin name.
*/
@Override
public String getName() {
return "AverageSlopeToDivide";
}
/**
* Used to retrieve the plugin tool's descriptive name. This can be a longer
* name (containing spaces) and is used in the interface to list the tool.
*
* @return String containing the plugin descriptive name.
*/
@Override
public String getDescriptiveName() {
return "Average Flowpath Slope From Cell To Divide";
}
/**
* Used to retrieve a short description of what the plugin tool does.
*
* @return String containing the plugin's description.
*/
@Override
public String getToolDescription() {
return "Measures the average slope gradient from each grid cell to all "
+ "upslope divide cells.";
}
/**
* Used to identify which toolboxes this plugin tool should be listed in.
*
* @return Array of Strings.
*/
@Override
public String[] getToolbox() {
String[] ret = {"FlowpathTAs"};
return ret;
}
/**
* Sets the WhiteboxPluginHost to which the plugin tool is tied. This is the
* class that the plugin will send all feedback messages, progress updates,
* and return objects.
*
* @param host The WhiteboxPluginHost that called the plugin tool.
*/
@Override
public void setPluginHost(WhiteboxPluginHost host) {
myHost = host;
}
/**
* Used to communicate feedback pop-up messages between a plugin tool and
* the main Whitebox user-interface.
*
* @param feedback String containing the text to display.
*/
private void showFeedback(String message) {
if (myHost != null) {
myHost.showFeedback(message);
} else {
System.out.println(message);
}
}
/**
* Used to communicate a return object from a plugin tool to the main
* Whitebox user-interface.
*
* @return Object, such as an output WhiteboxRaster.
*/
private void returnData(Object ret) {
if (myHost != null) {
myHost.returnData(ret);
}
}
private int previousProgress = 0;
private String previousProgressLabel = "";
/**
* Used to communicate a progress update between a plugin tool and the main
* Whitebox user interface.
*
* @param progressLabel A String to use for the progress label.
* @param progress Float containing the progress value (between 0 and 100).
*/
private void updateProgress(String progressLabel, int progress) {
if (myHost != null && ((progress != previousProgress)
|| (!progressLabel.equals(previousProgressLabel)))) {
myHost.updateProgress(progressLabel, progress);
}
previousProgress = progress;
previousProgressLabel = progressLabel;
}
/**
* Used to communicate a progress update between a plugin tool and the main
* Whitebox user interface.
*
* @param progress Float containing the progress value (between 0 and 100).
*/
private void updateProgress(int progress) {
if (myHost != null && progress != previousProgress) {
myHost.updateProgress(progress);
}
previousProgress = progress;
}
/**
* Sets the arguments (parameters) used by the plugin.
*
* @param args An array of string arguments.
*/
@Override
public void setArgs(String[] args) {
this.args = args.clone();
}
private boolean cancelOp = false;
/**
* Used to communicate a cancel operation from the Whitebox GUI.
*
* @param cancel Set to true if the plugin should be canceled.
*/
@Override
public void setCancelOp(boolean cancel) {
cancelOp = cancel;
}
private void cancelOperation() {
showFeedback("Operation cancelled.");
updateProgress("Progress: ", 0);
}
private boolean amIActive = false;
/**
* Used by the Whitebox GUI to tell if this plugin is still running.
*
* @return a boolean describing whether or not the plugin is actively being
* used.
*/
@Override
public boolean isActive() {
return amIActive;
}
/**
* Used to execute this plugin tool.
*/
@Override
public void run() {
amIActive = true;
String inputHeader = null;
String outputHeader = null;
String DEMHeader = null;
int row, col, x, y;
int progress = 0;
double z, val, val2, val3;
int i, c;
int[] dX = new int[]{1, 1, 1, 0, -1, -1, -1, 0};
int[] dY = new int[]{-1, 0, 1, 1, 1, 0, -1, -1};
double[] inflowingVals = new double[]{16, 32, 64, 128, 1, 2, 4, 8};
boolean flag = false;
double flowDir = 0;
double flowLength = 0;
double numUpslopeFlowpaths = 0;
double flowpathLengthToAdd = 0;
double conversionFactor = 1;
double divideElevToAdd = 0;
double radToDeg = 180 / Math.PI;
if (args.length <= 0) {
showFeedback("Plugin parameters have not been set.");
return;
}
inputHeader = args[0];
DEMHeader = args[1];
outputHeader = args[2];
conversionFactor = Double.parseDouble(args[3]);
// check to see that the inputHeader and outputHeader are not null.
if ((inputHeader == null) || (outputHeader == null)) {
showFeedback("One or more of the input parameters have not been set properly.");
return;
}
try {
WhiteboxRaster pntr = new WhiteboxRaster(inputHeader, "r");
int rows = pntr.getNumberRows();
int cols = pntr.getNumberColumns();
double noData = pntr.getNoDataValue();
double gridResX = pntr.getCellSizeX();
double gridResY = pntr.getCellSizeY();
double diagGridRes = Math.sqrt(gridResX * gridResX + gridResY * gridResY);
double[] gridLengths = new double[]{diagGridRes, gridResX, diagGridRes, gridResY, diagGridRes, gridResX, diagGridRes, gridResY};
WhiteboxRaster DEM = new WhiteboxRaster(DEMHeader, "r");
if (DEM.getNumberRows() != rows || DEM.getNumberColumns() != cols) {
showFeedback("The input files must have the same dimensions, i.e. number of "
+ "rows and columns.");
return;
}
WhiteboxRaster output = new WhiteboxRaster(outputHeader, "rw",
inputHeader, WhiteboxRaster.DataType.FLOAT, -999);
output.setPreferredPalette("blueyellow.pal");
output.setDataScale(WhiteboxRaster.DataScale.CONTINUOUS);
output.setZUnits(pntr.getXYUnits());
WhiteboxRaster numInflowingNeighbours = new WhiteboxRaster(outputHeader.replace(".dep",
"_temp1.dep"), "rw", inputHeader, WhiteboxRaster.DataType.FLOAT, 0);
numInflowingNeighbours.isTemporaryFile = true;
WhiteboxRaster numUpslopeDivideCells = new WhiteboxRaster(outputHeader.replace(".dep",
"_temp2.dep"), "rw", inputHeader, WhiteboxRaster.DataType.FLOAT, 0);
numUpslopeDivideCells.isTemporaryFile = true;
WhiteboxRaster totalFlowpathLength = new WhiteboxRaster(outputHeader.replace(".dep",
"_temp3.dep"), "rw", inputHeader, WhiteboxRaster.DataType.FLOAT, 0);
totalFlowpathLength.isTemporaryFile = true;
WhiteboxRaster totalUpslopeDivideElev = new WhiteboxRaster(outputHeader.replace(".dep",
"_temp4.dep"), "rw", inputHeader, WhiteboxRaster.DataType.FLOAT, 0);
totalUpslopeDivideElev.isTemporaryFile = true;
updateProgress("Loop 1 of 3:", 0);
for (row = 0; row < rows; row++) {
for (col = 0; col < cols; col++) {
if (pntr.getValue(row, col) != noData) {
z = 0;
for (i = 0; i < 8; i++) {
if (pntr.getValue(row + dY[i], col + dX[i]) ==
inflowingVals[i]) { z++; }
}
if (z > 0) {
numInflowingNeighbours.setValue(row, col, z);
} else {
numInflowingNeighbours.setValue(row, col, -1);
}
} else {
output.setValue(row, col, noData);
}
}
if (cancelOp) {
cancelOperation();
return;
}
progress = (int) (100f * row / (rows - 1));
updateProgress("Loop 1 of 3:", progress);
}
updateProgress("Loop 2 of 3:", 0);
for (row = 0; row < rows; row++) {
for (col = 0; col < cols; col++) {
val = numInflowingNeighbours.getValue(row, col);
if (val <= 0 && val != noData) {
flag = false;
x = col;
y = row;
do {
val = numInflowingNeighbours.getValue(y, x);
if (val <= 0 && val != noData) {
//there are no more inflowing neighbours to visit; carry on downslope
if (val == -1) {
//it's the start of a flowpath
numUpslopeDivideCells.setValue(y, x, 0);
numUpslopeFlowpaths = 1;
divideElevToAdd = DEM.getValue(y, x);
} else {
numUpslopeFlowpaths = numUpslopeDivideCells.getValue(y, x);
divideElevToAdd = totalUpslopeDivideElev.getValue(y, x);
}
numInflowingNeighbours.setValue(y, x, noData);
// find it's downslope neighbour
flowDir = pntr.getValue(y, x);
if (flowDir > 0) {
// what's the flow direction as an int?
c = (int) (Math.log(flowDir) / LnOf2);
flowLength = gridLengths[c];
val2 = totalFlowpathLength.getValue(y, x);
flowpathLengthToAdd = val2 + numUpslopeFlowpaths * flowLength;
//move x and y accordingly
x += dX[c];
y += dY[c];
numUpslopeDivideCells.setValue(y, x,
numUpslopeDivideCells.getValue(y, x)
+ numUpslopeFlowpaths);
totalFlowpathLength.setValue(y, x,
totalFlowpathLength.getValue(y, x)
+ flowpathLengthToAdd);
totalUpslopeDivideElev.setValue(y, x,
totalUpslopeDivideElev.getValue(y, x)
+ divideElevToAdd);
numInflowingNeighbours.setValue(y, x,
numInflowingNeighbours.getValue(y, x) - 1);
} else { // you've hit the edge or a pit cell.
flag = true;
}
} else {
flag = true;
}
} while (!flag);
}
}
if (cancelOp) {
cancelOperation();
return;
}
progress = (int) (100f * row / (rows - 1));
updateProgress("Loop 2 of 3:", progress);
}
numUpslopeDivideCells.flush();
totalFlowpathLength.flush();
totalUpslopeDivideElev.flush();
numInflowingNeighbours.close();
updateProgress("Loop 3 of 3:", 0);
double[] data1 = null;
double[] data2 = null;
double[] data3 = null;
double[] data4 = null;
double[] data5 = null;
for (row = 0; row < rows; row++) {
data1 = numUpslopeDivideCells.getRowValues(row);
data2 = totalFlowpathLength.getRowValues(row);
data3 = pntr.getRowValues(row);
data4 = totalUpslopeDivideElev.getRowValues(row);
data5 = DEM.getRowValues(row);
for (col = 0; col < cols; col++) {
if (data3[col] != noData) {
if (data1[col] > 0) {
val = data2[col] / data1[col];
val2 = (data4[col] / data1[col] - data5[col]) * conversionFactor;
val3 = Math.atan(val2 / val) * radToDeg;
output.setValue(row, col, val3);
} else {
output.setValue(row, col, 0);
}
} else {
output.setValue(row, col, noData);
}
}
if (cancelOp) {
cancelOperation();
return;
}
progress = (int) (100f * row / (rows - 1));
updateProgress("Loop 3 of 3:", progress);
}
output.addMetadataEntry("Created by the "
+ getDescriptiveName() + " tool.");
output.addMetadataEntry("Created on " + new Date());
pntr.close();
DEM.close();
numUpslopeDivideCells.close();
totalFlowpathLength.close();
totalUpslopeDivideElev.close();
output.close();
// returning a header file string displays the image.
returnData(outputHeader);
} catch (OutOfMemoryError oe) {
myHost.showFeedback("An out-of-memory error has occurred during operation.");
} catch (Exception e) {
myHost.showFeedback("An error has occurred during operation. See log file for details.");
myHost.logException("Error in " + getDescriptiveName(), e);
} finally {
updateProgress("Progress: ", 0);
// tells the main application that this process is completed.
amIActive = false;
myHost.pluginComplete();
}
}
}
|
jblindsay/jblindsay.github.io
|
ghrg/Whitebox/WhiteboxGAT-linux/resources/plugins/source_files/AverageSlopeToDivide.java
|
Java
|
mit
| 16,874 |
package nl.rmokveld.wearcast.phone;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v7.app.NotificationCompat;
import nl.rmokveld.wearcast.shared.C;
public class WearCastService extends Service {
private static final String ACTION_DISCOVERY = "discovery";
private static final String ACTION_START_CAST = "start_cast";
public static void startDiscovery(Context context) {
context.startService(new Intent(context, WearCastService.class).setAction(ACTION_DISCOVERY).putExtra("start", true));
}
public static void stopDiscovery(Context context) {
context.startService(new Intent(context, WearCastService.class).setAction(ACTION_DISCOVERY).putExtra("start", false));
}
public static void startCast(Context context, String requestNode, String deviceId, String mediaJson) {
context.startService(new Intent(context, WearCastService.class)
.setAction(ACTION_START_CAST)
.putExtra(C.REQUEST_NODE_ID, requestNode)
.putExtra(C.ARG_MEDIA_INFO, mediaJson)
.putExtra(C.DEVICE_ID, deviceId));
}
private WearCastDiscoveryHelper mCastDiscoveryHelper;
private AbstractStartCastHelper mStartCastHelper;
private Runnable mTimeout = new Runnable() {
@Override
public void run() {
stopForeground(true);
mCastDiscoveryHelper.stopDiscovery();
}
};
@Override
public void onCreate() {
super.onCreate();
mCastDiscoveryHelper = new WearCastDiscoveryHelper(this);
if (WearCastNotificationManager.getExtension() != null)
mStartCastHelper = WearCastNotificationManager.getExtension().newStartCastHelper(this);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null) {
if (ACTION_DISCOVERY.equals(intent.getAction())) {
if (intent.getBooleanExtra("start", false)) {
mCastDiscoveryHelper.startDiscovery();
}
else {
mCastDiscoveryHelper.stopDiscovery();
}
} else if (ACTION_START_CAST.equals(intent.getAction())) {
mStartCastHelper.startCastFromWear(
intent.getStringExtra(C.DEVICE_ID),
intent.getStringExtra(C.ARG_MEDIA_INFO),
intent.getStringExtra(C.REQUEST_NODE_ID), null);
}
}
return START_NOT_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
mCastDiscoveryHelper.release();
mStartCastHelper.release();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
|
remcomokveld/WearCast
|
library-app/src/main/java/nl/rmokveld/wearcast/phone/WearCastService.java
|
Java
|
mit
| 2,916 |
package org.github.sriki77.edgesh.command;
public class CommandException extends RuntimeException {
public CommandException(String message) {
super(message);
}
}
|
sriki77/edgesh
|
src/main/java/org/github/sriki77/edgesh/command/CommandException.java
|
Java
|
mit
| 180 |
package spaceinvaders.command.client;
import static spaceinvaders.command.ProtocolEnum.UDP;
import spaceinvaders.client.mvc.Controller;
import spaceinvaders.client.mvc.View;
import spaceinvaders.command.Command;
/** Flush the screen. */
public class FlushScreenCommand extends Command {
private transient Controller executor;
public FlushScreenCommand() {
super(FlushScreenCommand.class.getName(),UDP);
}
@Override
public void execute() {
for (View view : executor.getViews()) {
view.flush();
}
}
@Override
public void setExecutor(Object executor) {
if (executor instanceof Controller) {
this.executor = (Controller) executor;
} else {
// This should never happen.
throw new AssertionError();
}
}
}
|
apetenchea/SpaceInvaders
|
src/main/java/spaceinvaders/command/client/FlushScreenCommand.java
|
Java
|
mit
| 771 |
/*
* The MIT License
*
* Copyright 2017 michael.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package il.ac.bgu.cs.bp.bpjs.analysis;
import il.ac.bgu.cs.bp.bpjs.TestUtils;
import static il.ac.bgu.cs.bp.bpjs.TestUtils.eventNamesString;
import il.ac.bgu.cs.bp.bpjs.model.BProgram;
import il.ac.bgu.cs.bp.bpjs.execution.BProgramRunner;
import il.ac.bgu.cs.bp.bpjs.model.ResourceBProgram;
import il.ac.bgu.cs.bp.bpjs.execution.listeners.InMemoryEventLoggingListener;
import il.ac.bgu.cs.bp.bpjs.execution.listeners.PrintBProgramRunnerListener;
import org.junit.Test;
import static il.ac.bgu.cs.bp.bpjs.TestUtils.traceEventNamesString;
import static org.junit.Assert.*;
import il.ac.bgu.cs.bp.bpjs.model.StringBProgram;
import il.ac.bgu.cs.bp.bpjs.analysis.listeners.PrintDfsVerifierListener;
import il.ac.bgu.cs.bp.bpjs.analysis.violations.DeadlockViolation;
import il.ac.bgu.cs.bp.bpjs.analysis.violations.DetectedSafetyViolation;
import il.ac.bgu.cs.bp.bpjs.analysis.violations.JsErrorViolation;
import il.ac.bgu.cs.bp.bpjs.analysis.violations.Violation;
import il.ac.bgu.cs.bp.bpjs.model.BEvent;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import static java.util.stream.Collectors.joining;
/**
* @author michael
*/
public class DfsBProgramVerifierTest {
@Test
public void sanity() throws Exception {
BProgram program = new ResourceBProgram("DFSVerifierTests/AAABTrace.js");
DfsBProgramVerifier sut = new DfsBProgramVerifier();
sut.setDebugMode(true);
sut.setMaxTraceLength(3);
sut.setIterationCountGap(1);
sut.verify(program);
assertEquals( ExecutionTraceInspections.DEFAULT_SET, sut.getInspections() );
}
@Test
public void simpleAAABTrace_forgetfulStore() throws Exception {
BProgram program = new ResourceBProgram("DFSVerifierTests/AAABTrace.js");
DfsBProgramVerifier sut = new DfsBProgramVerifier();
sut.setProgressListener(new PrintDfsVerifierListener());
program.appendSource(Requirements.eventNotSelected("B"));
sut.setVisitedStateStore(new ForgetfulVisitedStateStore());
VerificationResult res = sut.verify(program);
assertTrue(res.isViolationFound());
assertEquals("AAAB", traceEventNamesString(res, ""));
}
@Test
public void simpleAAABTrace() throws Exception {
BProgram program = new ResourceBProgram("DFSVerifierTests/AAABTrace.js");
DfsBProgramVerifier sut = new DfsBProgramVerifier();
sut.setDebugMode(true);
sut.setProgressListener(new PrintDfsVerifierListener());
program.appendSource(Requirements.eventNotSelected("B"));
sut.setVisitedStateStore(new BThreadSnapshotVisitedStateStore());
VerificationResult res = sut.verify(program);
assertTrue(res.isViolationFound());
assertEquals("AAAB", traceEventNamesString(res, ""));
}
@Test
public void simpleAAABTrace_hashedNodeStore() throws Exception {
BProgram program = new ResourceBProgram("DFSVerifierTests/AAABTrace.js");
DfsBProgramVerifier sut = new DfsBProgramVerifier();
sut.setDebugMode(true);
sut.setProgressListener(new PrintDfsVerifierListener());
program.appendSource(Requirements.eventNotSelected("B"));
VisitedStateStore stateStore = new BProgramSnapshotVisitedStateStore();
sut.setVisitedStateStore(stateStore);
VerificationResult res = sut.verify(program);
assertTrue(res.isViolationFound());
assertEquals("AAAB", traceEventNamesString(res, ""));
//Add trivial getter check
VisitedStateStore retStore = sut.getVisitedStateStore();
assertSame(retStore, stateStore);
}
@Test
public void testAAABRun() {
BProgram program = new ResourceBProgram("DFSVerifierTests/AAABTrace.js");
BProgramRunner rnr = new BProgramRunner(program);
rnr.addListener(new PrintBProgramRunnerListener());
InMemoryEventLoggingListener eventLogger = rnr.addListener(new InMemoryEventLoggingListener());
rnr.run();
eventLogger.getEvents().forEach(System.out::println);
assertTrue(eventNamesString(eventLogger.getEvents(), "").matches("^(AAAB)+$"));
}
@Test
public void deadlockTrace() throws Exception {
BProgram program = new ResourceBProgram("DFSVerifierTests/deadlocking.js");
DfsBProgramVerifier sut = new DfsBProgramVerifier();
sut.setVisitedStateStore(new ForgetfulVisitedStateStore());
VerificationResult res = sut.verify(program);
assertTrue(res.isViolationFound());
assertTrue(res.getViolation().get() instanceof DeadlockViolation);
assertEquals("A", traceEventNamesString(res, ""));
}
@Test
public void testDeadlockSetting() throws Exception {
BProgram program = new ResourceBProgram("DFSVerifierTests/deadlocking.js");
DfsBProgramVerifier sut = new DfsBProgramVerifier();
sut.addInspection(ExecutionTraceInspections.FAILED_ASSERTIONS);
VerificationResult res = sut.verify(program);
assertFalse(res.isViolationFound());
}
@Test
public void deadlockRun() {
BProgram program = new ResourceBProgram("DFSVerifierTests/deadlocking.js");
BProgramRunner rnr = new BProgramRunner(program);
rnr.addListener(new PrintBProgramRunnerListener());
InMemoryEventLoggingListener eventLogger = rnr.addListener(new InMemoryEventLoggingListener());
rnr.run();
eventLogger.getEvents().forEach(System.out::println);
assertTrue(eventNamesString(eventLogger.getEvents(), "").matches("^A$"));
}
@Test
public void testTwoSimpleBThreads() throws Exception {
BProgram bprog = new StringBProgram(
"bp.registerBThread('bt1', function(){bp.sync({ request:[ bp.Event(\"STAM1\") ] });});" +
"bp.registerBThread('bt2', function(){bp.sync({ request:[ bp.Event(\"STAM2\") ] });});");
DfsBProgramVerifier sut = new DfsBProgramVerifier();
sut.setIterationCountGap(1);
sut.setProgressListener(new PrintDfsVerifierListener());
sut.addInspection(ExecutionTraceInspections.FAILED_ASSERTIONS);
VerificationResult res = sut.verify(bprog);
assertFalse(res.isViolationFound());
assertEquals(4, res.getScannedStatesCount());
assertEquals(4, res.getScannedEdgesCount());
}
@Test(timeout = 2000)
public void testTwoLoopingBThreads() throws Exception {
BProgram bprog = new StringBProgram("bp.registerBThread('bt1', function(){" + " while(true){\n"
+ " bp.sync({ request:[ bp.Event(\"STAM1\") ] });\n" + "}});\n"
+ "bp.registerBThread('bt2', function(){" + " while(true){\n"
+ " bp.sync({ request:[ bp.Event(\"STAM2\") ] });\n" + "}});\n" + "");
DfsBProgramVerifier sut = new DfsBProgramVerifier();
sut.setIterationCountGap(1);
sut.setProgressListener(new PrintDfsVerifierListener());
sut.setDebugMode(true);
VerificationResult res = sut.verify(bprog);
assertFalse(res.isViolationFound());
assertEquals(1, res.getScannedStatesCount());
}
@Test(timeout = 2000)
public void testVariablesInBT() throws Exception {
BProgram bprog = new StringBProgram("bp.registerBThread('bt1', function(){" + //
" for(var i=0; i<10; i++){\n" + //
" bp.sync({ waitFor:[ bp.Event(\"X\") ] });\n" + //
" }\n" + //
" bp.sync({ block:[ bp.Event(\"X\") ] });\n" + //
"});\n" + //
"bp.registerBThread('bt2', function(){" + //
" while(true){\n" + //
" bp.sync({ request:[ bp.Event(\"X\") ] });\n" + //
"}});\n" + //
"" //
);
DfsBProgramVerifier sut = new DfsBProgramVerifier();
sut.setIterationCountGap(1);
sut.setProgressListener(new PrintDfsVerifierListener());
sut.setDebugMode(true);
VerificationResult res = sut.verify(bprog);
assertTrue(res.isViolationFound());
assertTrue(res.getViolation().get() instanceof DeadlockViolation);
assertEquals(11, res.getScannedStatesCount());
}
@Test(timeout = 2000)
public void testVariablesEquailtyInBT() throws Exception {
BProgram bprog = new StringBProgram( //
"bp.registerBThread('bt1', function(){" + //
" bp.sync({ waitFor:[ bp.Event(\"X\") ] });\n" + // 1
" bp.sync({ waitFor:[ bp.Event(\"X\") ] });\n" + // 2
" bp.sync({ waitFor:[ bp.Event(\"X\") ] });\n" + // 3
" bp.sync({ waitFor:[ bp.Event(\"X\") ] });\n" + // 4
"});\n" +
"bp.registerBThread('bt2', function(){" + //
" while(true){\n" + //
" bp.sync({ request:[ bp.Event(\"X\") ] });\n" + //
"}});\n");
DfsBProgramVerifier sut = new DfsBProgramVerifier();
sut.setIterationCountGap(1);
sut.setProgressListener(new PrintDfsVerifierListener());
sut.setDebugMode(true);
VerificationResult res = sut.verify(bprog);
assertFalse(res.isViolationFound());
// 10 syncs while bt1 is alive, 1 sync per bt2's infinite loop alone.
assertEquals(5, res.getScannedStatesCount());
// in this case only one option per state
assertEquals(5, res.getScannedEdgesCount());
}
@Test(timeout = 2000)
public void testMaxTraceLength() throws Exception {
String source = "bp.registerBThread('bt1', function(){" +
" bp.sync({ request:[ bp.Event(\"X\") ] });\n" +
" bp.sync({ request:[ bp.Event(\"X\") ] });\n" +
" bp.sync({ request:[ bp.Event(\"X\") ] });\n" +
" bp.sync({ request:[ bp.Event(\"X\") ] });\n" +
" bp.sync({ request:[ bp.Event(\"X\") ] });\n" +
" bp.sync({ request:[ bp.Event(\"X\") ] });\n" +
" bp.ASSERT(false, \"\");" +
"});";
BProgram bprog = new StringBProgram(source);
DfsBProgramVerifier sut = new DfsBProgramVerifier();
sut.setIterationCountGap(1);
sut.setProgressListener(new PrintDfsVerifierListener());
sut.setDebugMode(true);
VerificationResult res = sut.verify(bprog);
assertTrue(res.isViolationFound());
sut.setMaxTraceLength(6);
res = sut.verify(new StringBProgram(source));
assertFalse(res.isViolationFound());
}
@Test(timeout = 6000)
public void testJavaVariablesInBT() throws Exception {
BProgram bprog = new StringBProgram( //
"bp.registerBThread('bt1', function(){" + //
" var sampleArray=[1,2,3,4,5];\n" +
" while(true) \n" + //
" for(var i=0; i<10; i++){\n" + //
" bp.sync({ request:[ bp.Event(\"X\"+i) ] });\n" + //
" if (i == 5) {bp.sync({ request:[ bp.Event(\"X\"+i) ] });}\n" + //
" }\n" + //
"});\n" +
"var xs = bp.EventSet( \"X\", function(e){\r\n" +
" return e.getName().startsWith(\"X\");\r\n" +
"} );\r\n" +
"" +
"bp.registerBThread('bt2', function(){" + //
" var lastE = {name:\"what\"};" + //
" while(true) {\n" + //
" var e = bp.sync({ waitFor: xs});\n" + //
" lastE = e;" + //
" if( e.name == lastE.name) { bp.ASSERT(false,\"Poof\");} " + //
"}});\n"
);
DfsBProgramVerifier sut = new DfsBProgramVerifier();
sut.setIterationCountGap(1);
sut.setProgressListener(new PrintDfsVerifierListener());
sut.setDebugMode(true);
VerificationResult res = sut.verify(bprog);
assertTrue(res.isViolationFound());
assertTrue(res.getViolation().get() instanceof DetectedSafetyViolation);
assertEquals(2, res.getScannedStatesCount());
assertEquals(1, res.getScannedEdgesCount());
}
/**
* Running this transition system. State 3 should be arrived at twice.
* +-»B1»--+
* | |
* -»1--»A»--2 3--»C»----+
* | | | |
* | +-»B2»--+ |
* +------------«------------+
*
* event trace "AB1-" is the result of execution
*
* -»1-»A»-2-»B1»-3
*
* Whose stack is:
*
* +---+----+---+
* |1,A|2,B1|3,-|
* +---+----+---+
*
* With C selected, we get to
*
* +---+----+---+
* |1,A|2,B1|3,C| + cycleTo 0
* +---+----+---+
*
* @throws Exception
*/
@Test
public void testDoublePathDiscovery() throws Exception {
BProgram bprog = new StringBProgram( //
"bp.registerBThread(\"round\", function(){\n" +
" while( true ) {\n" +
" bp.sync({request:bp.Event(\"A\")});\n" +
" bp.sync({waitFor:[bp.Event(\"B1\"), bp.Event(\"B2\")]});\n" +
" bp.sync({request:bp.Event(\"C\")});\n" +
" }\n" +
"});\n" +
"\n" +
"bp.registerBThread(\"round-s1\", function(){\n" +
" while( true ) {\n" +
" bp.sync({waitFor:bp.Event(\"A\")});\n" +
" bp.sync({request:bp.Event(\"B1\"), waitFor:bp.Event(\"B2\")});\n" +
" }\n" +
"});\n" +
"\n" +
"bp.registerBThread(\"round-s2\", function(){\n" +
" while( true ) {\n" +
" bp.sync({waitFor:bp.Event(\"A\")});\n" +
" bp.sync({request:bp.Event(\"B2\"), waitFor:bp.Event(\"B1\")});\n" +
" }\n" +
"});");
DfsBProgramVerifier sut = new DfsBProgramVerifier();
final Set<String> foundTraces = new HashSet<>();
sut.addInspection( ExecutionTraceInspection.named("DFS trace captures", et->{
String eventTrace = et.getNodes().stream()
.map( n->n.getEvent() )
.map( o->o.map(BEvent::getName).orElse("-") )
.collect( joining("") );
System.out.println("eventTrace = " + eventTrace);
foundTraces.add(eventTrace);
return Optional.empty();
}));
sut.setProgressListener(new PrintDfsVerifierListener());
VerificationResult res = sut.verify(bprog);
assertEquals(3, res.getScannedStatesCount());
assertEquals(4, res.getScannedEdgesCount());
Set<String> expected1 = new TreeSet<>(Arrays.asList("-","A-","AB1-","AB1C", "AB2-"));
Set<String> expected2 = new TreeSet<>(Arrays.asList("-","A-","AB2-","AB2C", "AB1-"));
String eventTraces = foundTraces.stream().sorted().collect( joining(", ") );
assertTrue("Traces don't match expected: " + eventTraces,
foundTraces.equals(expected1) || foundTraces.equals(expected2) );
System.out.println("Event traces: " + eventTraces);
}
/**
* Program graph is same as above, but state "3" is duplicated since a b-thread
* holds the last event that happened in a variable.
*
* +------------«------------+
* | |
* v +-»B1»--3'---»C»--+
* | |
* -»1--»A»--2
* | |
* ^ +-»B2»--3''--»C»--+
* | |
* +------------«------------+
*
*
*
* @throws Exception
*/
@Test
public void testDoublePathWithVariablesDiscovery() throws Exception {
BProgram bprog = new StringBProgram("doubleWithVar", //
"bp.registerBThread(\"round\", function(){\n" +
" var le=null;\n" +
" while( true ) {\n" +
" bp.sync({request:bp.Event(\"A\")});\n" +
" le = bp.sync({waitFor:[bp.Event(\"B1\"), bp.Event(\"B2\")]});\n" +
" bp.sync({request:bp.Event(\"C\")});\n" +
" le=null;\n " +
" }\n" +
"});\n" +
"\n" +
"bp.registerBThread(\"round-s1\", function(){\n" +
" while( true ) {\n" +
" bp.sync({waitFor:bp.Event(\"A\")});\n" +
" bp.sync({request:bp.Event(\"B1\"), waitFor:bp.Event(\"B2\")});\n" +
" }\n" +
"});\n" +
"\n" +
"bp.registerBThread(\"round-s2\", function(){\n" +
" while( true ) {\n" +
" bp.sync({waitFor:bp.Event(\"A\")});\n" +
" bp.sync({request:bp.Event(\"B2\"), waitFor:bp.Event(\"B1\")});\n" +
" }\n" +
"});");
DfsBProgramVerifier sut = new DfsBProgramVerifier();
final Set<String> foundTraces = new HashSet<>();
sut.addInspection( ExecutionTraceInspection.named("DFS trace captures", et->{
String eventTrace = et.getNodes().stream()
.map( n->n.getEvent() )
.map( o->o.map(BEvent::getName).orElse("-") )
.collect( joining("") );
System.out.println("eventTrace = " + eventTrace);
foundTraces.add(eventTrace);
return Optional.empty();
}));
sut.setVisitedStateStore( new BProgramSnapshotVisitedStateStore() );
sut.setProgressListener(new PrintDfsVerifierListener());
VerificationResult res = sut.verify(bprog);
assertEquals(4, res.getScannedStatesCount());
assertEquals(5, res.getScannedEdgesCount());
Set<String> expectedTraces = new TreeSet<>(Arrays.asList("-","A-","AB1-","AB1C","AB2-","AB2C"));
assertEquals("Traces don't match expected: " + foundTraces, expectedTraces, foundTraces );
}
@Test
public void testJavaScriptError() throws Exception {
BProgram bprog = new StringBProgram(
"bp.registerBThread( function(){\n"
+ " bp.sync({request:bp.Event(\"A\")});\n"
+ " bp.sync({request:bp.Event(\"A\")});\n"
+ " bp.sync({request:bp.Event(\"A\")});\n"
+ " var myNullVar;\n"
+ " myNullVar.isNullAndSoThisInvocationShouldCrash();\n"
+ " bp.sync({request:bp.Event(\"A\")});\n"
+ "});"
);
final AtomicBoolean errorCalled = new AtomicBoolean();
final AtomicBoolean errorMadeSense = new AtomicBoolean();
DfsBProgramVerifier sut = new DfsBProgramVerifier();
sut.setProgressListener(new DfsBProgramVerifier.ProgressListener() {
@Override public void started(DfsBProgramVerifier vfr) {}
@Override public void iterationCount(long count, long statesHit, DfsBProgramVerifier vfr) {}
@Override public void maxTraceLengthHit(ExecutionTrace aTrace, DfsBProgramVerifier vfr) {}
@Override public void done(DfsBProgramVerifier vfr) {}
@Override
public boolean violationFound(Violation aViolation, DfsBProgramVerifier vfr) {
errorCalled.set(aViolation instanceof JsErrorViolation );
JsErrorViolation jsev = (JsErrorViolation) aViolation;
errorMadeSense.set(jsev.decsribe().contains("isNullAndSoThisInvocationShouldCrash"));
System.out.println(jsev.getThrownException().getMessage());
return true;
}
});
sut.verify( bprog );
assertTrue( errorCalled.get() );
assertTrue( errorMadeSense.get() );
}
/**
* Test that even with forgetful storage, a circular trace does not get
* use to an infinite run.
* @throws java.lang.Exception
*/
@Test//(timeout=6000)
public void testCircularTraceDetection_forgetfulStorage() throws Exception {
String bprog = "bp.registerBThread(function(){\n"
+ "while (true) {\n"
+ " bp.sync({request:bp.Event(\"X\")});"
+ " bp.sync({request:bp.Event(\"Y\")});"
+ " bp.sync({request:bp.Event(\"Z\")});"
+ " bp.sync({request:bp.Event(\"W\")});"
+ " bp.sync({request:bp.Event(\"A\")});"
+ " bp.sync({request:bp.Event(\"B\")});"
+ "}"
+ "});";
DfsBProgramVerifier sut = new DfsBProgramVerifier();
sut.setVisitedStateStore( new ForgetfulVisitedStateStore() );
final AtomicInteger cycleToIndex = new AtomicInteger(Integer.MAX_VALUE);
final AtomicReference<String> lastEventName = new AtomicReference<>();
sut.addInspection(ExecutionTraceInspection.named("Cycle", t->{
if ( t.isCyclic() ) {
cycleToIndex.set( t.getCycleToIndex() );
lastEventName.set( t.getLastEvent().get().getName() );
System.out.println(TestUtils.traceEventNamesString(t, ", "));
}
return Optional.empty();
}));
VerificationResult res = sut.verify(new StringBProgram(bprog));
System.out.println("states: " + res.getScannedStatesCount());
assertEquals( 0, cycleToIndex.get() );
assertEquals( "B", lastEventName.get() );
}
@Test
public void testThreadStorageEquality() throws Exception {
BProgram program = new ResourceBProgram("hotColdThreadMonitor.js");
DfsBProgramVerifier sut = new DfsBProgramVerifier();
sut.setProgressListener(new PrintDfsVerifierListener());
VisitedStateStore stateStore = new BThreadSnapshotVisitedStateStore();
sut.setVisitedStateStore(stateStore);
VerificationResult res = sut.verify(program);
assertEquals( 9, res.getScannedStatesCount() );
assertEquals( 9, stateStore.getVisitedStateCount() );
}
}
|
bThink-BGU/BPjs
|
src/test/java/il/ac/bgu/cs/bp/bpjs/analysis/DfsBProgramVerifierTest.java
|
Java
|
mit
| 23,981 |
package org.graylog2.plugin.httpmonitor;
import org.graylog2.plugin.PluginConfigBean;
import org.graylog2.plugin.PluginModule;
import java.util.Collections;
import java.util.Set;
/**
* Extend the PluginModule abstract class here to add you plugin to the system.
*/
public class HttpMonitorInputModule extends PluginModule {
/**
* Returns all configuration beans required by this plugin.
*
* Implementing this method is optional. The default method returns an empty {@link Set}.
*/
// @Override
// public Set<? extends PluginConfigBean> getConfigBeans() {
// return Collections.emptySet();
// }
@Override
protected void configure() {
installTransport(transportMapBinder(),"http-monitor-transport",HttpMonitorTransport.class);
installInput(inputsMapBinder(), HttpMonitorInput.class, HttpMonitorInput.Factory.class);
}
}
|
sivasamyk/graylog2-plugin-input-httpmonitor
|
src/main/java/org/graylog2/plugin/httpmonitor/HttpMonitorInputModule.java
|
Java
|
mit
| 892 |
package io.picopalette.apps.event_me.Utils;
import android.annotation.SuppressLint;
import android.content.Context;
import android.support.design.widget.CoordinatorLayout;
import android.support.v7.widget.Toolbar;
import android.util.AttributeSet;
import android.view.View;
import com.facebook.drawee.view.SimpleDraweeView;
import io.picopalette.apps.event_me.R;
/**
* Created by Aswin Sundar on 14-06-2017.
*/
public class ImageBehaviour extends CoordinatorLayout.Behavior<SimpleDraweeView> {
private final static float MIN_AVATAR_PERCENTAGE_SIZE = 0.3f;
private final static int EXTRA_FINAL_AVATAR_PADDING = 80;
private final static String TAG = "behavior";
private final Context mContext;
private float mAvatarMaxSize;
private float mFinalLeftAvatarPadding;
private float mStartPosition;
private int mStartXPosition;
private float mStartToolbarPosition;
public ImageBehaviour(Context context, AttributeSet attrs) {
mContext = context;
init();
mFinalLeftAvatarPadding = context.getResources().getDimension(R.dimen.activity_horizontal_margin);
}
private void init() {
bindDimensions();
}
private void bindDimensions() {
mAvatarMaxSize = mContext.getResources().getDimension(R.dimen.image_width);
}
private int mStartYPosition;
private int mFinalYPosition;
private int finalHeight;
private int mStartHeight;
private int mFinalXPosition;
@Override
public boolean layoutDependsOn(CoordinatorLayout parent, SimpleDraweeView child, View dependency) {
return dependency instanceof Toolbar;
}
@Override
public boolean onDependentViewChanged(CoordinatorLayout parent, SimpleDraweeView child, View dependency) {
maybeInitProperties(child, dependency);
final int maxScrollDistance = (int) (mStartToolbarPosition - getStatusBarHeight());
float expandedPercentageFactor = dependency.getY() / maxScrollDistance;
float distanceYToSubtract = ((mStartYPosition - mFinalYPosition)
* (1f - expandedPercentageFactor)) + (child.getHeight()/2);
float distanceXToSubtract = ((mStartXPosition - mFinalXPosition)
* (1f - expandedPercentageFactor)) + (child.getWidth()/2);
float heightToSubtract = ((mStartHeight - finalHeight) * (1f - expandedPercentageFactor));
child.setY(mStartYPosition - distanceYToSubtract);
child.setX(mStartXPosition - distanceXToSubtract);
int proportionalAvatarSize = (int) (mAvatarMaxSize * (expandedPercentageFactor));
CoordinatorLayout.LayoutParams lp = (CoordinatorLayout.LayoutParams) child.getLayoutParams();
lp.width = (int) (mStartHeight - heightToSubtract);
lp.height = (int) (mStartHeight - heightToSubtract);
child.setLayoutParams(lp);
return true;
}
@SuppressLint("PrivateResource")
private void maybeInitProperties(SimpleDraweeView child, View dependency) {
if (mStartYPosition == 0)
mStartYPosition = (int) (dependency.getY());
if (mFinalYPosition == 0)
mFinalYPosition = (dependency.getHeight() /2);
if (mStartHeight == 0)
mStartHeight = child.getHeight();
if (finalHeight == 0)
finalHeight = mContext.getResources().getDimensionPixelOffset(R.dimen.image_small_width);
if (mStartXPosition == 0)
mStartXPosition = (int) (child.getX() + (child.getWidth() / 2));
if (mFinalXPosition == 0)
mFinalXPosition = mContext.getResources().getDimensionPixelOffset(R.dimen.abc_action_bar_content_inset_material) + (finalHeight / 2);
if (mStartToolbarPosition == 0)
mStartToolbarPosition = dependency.getY() + (dependency.getHeight()/2);
}
public int getStatusBarHeight() {
int result = 0;
int resourceId = mContext.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resourceId > 0) {
result = mContext.getResources().getDimensionPixelSize(resourceId);
}
return result;
}
}
|
picopalette/event-me
|
app/src/main/java/io/picopalette/apps/event_me/Utils/ImageBehaviour.java
|
Java
|
mit
| 4,149 |
package gea.api;
public class Api extends Thread{
}
|
acalvoa/GEA-FRAMEWORK
|
src/gea/api/Api.java
|
Java
|
mit
| 55 |
// Copyright (c) 2014 blinkbox Entertainment Limited. All rights reserved.
package com.blinkboxbooks.android.authentication;
import android.accounts.AbstractAccountAuthenticator;
import android.accounts.Account;
import android.accounts.AccountAuthenticatorResponse;
import android.accounts.AccountManager;
import android.accounts.NetworkErrorException;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import com.blinkboxbooks.android.api.BBBApiConstants;
import com.blinkboxbooks.android.api.model.BBBTokenResponse;
import com.blinkboxbooks.android.api.net.BBBRequest;
import com.blinkboxbooks.android.api.net.BBBRequestFactory;
import com.blinkboxbooks.android.api.net.BBBRequestManager;
import com.blinkboxbooks.android.api.net.BBBResponse;
import com.blinkboxbooks.android.controller.AccountController;
import com.blinkboxbooks.android.ui.account.LoginActivity;
import com.blinkboxbooks.android.util.LogUtils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
/**
* Implementation of AbstractAccountAuthenticator. Subclasses only need to override the getLaunchAuthenticatorActivityIntent() method to return an Intent which will launch
* an Activity which is a subclass of AccountAuthenticatorActivity
*/
public class BBBAuthenticator extends AbstractAccountAuthenticator {
private static final String TAG = BBBAuthenticator.class.getSimpleName();
private final Context mContext;
public BBBAuthenticator(Context context) {
super(context);
mContext = context;
}
/**
* {inheritDoc}
*/
public Bundle addAccount(AccountAuthenticatorResponse accountAuthenticatorResponse, String accountType, String authTokenType, String[] requiredFeatures, Bundle options) throws NetworkErrorException {
Intent intent = new Intent(mContext, LoginActivity.class);
intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, accountAuthenticatorResponse);
Bundle bundle = new Bundle();
bundle.putParcelable(AccountManager.KEY_INTENT, intent);
return bundle;
}
/**
* {inheritDoc}
*/
public Bundle confirmCredentials(AccountAuthenticatorResponse accountAuthenticatorResponse, Account account, Bundle options) throws NetworkErrorException {
return null;
}
/**
* {inheritDoc}
*/
public Bundle editProperties(AccountAuthenticatorResponse accountAuthenticatorResponse, String accountType) {
throw new UnsupportedOperationException();
}
/**
* {inheritDoc}
*/
public Bundle getAuthToken(AccountAuthenticatorResponse accountAuthenticatorResponse, Account account, String authTokenType, Bundle options) throws NetworkErrorException {
AccountManager am = AccountManager.get(mContext);
//first check to see if we already have an access token in the AccountManager cache
String accessToken = am.peekAuthToken(account, authTokenType);
if (accessToken != null) {
Bundle result = new Bundle();
result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
result.putString(AccountManager.KEY_ACCOUNT_TYPE, account.type);
result.putString(AccountManager.KEY_AUTHTOKEN, accessToken);
return result;
}
//if we don't have a valid access token we try and get a new one with the refresh token
String refreshToken = am.getUserData(account, BBBApiConstants.PARAM_REFRESH_TOKEN);
String clientId = am.getUserData(account, BBBApiConstants.PARAM_CLIENT_ID);
String clientSecret = am.getUserData(account, BBBApiConstants.PARAM_CLIENT_SECRET);
if (!TextUtils.isEmpty(refreshToken)) {
BBBRequest request = BBBRequestFactory.getInstance().createGetRefreshAuthTokenRequest(refreshToken, clientId, clientSecret);
BBBResponse response = BBBRequestManager.getInstance().executeRequestSynchronously(request);
if (response == null) {
throw new NetworkErrorException("Could not get auth token with refresh token");
}
String json = response.getResponseData();
BBBTokenResponse authenticationResponse = null;
if (json != null) {
try {
authenticationResponse = new Gson().fromJson(json, BBBTokenResponse.class);
} catch (JsonSyntaxException e) {
LogUtils.d(TAG, e.getMessage(), e);
}
}
if (authenticationResponse != null) {
accessToken = authenticationResponse.access_token;
refreshToken = authenticationResponse.refresh_token;
if (!TextUtils.isEmpty(accessToken)) {
Bundle result = new Bundle();
result.putString(AccountManager.KEY_ACCOUNT_NAME, account.name);
result.putString(AccountManager.KEY_ACCOUNT_TYPE, BBBApiConstants.AUTHTOKEN_TYPE);
result.putString(AccountManager.KEY_AUTHTOKEN, authenticationResponse.access_token);
AccountController.getInstance().setAccessToken(account, accessToken);
AccountController.getInstance().setRefreshToken(account, refreshToken);
return result;
}
}
}
//if we can't get an access token via the cache or by using the refresh token we must return an Intent which will launch an Activity allowing the user to perform manual authentication
Intent intent = new Intent(mContext, LoginActivity.class);
intent.putExtra(AccountManager.KEY_ACCOUNT_AUTHENTICATOR_RESPONSE, accountAuthenticatorResponse);
intent.putExtra(BBBApiConstants.PARAM_USERNAME, account.name);
intent.putExtra(BBBApiConstants.PARAM_AUTHTOKEN_TYPE, authTokenType);
Bundle bundle = new Bundle();
bundle.putParcelable(AccountManager.KEY_INTENT, intent);
return bundle;
}
/**
* {inheritDoc}
*/
public String getAuthTokenLabel(String authTokenType) {
//we don't need to display the authTokenType in the account manager so we return null
return null;
}
/**
* {inheritDoc}
*/
public Bundle hasFeatures(AccountAuthenticatorResponse accountAuthenticatorResponse, Account account, String[] features) throws NetworkErrorException {
Bundle result = new Bundle();
result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false);
return result;
}
/**
* {inheritDoc}
*/
public Bundle updateCredentials(AccountAuthenticatorResponse accountAuthenticatorResponse, Account account, String authTokenType, Bundle options) throws NetworkErrorException {
return null;
}
}
|
blinkboxbooks/android-app
|
app/src/main/java/com/blinkboxbooks/android/authentication/BBBAuthenticator.java
|
Java
|
mit
| 6,858 |
package org.spongycastle.pqc.jcajce.provider.test;
import java.security.KeyPairGenerator;
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.Cipher;
import org.spongycastle.pqc.jcajce.spec.ECCKeyGenParameterSpec;
public class McElieceKobaraImaiCipherTest
extends AsymmetricHybridCipherTest
{
protected void setUp()
{
super.setUp();
try
{
kpg = KeyPairGenerator.getInstance("McElieceKobaraImai");
cipher = Cipher.getInstance("McElieceKobaraImaiWithSHA256");
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* Test encryption and decryption performance for SHA256 message digest and parameters
* m=11, t=50.
*/
public void testEnDecryption_SHA256_11_50()
throws Exception
{
// initialize key pair generator
AlgorithmParameterSpec kpgParams = new ECCKeyGenParameterSpec(11, 50);
kpg.initialize(kpgParams);
performEnDecryptionTest(1, 10, 32, null);
}
}
|
iseki-masaya/spongycastle
|
prov/src/test/java/org/spongycastle/pqc/jcajce/provider/test/McElieceKobaraImaiCipherTest.java
|
Java
|
mit
| 1,060 |
package com.github.scaronthesky.eternalwinterwars.view.entities;
public interface IMeasureableEntity {
public float getWidth();
public float getHeight();
}
|
hinogi/eternalwinterwars
|
src/com/github/scaronthesky/eternalwinterwars/view/entities/IMeasureableEntity.java
|
Java
|
mit
| 160 |
/*
* Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Sun designates this
* particular file as subject to the "Classpath" exception as provided
* by Sun in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package com.sun.source.util;
import com.sun.source.tree.CompilationUnitTree;
import javax.lang.model.element.TypeElement;
import javax.tools.JavaFileObject;
/**
* Provides details about work that has been done by the Sun Java Compiler, javac.
*
* @author Jonathan Gibbons
* @since 1.6
*/
public final class TaskEvent
{
/**
* Kind of task event.
* @since 1.6
*/
public enum Kind {
/**
* For events related to the parsing of a file.
*/
PARSE,
/**
* For events relating to elements being entered.
**/
ENTER,
/**
* For events relating to elements being analyzed for errors.
**/
ANALYZE,
/**
* For events relating to class files being generated.
**/
GENERATE,
/**
* For events relating to overall annotaion processing.
**/
ANNOTATION_PROCESSING,
/**
* For events relating to an individual annotation processing round.
**/
ANNOTATION_PROCESSING_ROUND
};
public TaskEvent(Kind kind) {
this(kind, null, null, null);
}
public TaskEvent(Kind kind, JavaFileObject sourceFile) {
this(kind, sourceFile, null, null);
}
public TaskEvent(Kind kind, CompilationUnitTree unit) {
this(kind, unit.getSourceFile(), unit, null);
}
public TaskEvent(Kind kind, CompilationUnitTree unit, TypeElement clazz) {
this(kind, unit.getSourceFile(), unit, clazz);
}
private TaskEvent(Kind kind, JavaFileObject file, CompilationUnitTree unit, TypeElement clazz) {
this.kind = kind;
this.file = file;
this.unit = unit;
this.clazz = clazz;
}
public Kind getKind() {
return kind;
}
public JavaFileObject getSourceFile() {
return file;
}
public CompilationUnitTree getCompilationUnit() {
return unit;
}
public TypeElement getTypeElement() {
return clazz;
}
public String toString() {
return "TaskEvent["
+ kind + ","
+ file + ","
// the compilation unit is identified by the file
+ clazz + "]";
}
private Kind kind;
private JavaFileObject file;
private CompilationUnitTree unit;
private TypeElement clazz;
}
|
daniel-beck/sorcerer
|
javac/src/main/java/com/sun/source/util/TaskEvent.java
|
Java
|
mit
| 3,433 |
package com.raoulvdberge.refinedstorage.block.enums;
import net.minecraft.util.IStringSerializable;
public enum ControllerType implements IStringSerializable {
NORMAL(0, "normal"),
CREATIVE(1, "creative");
private int id;
private String name;
ControllerType(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public String getName() {
return name;
}
public int getId() {
return id;
}
@Override
public String toString() {
return name;
}
}
|
way2muchnoise/refinedstorage
|
src/main/java/com/raoulvdberge/refinedstorage/block/enums/ControllerType.java
|
Java
|
mit
| 557 |
/***************************************************************************
* Copyright (C) 2006 by Arnaud Desaedeleer *
* arnaud@desaedeleer.com *
* *
* This file is part of OpenOMR *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
package openomr.omr_engine;
import java.awt.image.BufferedImage;
/**
* The <code> XProjection </code> class will calculate the X-Projection of an image. The constructor
* is given a <code> BufferedImage </code> and then the <code> calcXProjection </method> is invoked
* to calculate the X-Projection of the <code> BufferedImage </code>.
* <p>
* The <code> XProjection </code> class is used as follows:
* <p>
* <code>
* XProjection xProj = new XProjection(BufferedImage); <br>
* xProj.calcXProjection(startH, endH, startW, endW); <br>
* </code>
* <p>
* Calling the <code> calcXProjection </code> method will place the X-Projection of the <code> BufferedImage </code>
* in a int[] array which can be obtained by calling the <code> getYProjection </code> method.
* <p>
*
* @author Arnaud Desaedeleer
* @version 1.0
*/
public class XProjection
{
private int xProjection[];
private int size;
private BufferedImage buffImage;
public XProjection(BufferedImage buffImage)
{
this.buffImage = buffImage;
}
/**
* Cacluate the X-Projection of the BufferedImage
* @param startH Desired start Y-Coordinate of the BufferedImage
* @param endH Desired end Y-Coordinate of the BufferedImage
* @param startW Desired start X-Coordinate of the BufferedImage
* @param endW Desired end X-Coordinate of the BufferedImage
*/
public void calcXProjection(int startH, int endH, int startW, int endW)
{
int size = Math.abs(endW - startW) + 1;
//System.out.println("Size: " + size);
this.size = size;
xProjection = new int[size];
for (int i = startW; i < endW; i += 1)
{
for (int j = startH; j < endH; j += 1)
{
int color = 0;
try
{
color = buffImage.getRGB(i, j);
}
catch (ArrayIndexOutOfBoundsException e)
{
}
if (color != -1) //if black pixel
{
xProjection[i-startW] += 1;
}
}
}
}
/**
* Returns the resulting X-Projection of the BufferedImage
* @return xProjection
*/
public int[] getXProjection()
{
return xProjection;
}
/**
* Prints the X-Projection of the BufferedImage
*
*/
public void printXProjection()
{
System.out.println("X Projection");
for (int i=0; i<size; i+=1)
{
System.out.println(xProjection[i]);
}
System.out.println("END X Projection");
}
}
|
nayan92/ic-hack
|
OpenOMR/openomr/omr_engine/XProjection.java
|
Java
|
mit
| 4,106 |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.eventgrid.v2020_04_01_preview;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
/**
* NumberGreaterThanOrEquals Advanced Filter.
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "operatorType", defaultImpl = NumberGreaterThanOrEqualsAdvancedFilter.class)
@JsonTypeName("NumberGreaterThanOrEquals")
public class NumberGreaterThanOrEqualsAdvancedFilter extends AdvancedFilter {
/**
* The filter value.
*/
@JsonProperty(value = "value")
private Double value;
/**
* Get the filter value.
*
* @return the value value
*/
public Double value() {
return this.value;
}
/**
* Set the filter value.
*
* @param value the value value to set
* @return the NumberGreaterThanOrEqualsAdvancedFilter object itself.
*/
public NumberGreaterThanOrEqualsAdvancedFilter withValue(Double value) {
this.value = value;
return this;
}
}
|
selvasingh/azure-sdk-for-java
|
sdk/eventgrid/mgmt-v2020_04_01_preview/src/main/java/com/microsoft/azure/management/eventgrid/v2020_04_01_preview/NumberGreaterThanOrEqualsAdvancedFilter.java
|
Java
|
mit
| 1,359 |
package derpstream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.PriorityQueue;
import java.util.TimerTask;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author Mads
*/
public final class ChunkInfo extends TimerTask {
private static final Logger LOGGER = Logger.getLogger("derpstream");
private static final int BUFFER_PIECES = 3;
private final StreamInfo streamInfo;
private final DerpStream derpStream;
// Template for generating chunk links
private final String chunkPath;
private final LinkedBlockingDeque<Piece> pieceQueue = new LinkedBlockingDeque<>();
private final PriorityQueue<Piece> bufferedPieces = new PriorityQueue<>();
private long nextPieceTime; // when next piece becomes available
private int maxValidPiece; // maximum valid piece that can be requested
private int writePiece; // next piece to be written to disk.
private final Object waitObj = new Object();
ChunkInfo(DerpStream derpStream, StreamInfo streamInfo) throws IOException {
this.streamInfo = streamInfo;
this.derpStream = derpStream;
// Download chunklist
LOGGER.info("Getting latest chunklist...");
String chunkList = DerpStream.downloadString(streamInfo.getChunkInfoPath());
if(!DerpStream.isM3U(chunkList)) throw new IllegalStateException("Invalid chunklist: " + chunkList);
// Parse current chunk index
String search = "#EXT-X-MEDIA-SEQUENCE:";
int start = chunkList.indexOf(search) + search.length();
int end = chunkList.indexOf("\n", start);
maxValidPiece = Integer.parseInt(chunkList.substring(start, end));
writePiece = maxValidPiece - BUFFER_PIECES;
LOGGER.info("Ok. Stream is at piece " + maxValidPiece + "\n");
// Figure out chunkPath template
String[] lines = chunkList.split("\n");
String chunkPath = null;
for (String line : lines) {
if(!line.startsWith("#")) {
if(line.contains(""+maxValidPiece)) {
chunkPath = line.replace("" + maxValidPiece, "%d");
LOGGER.info("Setting chunkpath: " + chunkPath);
break;
}
}
}
if(chunkPath == null) throw new IllegalStateException("Couldn't find chunkPath");
this.chunkPath = chunkPath;
// Enqueue valid pieces
for (int i = 0; i < BUFFER_PIECES; i++) {
pieceQueue.add(makePiece(writePiece+i));
}
// 10 seconds to next piece becomes available
nextPieceTime = System.currentTimeMillis() + 10000;
}
// Increments the piece counter for every 10 seconds since start.
public void updatePiece() {
long time = System.currentTimeMillis();
while(time >= nextPieceTime) {
nextPieceTime += 10000;
pieceQueue.add(makePiece(maxValidPiece));
DerpStreamCallbacks callbacks = derpStream.getCallbacks();
if(callbacks != null) {
callbacks.pieceAvailable(maxValidPiece);
}
maxValidPiece++;
}
}
public String getChunkPath() {
return String.format(chunkPath, writePiece);
}
private Piece makePiece(int index) {
return new Piece(index, String.format(chunkPath, index));
}
@Override
public void run() {
// Update pieces
updatePiece();
}
void lostPiece(Piece p) {
synchronized(bufferedPieces) {
bufferedPieces.add(p);
}
synchronized(waitObj) {
waitObj.notify();
}
}
public void registerPiece(Piece p) {
synchronized(bufferedPieces) {
bufferedPieces.add(p);
}
synchronized(waitObj) {
waitObj.notify();
}
}
public Piece grabWork() throws InterruptedException {
return pieceQueue.takeFirst();
}
void startWriting(FileOutputStream fos) throws IOException {
DerpStreamCallbacks callbacks = derpStream.getCallbacks();
while(derpStream.isRunning()) {
// Write data to the file as it becomes available.
synchronized(bufferedPieces) {
while(bufferedPieces.size() > 0) {
Piece topPiece = bufferedPieces.peek();
// Not what we're looking for?
if(topPiece.pieceIndex != writePiece) break;
// Grab it!
Piece removedPiece = bufferedPieces.poll();
// Check it!
if(removedPiece != topPiece) throw new RuntimeException("Huh?");
if(topPiece.data != null) {
LOGGER.fine("Writing " + topPiece);
// Write it!
fos.getChannel().write(topPiece.data);
if(callbacks != null) {
callbacks.finishedWriting(topPiece.pieceIndex);
}
} else {
LOGGER.warning("Skipping " + topPiece);
if(callbacks != null) {
callbacks.skippedWriting(topPiece.pieceIndex);
}
}
writePiece++;
}
}
synchronized(waitObj) {
try {
waitObj.wait(5000);
} catch (InterruptedException ex) {
}
}
}
}
}
|
maesse/DerpStream
|
src/derpstream/ChunkInfo.java
|
Java
|
mit
| 5,842 |
package cn.honjow.leanc.ui.Fragment;
import cn.honjow.leanc.adapter.QuestionListAdapter;
import cn.honjow.leanc.ui.Activice.ChoQueActivity;
import cn.droidlover.xdroidmvp.base.SimpleRecAdapter;
import cn.honjow.leanc.model.QuestionItem;
import cn.honjow.leanc.ui.BaseLeancFragment;
import cn.droidlover.xrecyclerview.RecyclerItemCallback;
import cn.droidlover.xrecyclerview.XRecyclerView;
/**
* Created by honjow311 on 2017/5/17.
*/
public class ChoQueListFragment extends BaseLeancFragment {
QuestionListAdapter adapter;
@Override
public SimpleRecAdapter getAdapter() {
if (adapter == null) {
adapter = new QuestionListAdapter(context);
adapter.setRecItemClick(new RecyclerItemCallback<QuestionItem, QuestionListAdapter.ViewHolder>() {
@Override
public void onItemClick(int position, QuestionItem model, int tag, QuestionListAdapter.ViewHolder holder) {
super.onItemClick(position, model, tag, holder);
switch (tag) {
case QuestionListAdapter.TAG_VIEW:
ChoQueActivity.launch(context, model);
break;
}
}
});
}
return adapter;
}
@Override
public void setLayoutManager(XRecyclerView recyclerView) {
recyclerView.verticalLayoutManager(context);
}
@Override
public String getType() {
return "1";
}
public static ChoQueListFragment newInstance() {
return new ChoQueListFragment();
}
}
|
honjow/XDroidMvp_hzw
|
app/src/main/java/cn/honjow/leanc/ui/Fragment/ChoQueListFragment.java
|
Java
|
mit
| 1,611 |
package joshie.progression.api.gui;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
/** Implement this on rewards, triggers, filters, conditions,
* if you wish to draw something special on them, other than default fields. */
public interface ICustomDrawGuiDisplay {
@SideOnly(Side.CLIENT)
public void drawDisplay(IDrawHelper helper, int renderX, int renderY, int mouseX, int mouseY);
}
|
joshiejack/Progression
|
src/main/java/joshie/progression/api/gui/ICustomDrawGuiDisplay.java
|
Java
|
mit
| 449 |
package edu.gatech.nutrack;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.support.v4.app.NavUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class Home extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
public void callScan(View view) {
Intent callScanIntent = new Intent(this, NutritionixActivity.class);
startActivity(callScanIntent);
}
public void callTrack(View view) {
Intent callTrackIntent = new Intent(this, Track.class);
startActivity(callTrackIntent);
}
public void callSync(View view) {
Intent callSyncIntent = new Intent(this, Sync.class);
startActivity(callSyncIntent);
}
public void callReco(View view) {
Intent callRecoIntent = new Intent(this, Reco.class);
startActivity(callRecoIntent);
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.action_scan:
Intent callScanIntent = new Intent(this, NutritionixActivity.class);
startActivity(callScanIntent);
return true;
case R.id.action_track:
Intent callTrackIntent = new Intent(this, Track.class);
startActivity(callTrackIntent);
return true;
case R.id.action_reco:
Intent callReco = new Intent(this, Track.class);
startActivity(callReco);
return true;
case R.id.action_nutrition_info:
Intent callNutritionInfo = new Intent(this, Track.class);
startActivity(callNutritionInfo);
return true;
case R.id.action_log_out:
callLogout(item.getActionView());
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// log out. Every activity should have this method!
public void callLogout(View view) {
Intent callLoginIntent = new Intent(this, Login.class);
startActivity(callLoginIntent);
}
}
|
i3l/NuTrack
|
src/edu/gatech/nutrack/Home.java
|
Java
|
mit
| 2,842 |
package com.dgex.offspring.nxtCore.service;
import java.util.List;
import nxt.Account;
import nxt.Alias;
import nxt.Block;
import nxt.Transaction;
import com.dgex.offspring.nxtCore.core.TransactionHelper.IteratorAsList;
public interface IAccount {
public Account getNative();
public Long getId();
public String getStringId();
public long getBalance();
public long getUnconfirmedBalance();
public long getAssetBalance(Long assetId);
public long getUnconfirmedAssetBalance(Long assetId);
public String getPrivateKey();
public byte[] getPublicKey();
public List<ITransaction> getTransactions();
public List<Transaction> getNativeTransactions();
public List<Alias> getNativeAliases();
public List<Block> getForgedBlocks();
public List<IAlias> getAliases();
public List<IMessage> getMessages();
public List<IAsset> getIssuedAssets();
public int getForgedFee();
public boolean startForging();
public boolean stopForging();
public boolean isForging();
public boolean isReadOnly();
IteratorAsList getUserTransactions();
}
|
incentivetoken/offspring
|
com.dgex.offspring.nxtCore/src/com/dgex/offspring/nxtCore/service/IAccount.java
|
Java
|
mit
| 1,085 |
package com.bitdubai.fermat_api.layer.dmp_basic_wallet.common.enums;
/**
* Created by natalia on 06/07/15.
*/
public enum BalanceType {
AVAILABLE("AVAILABLE"),
BOOK("BOOK");
private final String code;
BalanceType(String code) {
this.code = code;
}
public String getCode() { return this.code ; }
public static BalanceType getByCode(String code) {
switch (code) {
case "BOOK": return BOOK;
case "AVAILABLE": return AVAILABLE;
default: return AVAILABLE;
}
}
}
|
fvasquezjatar/fermat-unused
|
fermat-api/src/main/java/com/bitdubai/fermat_api/layer/dmp_basic_wallet/common/enums/BalanceType.java
|
Java
|
mit
| 574 |
package org.shenit.tutorial.android;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class HelloWorldActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello_world);
}
}
|
jgnan/edu
|
android/AndroidTutorial/app/src/main/java/org/shenit/tutorial/android/HelloWorldActivity.java
|
Java
|
mit
| 353 |
package com.sinovoice.pathfinder.hcicloud.hwr;
import android.content.Context;
import android.util.Log;
import com.sinovoice.hcicloudsdk.api.hwr.HciCloudHwr;
import com.sinovoice.hcicloudsdk.common.hwr.HwrInitParam;
import com.sinovoice.pathfinder.hcicloud.sys.SysConfig;
public class HciCloudHwrHelper {
private static final String TAG = HciCloudHwrHelper.class.getSimpleName();
private static HciCloudHwrHelper mInstance;
private HciCloudHwrHelper() {
}
public static HciCloudHwrHelper getInstance() {
if (mInstance == null) {
mInstance = new HciCloudHwrHelper();
}
return mInstance;
}
/**
* HWRÊÖдʶ±ðÄÜÁ¦³õʼ»¯£¬·µ»ØµÄ´íÎóÂë¿ÉÒÔÔÚAPIÖÐHciErrorCode²é¿´
*
* @param context
* @return ´íÎóÂë, return 0 ±íʾ³É¹¦
*/
public int init(Context context) {
int initResult = 0;
// ¹¹ÔìHwr³õʼ»¯µÄ²ÎÊýÀàµÄʵÀý
HwrInitParam hwrInitParam = new HwrInitParam();
// »ñÈ¡AppÓ¦ÓÃÖеÄlibµÄ·¾¶,Èç¹ûʹÓÃ/data/data/pkgName/libϵÄ×ÊÔ´Îļþ,ÐèÒªÌí¼Óandroid_soµÄ±ê¼Ç
String hwrDirPath = context.getFilesDir().getAbsolutePath()
.replace("files", "lib");
hwrInitParam.addParam(HwrInitParam.PARAM_KEY_DATA_PATH, hwrDirPath);
hwrInitParam.addParam(HwrInitParam.PARAM_KEY_FILE_FLAG, "android_so");
hwrInitParam.addParam(HwrInitParam.PARAM_KEY_INIT_CAP_KEYS,
SysConfig.CAPKEY_HWR);
Log.d(TAG, "hwr init config: " + hwrInitParam.getStringConfig());
// HWR ³õʼ»¯
initResult = HciCloudHwr.hciHwrInit(hwrInitParam.getStringConfig());
return initResult;
}
/**
* HWRÊÖдʶ±ðÄÜÁ¦·´³õʼ»¯£¬·µ»ØµÄ´íÎóÂë¿ÉÒÔÔÚAPIÖÐHciErrorCode²é¿´
*
* @return ´íÎóÂë, return 0 ±íʾ³É¹¦
*/
public int release() {
int result = HciCloudHwr.hciHwrRelease();
return result;
}
}
|
open-sinovoice/sinovoice-pathfinder
|
Pathfinder/src/com/sinovoice/pathfinder/hcicloud/hwr/HciCloudHwrHelper.java
|
Java
|
mit
| 1,907 |
/*
* www.javagl.de - Flow
*
* Copyright (c) 2012-2017 Marco Hutter - http://www.javagl.de
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package de.javagl.flow.gui;
import java.awt.Shape;
import java.awt.geom.Line2D;
import java.awt.geom.PathIterator;
import java.util.ArrayList;
import java.util.List;
/**
* Utility methods related to shapes
*/
class Shapes
{
/**
* Create a list containing line segments that approximate the given
* shape.
*
* NOTE: Copied from https://github.com/javagl/Geom/blob/master/
* src/main/java/de/javagl/geom/Shapes.java
*
* @param shape The shape
* @param flatness The allowed flatness
* @return The list of line segments
*/
public static List<Line2D> computeLineSegments(
Shape shape, double flatness)
{
List<Line2D> result = new ArrayList<Line2D>();
PathIterator pi = shape.getPathIterator(null, flatness);
double[] coords = new double[6];
double previous[] = new double[2];
double first[] = new double[2];
while (!pi.isDone())
{
int segment = pi.currentSegment(coords);
switch (segment)
{
case PathIterator.SEG_MOVETO:
previous[0] = coords[0];
previous[1] = coords[1];
first[0] = coords[0];
first[1] = coords[1];
break;
case PathIterator.SEG_CLOSE:
result.add(new Line2D.Double(
previous[0], previous[1],
first[0], first[1]));
previous[0] = first[0];
previous[1] = first[1];
break;
case PathIterator.SEG_LINETO:
result.add(new Line2D.Double(
previous[0], previous[1],
coords[0], coords[1]));
previous[0] = coords[0];
previous[1] = coords[1];
break;
case PathIterator.SEG_QUADTO:
// Should never occur
throw new AssertionError(
"SEG_QUADTO in flattened path!");
case PathIterator.SEG_CUBICTO:
// Should never occur
throw new AssertionError(
"SEG_CUBICTO in flattened path!");
default:
// Should never occur
throw new AssertionError(
"Invalid segment in flattened path!");
}
pi.next();
}
return result;
}
/**
* Private constructor to prevent instantiation
*/
private Shapes()
{
// Private constructor to prevent instantiation
}
}
|
javagl/Flow
|
flow-gui/src/main/java/de/javagl/flow/gui/Shapes.java
|
Java
|
mit
| 4,028 |
package net.ausiasmarch.fartman.util;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
/**
* AudioManager.java
* Gestiona la musica y sonidos
* @author Luis
*
*/
public class AudioManager {
/** Administrador de audio */
public static final AudioManager instance = new AudioManager();
/** Musica reproduciendose*/
private Music playingMusic;
/** singleton: previene la instanciacion desde otras clases */
private AudioManager () {
}
/** Reproduce sonido */
public void play (Sound sound) {
play(sound, 1);
}
/** Reproduce sonido */
public void play (Sound sound, float volume) {
play(sound, volume, 1);
}
/** Reproduce sonido */
public void play (Sound sound, float volume, float pitch) {
play(sound, volume, pitch, 0);
}
/** Reproduce sonido */
public void play (Sound sound, float volume, float pitch, float pan) {
if (!GamePreferences.instance.sound) return;
sound.play(volume, pitch, pan);
}
/** Reproduce musica */
public void play(Music music){
play(music, 1);
}
/** Reproduce musica */
public void play (Music music, float volume) {
stopMusic();
playingMusic = music;
if (GamePreferences.instance.music) {
music.setLooping(true);
music.setVolume(volume);
music.play();
}
}
/** Para la musica */
public void stopMusic () {
if (playingMusic != null) playingMusic.stop();
}
/** Obtiene la musica que se esta reproduciendo */
public Music getPlayingMusic () {
return playingMusic;
}
/** Reproduce/pausa la musica segun el archivo de preferencias */
public void onSettingsUpdated () {
if (playingMusic == null) return;
if (GamePreferences.instance.music) {
if (!playingMusic.isPlaying()) playingMusic.play();
} else {
playingMusic.pause();
}
}
}
|
fluted0g/Mr.Fartman
|
core/src/net/ausiasmarch/fartman/util/AudioManager.java
|
Java
|
mit
| 1,784 |
package creationalPattern.builder;
public abstract class ColdDrink implements Item {
public Packing packing() {
return new Bottle();
}
public abstract float price();
}
|
ajil/Java-Patterns
|
src/main/java/creationalPattern/builder/ColdDrink.java
|
Java
|
mit
| 192 |
/*
* generated by Xtext
*/
package co.edu.uniandes.mono.gesco.ui.contentassist.antlr;
import java.util.Collection;
import java.util.Collections;
import org.eclipse.xtext.AbstractRule;
import org.eclipse.xtext.ui.codetemplates.ui.partialEditing.IPartialContentAssistParser;
import org.eclipse.xtext.ui.editor.contentassist.antlr.FollowElement;
import org.eclipse.xtext.ui.editor.contentassist.antlr.internal.AbstractInternalContentAssistParser;
import org.eclipse.xtext.util.PolymorphicDispatcher;
/**
* @author Sebastian Zarnekow - Initial contribution and API
*/
@SuppressWarnings("restriction")
public class PartialDSLContentAssistParser extends DSLParser implements IPartialContentAssistParser {
private AbstractRule rule;
public void initializeFor(AbstractRule rule) {
this.rule = rule;
}
@Override
protected Collection<FollowElement> getFollowElements(AbstractInternalContentAssistParser parser) {
if (rule == null || rule.eIsProxy())
return Collections.emptyList();
String methodName = "entryRule" + rule.getName();
PolymorphicDispatcher<Collection<FollowElement>> dispatcher =
new PolymorphicDispatcher<Collection<FollowElement>>(methodName, 0, 0, Collections.singletonList(parser));
dispatcher.invoke();
return parser.getFollowElements();
}
}
|
lfmendivelso10/GescoFinal
|
DSL/co.edu.uniandes.mono.gesco.ui/src-gen/co/edu/uniandes/mono/gesco/ui/contentassist/antlr/PartialDSLContentAssistParser.java
|
Java
|
mit
| 1,288 |
package selector;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.util.EventObject;
class Barra
implements AdjustmentListener
{
SelectorApplet applet;
public Barra(SelectorApplet applet)
{
this.applet = applet;
}
public void adjustmentValueChanged(AdjustmentEvent e) {
Object obj = e.getSource();
if (obj == this.applet.sbElectrico)
this.applet.sbElectrico_adjustmentValueChanged(e);
else if (obj == this.applet.sbMagnetico)
this.applet.sbMagnetico_adjustmentValueChanged(e);
else
this.applet.sbVelocidad_adjustmentValueChanged(e);
}
}
|
Thaenor/magnetic-and-electric-forces-study
|
src/selector/Barra.java
|
Java
|
mit
| 659 |
package org.luaj.vm2;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
/**
* Debug helper class to pretty-print lua bytecodes.
* @see Prototype
* @see LuaClosure
*/
public class Print extends Lua
{
/** opcode names */
private static final String STRING_FOR_NULL = "null";
private static final String[] OPNAMES = {
"MOVE",
"LOADK",
"LOADBOOL",
"LOADNIL",
"GETUPVAL",
"GETGLOBAL",
"GETTABLE",
"SETGLOBAL",
"SETUPVAL",
"SETTABLE",
"NEWTABLE",
"SELF",
"ADD",
"SUB",
"MUL",
"DIV",
"MOD",
"POW",
"UNM",
"NOT",
"LEN",
"CONCAT",
"JMP",
"EQ",
"LT",
"LE",
"TEST",
"TESTSET",
"CALL",
"TAILCALL",
"RETURN",
"FORLOOP",
"FORPREP",
"TFORLOOP",
"SETLIST",
"CLOSE",
"CLOSURE",
"VARARG",
};
static void printString(PrintStream ps, LuaString s)
{
ps.print('"');
for(int i = 0, n = s._length; i < n; i++)
{
int c = s._bytes[s._offset + i];
if(c >= ' ' && c <= '~' && c != '\"' && c != '\\')
ps.print((char)c);
else
{
switch(c)
{
case '"':
ps.print("\\\"");
break;
case '\\':
ps.print("\\\\");
break;
case 0x0007: /* bell */
ps.print("\\a");
break;
case '\b': /* backspace */
ps.print("\\b");
break;
case '\f': /* form feed */
ps.print("\\f");
break;
case '\t': /* tab */
ps.print("\\t");
break;
case '\r': /* carriage return */
ps.print("\\r");
break;
case '\n': /* newline */
ps.print("\\n");
break;
case 0x000B: /* vertical tab */
ps.print("\\v");
break;
default:
ps.print('\\');
ps.print(Integer.toString(1000 + 0xff & c).substring(1));
break;
}
}
}
ps.print('"');
}
static void printValue(PrintStream ps, LuaValue v)
{
switch(v.type())
{
case LuaValue.TSTRING:
printString(ps, (LuaString)v);
break;
default:
ps.print(v.tojstring());
}
}
static void printConstant(PrintStream ps, Prototype f, int i)
{
printValue(ps, f.k[i]);
}
/**
* Print the code in a prototype
* @param f the {@link Prototype}
*/
public static void printCode(PrintStream ps, Prototype f)
{
int[] code = f.code;
int pc, n = code.length;
for(pc = 0; pc < n; pc++)
{
printOpCode(ps, f, pc);
ps.println();
}
}
/**
* Print an opcode in a prototype
* @param ps the {@link PrintStream} to print to
* @param f the {@link Prototype}
* @param pc the program counter to look up and print
*/
public static void printOpCode(PrintStream ps, Prototype f, int pc)
{
int[] code = f.code;
int i = code[pc];
int o = GET_OPCODE(i);
int a = GETARG_A(i);
int b = GETARG_B(i);
int c = GETARG_C(i);
int bx = GETARG_Bx(i);
int sbx = GETARG_sBx(i);
int line = getline(f, pc);
ps.print(" " + (pc + 1) + " ");
if(line > 0)
ps.print("[" + line + "] ");
else
ps.print("[-] ");
ps.print(OPNAMES[o] + " ");
switch(getOpMode(o))
{
case iABC:
ps.print(a);
if(getBMode(o) != OpArgN)
ps.print(" " + (ISK(b) ? (-1 - INDEXK(b)) : b));
if(getCMode(o) != OpArgN)
ps.print(" " + (ISK(c) ? (-1 - INDEXK(c)) : c));
break;
case iABx:
if(getBMode(o) == OpArgK)
{
ps.print(a + " " + (-1 - bx));
}
else
{
ps.print(a + " " + (bx));
}
break;
case iAsBx:
if(o == OP_JMP)
ps.print(sbx);
else
ps.print(a + " " + sbx);
break;
}
switch(o)
{
case OP_LOADK:
ps.print(" ; ");
printConstant(ps, f, bx);
break;
case OP_GETUPVAL:
case OP_SETUPVAL:
ps.print(" ; ");
if(f.upvalues.length > b)
printValue(ps, f.upvalues[b]);
else
ps.print("-");
break;
case OP_GETGLOBAL:
case OP_SETGLOBAL:
ps.print(" ; ");
printConstant(ps, f, bx);
break;
case OP_GETTABLE:
case OP_SELF:
if(ISK(c))
{
ps.print(" ; ");
printConstant(ps, f, INDEXK(c));
}
break;
case OP_SETTABLE:
case OP_ADD:
case OP_SUB:
case OP_MUL:
case OP_DIV:
case OP_POW:
case OP_EQ:
case OP_LT:
case OP_LE:
if(ISK(b) || ISK(c))
{
ps.print(" ; ");
if(ISK(b))
printConstant(ps, f, INDEXK(b));
else
ps.print("-");
ps.print(" ");
if(ISK(c))
printConstant(ps, f, INDEXK(c));
else
ps.print("-");
}
break;
case OP_JMP:
case OP_FORLOOP:
case OP_FORPREP:
ps.print(" ; to " + (sbx + pc + 2));
break;
case OP_CLOSURE:
ps.print(" ; " + f.p[bx].getClass().getName());
break;
case OP_SETLIST:
if(c == 0)
ps.print(" ; " + code[++pc]);
else
ps.print(" ; " + c);
break;
case OP_VARARG:
ps.print(" ; is_vararg=" + f.is_vararg);
break;
default:
break;
}
}
private static int getline(Prototype f, int pc)
{
return pc > 0 && f.lineinfo != null && pc < f.lineinfo.length ? f.lineinfo[pc] : -1;
}
static void printHeader(PrintStream ps, Prototype f)
{
String s = String.valueOf(f.source);
if(s.startsWith("@") || s.startsWith("="))
s = s.substring(1);
else if("\033Lua".equals(s))
s = "(bstring)";
else
s = "(string)";
String a = (f.linedefined == 0) ? "main" : "function";
ps.print("\n%" + a + " <" + s + ":" + f.linedefined + ","
+ f.lastlinedefined + "> (" + f.code.length + " instructions, "
+ f.code.length * 4 + " bytes at " + id() + ")\n");
ps.print(f.numparams + " param, " + f.maxstacksize + " slot, "
+ f.upvalues.length + " upvalue, ");
ps.print(f.locvars.length + " local, " + f.k.length
+ " constant, " + f.p.length + " function\n");
}
static void printConstants(PrintStream ps, Prototype f)
{
int i, n = f.k.length;
ps.print("constants (" + n + ") for " + id() + ":\n");
for(i = 0; i < n; i++)
{
ps.print(" " + (i + 1) + " ");
printValue(ps, f.k[i]);
ps.print("\n");
}
}
static void printLocals(PrintStream ps, Prototype f)
{
int i, n = f.locvars.length;
ps.print("locals (" + n + ") for " + id() + ":\n");
for(i = 0; i < n; i++)
{
ps.println(" " + i + " " + f.locvars[i]._varname + " " + (f.locvars[i]._startpc + 1) + " " + (f.locvars[i]._endpc + 1));
}
}
static void printUpValues(PrintStream ps, Prototype f)
{
int i, n = f.upvalues.length;
ps.print("upvalues (" + n + ") for " + id() + ":\n");
for(i = 0; i < n; i++)
{
ps.print(" " + i + " " + f.upvalues[i] + "\n");
}
}
public static void print(PrintStream ps, Prototype p)
{
printFunction(ps, p, true);
}
public static void printFunction(PrintStream ps, Prototype f, boolean full)
{
int i, n = f.p.length;
printHeader(ps, f);
printCode(ps, f);
if(full)
{
printConstants(ps, f);
printLocals(ps, f);
printUpValues(ps, f);
}
for(i = 0; i < n; i++)
printFunction(ps, f.p[i], full);
}
private static void format(PrintStream ps, String s, int maxcols)
{
int n = s.length();
if(n > maxcols)
ps.print(s.substring(0, maxcols));
else
{
ps.print(s);
for(int i = maxcols - n; --i >= 0;)
ps.print(' ');
}
}
private static String id()
{
return "Proto";
}
/**
* Print the state of a {@link LuaClosure} that is being executed
* @param cl the {@link LuaClosure}
* @param pc the program counter
* @param stack the stack of {@link LuaValue}
* @param top the top of the stack
* @param varargs any {@link Varargs} value that may apply
*/
public static void printState(LuaClosure cl, int pc, LuaValue[] stack, int top, Varargs varargs)
{
// print opcode into buffer
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
printOpCode(ps, cl._p, pc);
ps.flush();
ps.close();
ps = System.out;
format(ps, baos.toString(), 50);
// print stack
ps.print('[');
for(int i = 0; i < stack.length; i++)
{
LuaValue v = stack[i];
if(v == null)
ps.print(STRING_FOR_NULL);
else
switch(v.type())
{
case LuaValue.TSTRING:
LuaString s = v.checkstring();
ps.print(s.length() < 48 ?
s.tojstring() :
s.substring(0, 32).tojstring() + "...+" + (s.length() - 32) + "b");
break;
case LuaValue.TFUNCTION:
ps.print((v instanceof LuaClosure) ?
((LuaClosure)v)._p.toString() : v.tojstring());
break;
case LuaValue.TUSERDATA:
Object o = v.touserdata();
if(o != null)
{
String n = o.getClass().getName();
n = n.substring(n.lastIndexOf('.') + 1);
ps.print(n + ": " + Integer.toHexString(o.hashCode()));
}
else
{
ps.print(v.toString());
}
break;
default:
ps.print(v.tojstring());
}
if(i + 1 == top)
ps.print(']');
ps.print(" | ");
}
ps.print(varargs);
ps.println();
}
}
|
dwing4g/luaj
|
src/org/luaj/vm2/Print.java
|
Java
|
mit
| 10,612 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.