blob_id
stringlengths 40
40
| language
stringclasses 1
value | repo_name
stringlengths 5
132
| path
stringlengths 2
382
| src_encoding
stringclasses 34
values | length_bytes
int64 9
3.8M
| score
float64 1.5
4.94
| int_score
int64 2
5
| detected_licenses
listlengths 0
142
| license_type
stringclasses 2
values | text
stringlengths 9
3.8M
| download_success
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|
7099d69825205355a10756bc44eefa38d052484c
|
Java
|
Viktor-Vrublevski/jm_fixed
|
/src/main/java/com/javamentor/qa/platform/service/abstracts/dto/QuestionDtoService.java
|
UTF-8
| 1,004
| 1.859375
| 2
|
[] |
no_license
|
package com.javamentor.qa.platform.service.abstracts.dto;
import com.javamentor.qa.platform.models.dto.PageDto;
import com.javamentor.qa.platform.models.dto.QuestionDto;
import java.util.List;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
public interface QuestionDtoService {
Optional<QuestionDto> getQuestionDtoById(Long id);
PageDto<QuestionDto, Object> getPagination(int page, int size);
PageDto<QuestionDto, Object> getPaginationPopular(int page, int size, long days);
PageDto<QuestionDto, Object> getPaginationWithoutAnswers(int page, int size);
PageDto<QuestionDto, Object> getPaginationOrderedNew(int page, int size);
PageDto<QuestionDto, Object> getPAginationWithGivenTags(int page, int size, List<Long> tagIds);
PageDto<QuestionDto, Object> getPaginationWithoutTags(int page, int size, List<Long> tagIds);
PageDto<QuestionDto, Object> getQuestionBySearchValue(String message, int page, int size);
}
| true
|
34a4624e908d7b02260449f7a6851f1ae824253a
|
Java
|
proofy/pollo
|
/src/org/outerj/pollo/action/UserPreferencesAction.java
|
UTF-8
| 1,735
| 2.34375
| 2
|
[
"MIT"
] |
permissive
|
package org.outerj.pollo.action;
import org.outerj.pollo.*;
import org.outerj.pollo.util.ResourceManager;
import org.outerj.pollo.config.PolloConfiguration;
import org.outerj.pollo.gui.UserPreferencesDialog;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.Iterator;
/**
* Action that shows the user preferences dialog.
*/
public class UserPreferencesAction extends AbstractAction
{
protected PolloFrame polloFrame;
protected PolloConfiguration polloConfiguration;
public UserPreferencesAction(PolloFrame polloFrame, PolloConfiguration polloConfiguration)
{
this.polloFrame = polloFrame;
this.polloConfiguration = polloConfiguration;
final ResourceManager resourceManager = ResourceManager.getManager(UserPreferencesAction.class);
resourceManager.configureAction(this);
}
public void actionPerformed(ActionEvent e)
{
UserPreferencesDialog dialog = UserPreferencesDialog.getInstance();
dialog.readConfiguration(polloConfiguration);
if (dialog.showDialog(polloFrame))
{
dialog.storeConfiguration(polloConfiguration);
Pollo pollo = Pollo.getInstance();
Iterator openFramesIt = pollo.getOpenFrames().iterator();
while (openFramesIt.hasNext())
{
PolloFrame polloFrame = (PolloFrame)openFramesIt.next();
Iterator editorPanelIt = polloFrame.getEditorPanels().iterator();
while (editorPanelIt.hasNext())
{
EditorPanel editorPanel = (EditorPanel)editorPanelIt.next();
editorPanel.refreshUserPreferences();
}
}
}
}
}
| true
|
d2cd4c7c46b8e363613a1b7abc4ae46906afc5a4
|
Java
|
rosoareslv/SED99
|
/java/lucene-solr/2015/12/LeaderInitiatedRecoveryThread.java
|
UTF-8
| 17,106
| 1.835938
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.apache.solr.cloud;
import org.apache.http.NoHttpResponseException;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.request.CoreAdminRequest.RequestRecovery;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.SolrException.ErrorCode;
import org.apache.solr.common.cloud.Replica;
import org.apache.solr.common.cloud.ZkCoreNodeProps;
import org.apache.solr.common.cloud.ZkNodeProps;
import org.apache.solr.common.cloud.ZkStateReader;
import org.apache.solr.common.params.CoreAdminParams.CoreAdminAction;
import org.apache.solr.common.util.Utils;
import org.apache.solr.core.CoreContainer;
import org.apache.solr.core.CoreDescriptor;
import org.apache.zookeeper.KeeperException;
import org.apache.solr.util.RTimer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.invoke.MethodHandles;
import java.net.ConnectException;
import java.net.SocketException;
import java.util.List;
/*
* 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.
*/
/**
* Background daemon thread that tries to send the REQUESTRECOVERY to a downed
* replica; used by a shard leader to nag a replica into recovering after the
* leader experiences an error trying to send an update request to the replica.
*/
public class LeaderInitiatedRecoveryThread extends Thread {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
protected ZkController zkController;
protected CoreContainer coreContainer;
protected String collection;
protected String shardId;
protected ZkCoreNodeProps nodeProps;
protected int maxTries;
private CoreDescriptor leaderCd;
public LeaderInitiatedRecoveryThread(ZkController zkController,
CoreContainer cc,
String collection,
String shardId,
ZkCoreNodeProps nodeProps,
int maxTries,
CoreDescriptor leaderCd)
{
super("LeaderInitiatedRecoveryThread-"+nodeProps.getCoreName());
this.zkController = zkController;
this.coreContainer = cc;
this.collection = collection;
this.shardId = shardId;
this.nodeProps = nodeProps;
this.maxTries = maxTries;
this.leaderCd = leaderCd;
setDaemon(true);
}
public void run() {
RTimer timer = new RTimer();
String replicaCoreName = nodeProps.getCoreName();
String replicaCoreNodeName = ((Replica) nodeProps.getNodeProps()).getName();
String replicaNodeName = nodeProps.getNodeName();
final String replicaUrl = nodeProps.getCoreUrl();
if (!zkController.isReplicaInRecoveryHandling(replicaUrl)) {
throw new SolrException(ErrorCode.INVALID_STATE, "Replica: " + replicaUrl + " should have been marked under leader initiated recovery in ZkController but wasn't.");
}
boolean sendRecoveryCommand = publishDownState(replicaCoreName, replicaCoreNodeName, replicaNodeName, replicaUrl, false);
if (sendRecoveryCommand) {
try {
sendRecoveryCommandWithRetry();
} catch (Exception exc) {
log.error(getName()+" failed due to: "+exc, exc);
if (exc instanceof SolrException) {
throw (SolrException)exc;
} else {
throw new SolrException(ErrorCode.SERVER_ERROR, exc);
}
} finally {
zkController.removeReplicaFromLeaderInitiatedRecoveryHandling(replicaUrl);
}
} else {
// replica is no longer in recovery on this node (may be handled on another node)
zkController.removeReplicaFromLeaderInitiatedRecoveryHandling(replicaUrl);
}
log.info("{} completed successfully after running for {}ms", getName(), timer.getTime());
}
public boolean publishDownState(String replicaCoreName, String replicaCoreNodeName, String replicaNodeName, String replicaUrl, boolean forcePublishState) {
boolean sendRecoveryCommand = true;
boolean publishDownState = false;
if (zkController.getZkStateReader().getClusterState().liveNodesContain(replicaNodeName)) {
try {
// create a znode that requires the replica needs to "ack" to verify it knows it was out-of-sync
updateLIRState(replicaCoreNodeName);
log.info("Put replica core={} coreNodeName={} on " +
replicaNodeName + " into leader-initiated recovery.", replicaCoreName, replicaCoreNodeName);
publishDownState = true;
} catch (Exception e) {
Throwable setLirZnodeFailedCause = SolrException.getRootCause(e);
log.error("Leader failed to set replica " +
nodeProps.getCoreUrl() + " state to DOWN due to: " + setLirZnodeFailedCause, setLirZnodeFailedCause);
if (setLirZnodeFailedCause instanceof KeeperException.SessionExpiredException
|| setLirZnodeFailedCause instanceof KeeperException.ConnectionLossException
|| setLirZnodeFailedCause instanceof ZkController.NotLeaderException) {
// our session is expired, which means our state is suspect, so don't go
// putting other replicas in recovery (see SOLR-6511)
sendRecoveryCommand = false;
forcePublishState = false; // no need to force publish any state in this case
} // else will go ahead and try to send the recovery command once after this error
}
} else {
log.info("Node " + replicaNodeName +
" is not live, so skipping leader-initiated recovery for replica: core={} coreNodeName={}",
replicaCoreName, replicaCoreNodeName);
// publishDownState will be false to avoid publishing the "down" state too many times
// as many errors can occur together and will each call into this method (SOLR-6189)
forcePublishState = false; // no need to force publish the state because replica is not live
sendRecoveryCommand = false; // no need to send recovery messages as well
}
try {
if (publishDownState || forcePublishState) {
ZkNodeProps m = new ZkNodeProps(Overseer.QUEUE_OPERATION, "state",
ZkStateReader.STATE_PROP, Replica.State.DOWN.toString(),
ZkStateReader.BASE_URL_PROP, nodeProps.getBaseUrl(),
ZkStateReader.CORE_NAME_PROP, nodeProps.getCoreName(),
ZkStateReader.NODE_NAME_PROP, nodeProps.getNodeName(),
ZkStateReader.SHARD_ID_PROP, shardId,
ZkStateReader.COLLECTION_PROP, collection);
log.warn("Leader is publishing core={} coreNodeName ={} state={} on behalf of un-reachable replica {}",
replicaCoreName, replicaCoreNodeName, Replica.State.DOWN.toString(), replicaUrl);
zkController.getOverseerJobQueue().offer(Utils.toJSON(m));
}
} catch (Exception e) {
log.error("Could not publish 'down' state for replicaUrl: {}", replicaUrl, e);
}
return sendRecoveryCommand;
}
/*
protected scope for testing purposes
*/
protected void updateLIRState(String replicaCoreNodeName) {
zkController.updateLeaderInitiatedRecoveryState(collection,
shardId,
replicaCoreNodeName, Replica.State.DOWN, leaderCd, true);
}
protected void sendRecoveryCommandWithRetry() throws Exception {
int tries = 0;
long waitBetweenTriesMs = 5000L;
boolean continueTrying = true;
String replicaCoreName = nodeProps.getCoreName();
String recoveryUrl = nodeProps.getBaseUrl();
String replicaNodeName = nodeProps.getNodeName();
String coreNeedingRecovery = nodeProps.getCoreName();
String replicaCoreNodeName = ((Replica) nodeProps.getNodeProps()).getName();
String replicaUrl = nodeProps.getCoreUrl();
log.info(getName()+" started running to send REQUESTRECOVERY command to "+replicaUrl+
"; will try for a max of "+(maxTries * (waitBetweenTriesMs/1000))+" secs");
RequestRecovery recoverRequestCmd = new RequestRecovery();
recoverRequestCmd.setAction(CoreAdminAction.REQUESTRECOVERY);
recoverRequestCmd.setCoreName(coreNeedingRecovery);
while (continueTrying && ++tries <= maxTries) {
if (tries > 1) {
log.warn("Asking core={} coreNodeName={} on " + recoveryUrl +
" to recover; unsuccessful after "+tries+" of "+maxTries+" attempts so far ...", coreNeedingRecovery, replicaCoreNodeName);
} else {
log.info("Asking core={} coreNodeName={} on " + recoveryUrl + " to recover", coreNeedingRecovery, replicaCoreNodeName);
}
try (HttpSolrClient client = new HttpSolrClient(recoveryUrl)) {
client.setSoTimeout(60000);
client.setConnectionTimeout(15000);
try {
client.request(recoverRequestCmd);
log.info("Successfully sent " + CoreAdminAction.REQUESTRECOVERY +
" command to core={} coreNodeName={} on " + recoveryUrl, coreNeedingRecovery, replicaCoreNodeName);
continueTrying = false; // succeeded, so stop looping
} catch (Exception t) {
Throwable rootCause = SolrException.getRootCause(t);
boolean wasCommError =
(rootCause instanceof ConnectException ||
rootCause instanceof ConnectTimeoutException ||
rootCause instanceof NoHttpResponseException ||
rootCause instanceof SocketException);
SolrException.log(log, recoveryUrl + ": Could not tell a replica to recover", t);
if (!wasCommError) {
continueTrying = false;
}
}
}
// wait a few seconds
if (continueTrying) {
try {
Thread.sleep(waitBetweenTriesMs);
} catch (InterruptedException ignoreMe) {
Thread.currentThread().interrupt();
}
if (coreContainer.isShutDown()) {
log.warn("Stop trying to send recovery command to downed replica core={} coreNodeName={} on "
+ replicaNodeName + " because my core container is closed.", coreNeedingRecovery, replicaCoreNodeName);
continueTrying = false;
break;
}
// see if the replica's node is still live, if not, no need to keep doing this loop
ZkStateReader zkStateReader = zkController.getZkStateReader();
try {
zkStateReader.updateClusterState();
} catch (Exception exc) {
log.warn("Error when updating cluster state: "+exc);
}
if (!zkStateReader.getClusterState().liveNodesContain(replicaNodeName)) {
log.warn("Node "+replicaNodeName+" hosting core "+coreNeedingRecovery+
" is no longer live. No need to keep trying to tell it to recover!");
continueTrying = false;
break;
}
String leaderCoreNodeName = leaderCd.getCloudDescriptor().getCoreNodeName();
// stop trying if I'm no longer the leader
if (leaderCoreNodeName != null && collection != null) {
String leaderCoreNodeNameFromZk = null;
try {
leaderCoreNodeNameFromZk = zkController.getZkStateReader().getLeaderRetry(collection, shardId, 1000).getName();
} catch (Exception exc) {
log.error("Failed to determine if " + leaderCoreNodeName + " is still the leader for " + collection +
" " + shardId + " before starting leader-initiated recovery thread for " + replicaUrl + " due to: " + exc);
}
if (!leaderCoreNodeName.equals(leaderCoreNodeNameFromZk)) {
log.warn("Stop trying to send recovery command to downed replica core=" + coreNeedingRecovery +
",coreNodeName=" + replicaCoreNodeName + " on " + replicaNodeName + " because " +
leaderCoreNodeName + " is no longer the leader! New leader is " + leaderCoreNodeNameFromZk);
continueTrying = false;
break;
}
if (!leaderCd.getCloudDescriptor().isLeader()) {
log.warn("Stop trying to send recovery command to downed replica core=" + coreNeedingRecovery +
",coreNodeName=" + replicaCoreNodeName + " on " + replicaNodeName + " because " +
leaderCoreNodeName + " is no longer the leader!");
continueTrying = false;
break;
}
}
// additional safeguard against the replica trying to be in the active state
// before acknowledging the leader initiated recovery command
if (collection != null && shardId != null) {
try {
// call out to ZooKeeper to get the leader-initiated recovery state
final Replica.State lirState = zkController.getLeaderInitiatedRecoveryState(collection, shardId, replicaCoreNodeName);
if (lirState == null) {
log.warn("Stop trying to send recovery command to downed replica core="+coreNeedingRecovery+
",coreNodeName=" + replicaCoreNodeName + " on "+replicaNodeName+" because the znode no longer exists.");
continueTrying = false;
break;
}
if (lirState == Replica.State.RECOVERING) {
// replica has ack'd leader initiated recovery and entered the recovering state
// so we don't need to keep looping to send the command
continueTrying = false;
log.info("Replica "+coreNeedingRecovery+
" on node "+replicaNodeName+" ack'd the leader initiated recovery state, "
+ "no need to keep trying to send recovery command");
} else {
String lcnn = zkStateReader.getLeaderRetry(collection, shardId, 5000).getName();
List<ZkCoreNodeProps> replicaProps =
zkStateReader.getReplicaProps(collection, shardId, lcnn);
if (replicaProps != null && replicaProps.size() > 0) {
for (ZkCoreNodeProps prop : replicaProps) {
final Replica replica = (Replica) prop.getNodeProps();
if (replicaCoreNodeName.equals(replica.getName())) {
if (replica.getState() == Replica.State.ACTIVE) {
// replica published its state as "active",
// which is bad if lirState is still "down"
if (lirState == Replica.State.DOWN) {
// OK, so the replica thinks it is active, but it never ack'd the leader initiated recovery
// so its state cannot be trusted and it needs to be told to recover again ... and we keep looping here
log.warn("Replica core={} coreNodeName={} set to active but the leader thinks it should be in recovery;"
+ " forcing it back to down state to re-run the leader-initiated recovery process; props: " + replicaProps.get(0), coreNeedingRecovery, replicaCoreNodeName);
publishDownState(replicaCoreName, replicaCoreNodeName, replicaNodeName, replicaUrl, true);
}
}
break;
}
}
}
}
} catch (Exception ignoreMe) {
log.warn("Failed to determine state of core={} coreNodeName={} due to: "+ignoreMe, coreNeedingRecovery, replicaCoreNodeName);
// eventually this loop will exhaust max tries and stop so we can just log this for now
}
}
}
}
// replica is no longer in recovery on this node (may be handled on another node)
zkController.removeReplicaFromLeaderInitiatedRecoveryHandling(replicaUrl);
if (continueTrying) {
// ugh! this means the loop timed out before the recovery command could be delivered
// how exotic do we want to get here?
log.error("Timed out after waiting for "+(tries * (waitBetweenTriesMs/1000))+
" secs to send the recovery request to: "+replicaUrl+"; not much more we can do here?");
// TODO: need to raise a JMX event to allow monitoring tools to take over from here
}
}
}
| true
|
7096fc4dea399bca5fc4d0e4acf345fb79233188
|
Java
|
epotters/poc
|
/poc-jobs/src/main/java/poc/jobs/collectors/UserAccount.java
|
UTF-8
| 202
| 1.757813
| 2
|
[] |
no_license
|
package poc.jobs.collectors;
import lombok.Data;
@Data
public class UserAccount {
private String displayName;
private String username;
private String password;
private AccountType type;
}
| true
|
815c6c930ea1600728f9e6c8fa8039bc2b86644e
|
Java
|
faruk-becirovic/UniversalConverter
|
/src/Converter.java
|
UTF-8
| 570
| 3.484375
| 3
|
[] |
no_license
|
public class Converter {
public static double kgToLb(double kg) {
double lbs = kg * 2.2046;
return lbs;
}
public static double lbToKg(double lbs) {
double kg = lbs / 2.2046;
return kg;
}
public static double cmToInch(double cm) {
return (cm/2.54);
}
public static double inchToCm(double inch) {
return (inch*2.54);
}
public static double celsiusToFahrenheit(double c) {
return c*1.8+32;
}
public static double fahrenheitToCelsius(double f) {
return (f-32)/1.8;
}
public static void main(String[] args) {
}
}
| true
|
4d37279fea68fed0c830249b3c8d6270a7fd4422
|
Java
|
github-is-too-slow/cloud2021
|
/cloud-consumer-orderhytrix80/src/main/java/com/billion/springcloud/service/OrderService.java
|
UTF-8
| 655
| 1.835938
| 2
|
[] |
no_license
|
package com.billion.springcloud.service;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
/**
* @author Billion
* @create 2021/04/28 22:49
*/
@Service
@FeignClient(name = "CLOUD-PAYMENT-SERVICE", fallback = OrderFallbackService.class)
public interface OrderService {
@GetMapping("/payment/hythrix/ok/{id}")
String getInfoOk(@PathVariable("id") Integer id);
@GetMapping("/payment/hythrix/timeout/{id}")
String getInfoTimeout(@PathVariable("id") Integer id);
}
| true
|
9473a6bc7678facbc817bffcd13305d072fea01a
|
Java
|
fy-kenny/demo6
|
/src/main/java/com/example/demo6/model/StudentWork.java
|
UTF-8
| 389
| 1.78125
| 2
|
[] |
no_license
|
package com.example.demo6.model;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
/**
* File comments...
*
* @author Kenny Fang
* @version 1.0
* @date 2017/9/15 20:15
*/
@NoArgsConstructor
@AllArgsConstructor
@Data
public class StudentWork {
@Id
private String id;
private String name;
}
| true
|
7344fa7950aff3c2ba4998d906f6c719e228cefe
|
Java
|
Kaushal28/CPU-Scheduling-Algorithm-Simulation
|
/FCFS/src/fcfs/Utility.java
|
UTF-8
| 487
| 1.71875
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package fcfs;
import java.util.ArrayList;
import java.util.Set;
import java.util.TreeSet;
/**
*
* @author kaushal28
*/
public class Utility {
public static ArrayList<Integer> one = new ArrayList<>();
public static Set<Integer> time = new TreeSet<>();
public static double wt,at;
}
| true
|
6ce5c00f7e8ad093ed1d83f16408a49401c86814
|
Java
|
susheelit/AndroidApps
|
/CRM_Admin/app/src/main/java/com/irg/crm_admin/common/OprActivity.java
|
UTF-8
| 4,131
| 1.890625
| 2
|
[] |
no_license
|
package com.irg.crm_admin.common;
import android.content.Context;
import android.content.Intent;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import com.irg.crm_admin.R;
import com.irg.crm_admin.activity.LoginActivity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
/**
* Created by hdi on 25/10/17.
*/
public class OprActivity {
public static void finishAllOpenNewActivity(Context context, AppCompatActivity activity) {
// clear all and open new Activity
Intent intent = new Intent(context, activity.getClass());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
context.startActivity(intent);
((AppCompatActivity) context).finish();
// ((AppCompatActivity) context).overridePendingTransition(R.anim.right_in1, R.anim.left_out1);
}
public static void openActivity(Context context, AppCompatActivity activity) {
Intent intent = new Intent(context, activity.getClass());
context.startActivity(intent);
// ((AppCompatActivity) context).overridePendingTransition(R.anim.right_in1, R.anim.left_out1);
}
public static void finishActivity(Context context) {
((AppCompatActivity) context).finish();
// ((AppCompatActivity) context).overridePendingTransition(R.anim.right_in1, R.anim.left_out1);
}
public static String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
public static void setUpToolbar(Toolbar toolbar, Context context) {
((AppCompatActivity) context).setSupportActionBar(toolbar);
((AppCompatActivity) context).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((AppCompatActivity) context).getSupportActionBar().setTitle(context.getResources().getString(R.string.app_name));
}
public static void setUpToolbarWithTitle(Toolbar toolbar, String title, Context context) {
((AppCompatActivity) context).setSupportActionBar(toolbar);
((AppCompatActivity) context).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((AppCompatActivity) context).getSupportActionBar().setTitle(title);
}
public static void setUpToolbarWithoutBack(Toolbar toolbar, Context context) {
((AppCompatActivity) context).setSupportActionBar(toolbar);
// ((AppCompatActivity) context).getSupportActionBar().setDisplayHomeAsUpEnabled(true);
((AppCompatActivity) context).getSupportActionBar().setTitle(context.getResources().getString(R.string.app_name));
}
/*public static void replaceFragment(Fragment frag, Context context) {
FragmentManager manager = ((AppCompatActivity) context).getSupportFragmentManager();
if (manager != null) {
FragmentTransaction ft = manager.beginTransaction();
Fragment currentFrag = manager.findFragmentById(R.id.content_frame);
ft.setCustomAnimations(R.anim.right_in1, R.anim.left_out1);
ft.replace(R.id.content_frame, frag).addToBackStack(null).commit();
}
}*/
public static void logoutUser(Context context){
String userName = SharedPref.getMobileNo(context);
String password = SharedPref.getPassword(context);
// GetApi_Result.userLogOut(context, userName, password, true);
Intent intent = new Intent(context, LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent);
}
/* public static void dismissProgressDialog() {
if ( CallPostApi.progressDialog!=null && CallPostApi.progressDialog.isShowing() ){
CallPostApi.progressDialog.dismiss();
}
}*/
}
| true
|
a54967e0b4b83d979024225722d3c9fe8b644675
|
Java
|
erdemdenizli/Testing
|
/src/_40_TestNGTutorial.java
|
UTF-8
| 418
| 2.015625
| 2
|
[] |
no_license
|
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.Test;
public class _40_TestNGTutorial {
@Test
public void testMethod() {
System.out.println("Hello world!");
}
@Test
public void testMethod2() {
System.out.println("Hello world!");
}
//testng.xml under this project belongs to this :)
}
| true
|
570d3c1d536ff347c39e55addaa85b70b4147122
|
Java
|
ezsaidi/configuration
|
/target/generated-sources/entity-codegen/extensions/pc/internal/domain/contact/gen/PersonExtStub.java
|
UTF-8
| 3,227
| 1.789063
| 2
|
[] |
no_license
|
package extensions.pc.internal.domain.contact.gen;
import com.guidewire.pc.domain.contact.impl.PersonCoreExtImpl;
import extensions.pc.internal.domain.contact.impl.ContactExtInternal;
import extensions.pc.internal.domain.contact.impl.ContactExtMethodsImpl;
import extensions.pc.internal.domain.contact.impl.GlobalContactNameExtInternal;
import extensions.pc.internal.domain.contact.impl.GlobalContactNameExtMethodsImpl;
import extensions.pc.internal.domain.contact.impl.GlobalPersonNameExtInternal;
import extensions.pc.internal.domain.contact.impl.GlobalPersonNameExtMethodsImpl;
import extensions.pc.internal.domain.contact.impl.PersonExtInternal;
import gw.pc.account.entity.AccountContact;
public class PersonExtStub
extends PersonCoreExtImpl
implements ContactExtInternal, GlobalContactNameExtInternal, GlobalPersonNameExtInternal, PersonExtInternal
{
@Override
public Integer getExternalVersion() {
return getExtensionDelegate(ContactExtMethodsImpl.class).getExternalVersion();
}
@Override
public void setExternalVersion(Integer value) {
getExtensionDelegate(ContactExtMethodsImpl.class).setExternalVersion(value);
}
@Override
public String getCityKanjiDenorm() {
return getExtensionDelegate(ContactExtMethodsImpl.class).getCityKanjiDenorm();
}
@Override
public void setCityKanjiDenorm(String value) {
getExtensionDelegate(ContactExtMethodsImpl.class).setCityKanjiDenorm(value);
}
@Override
public AccountContact[] getAccountContacts() {
return getExtensionDelegate(ContactExtMethodsImpl.class).getAccountContacts();
}
@Override
public void addToAccountContacts(AccountContact value) {
getExtensionDelegate(ContactExtMethodsImpl.class).addToAccountContacts(value);
}
@Override
public void removeFromAccountContacts(AccountContact value) {
getExtensionDelegate(ContactExtMethodsImpl.class).removeFromAccountContacts(value);
}
@Override
public String getNameKanji() {
return getExtensionDelegate(GlobalContactNameExtMethodsImpl.class).getNameKanji();
}
@Override
public void setNameKanji(String value) {
getExtensionDelegate(GlobalContactNameExtMethodsImpl.class).setNameKanji(value);
}
@Override
public String getFirstNameKanji() {
return getExtensionDelegate(GlobalPersonNameExtMethodsImpl.class).getFirstNameKanji();
}
@Override
public void setFirstNameKanji(String value) {
getExtensionDelegate(GlobalPersonNameExtMethodsImpl.class).setFirstNameKanji(value);
}
@Override
public String getLastNameKanji() {
return getExtensionDelegate(GlobalPersonNameExtMethodsImpl.class).getLastNameKanji();
}
@Override
public void setLastNameKanji(String value) {
getExtensionDelegate(GlobalPersonNameExtMethodsImpl.class).setLastNameKanji(value);
}
@Override
public String getParticle() {
return getExtensionDelegate(GlobalPersonNameExtMethodsImpl.class).getParticle();
}
@Override
public void setParticle(String value) {
getExtensionDelegate(GlobalPersonNameExtMethodsImpl.class).setParticle(value);
}
}
| true
|
e4da3448eb520ff1986e692dc6e9bdb9203a0a1e
|
Java
|
flywind2/joeis
|
/src/irvine/oeis/a006/A006021.java
|
UTF-8
| 1,282
| 2.921875
| 3
|
[] |
no_license
|
package irvine.oeis.a006;
import java.util.HashSet;
import java.util.Set;
import irvine.math.MemoryFunction;
import irvine.math.z.Z;
import irvine.oeis.Sequence;
/**
* A006021 The game of contours.
* @author Sean A. Irvine
*/
public class A006021 extends MemoryFunction<Long, Long> implements Sequence {
// Uses non-negative indices for n and negative indices for tilde n
// This sequence is actually periodic so a simpler implementation is possible
private void augment(final Set<Long> seen, final long n) {
for (long a = 1; a < n; a++) {
// n -> a + tilde b where a + b == n - 1
seen.add(getValue(-a) ^ getValue(n - a - 1));
}
}
private void augmentTilde(final Set<Long> seen, final long n) {
for (long a = 0; a < n; a++) {
// tilde n -> tilde a + tilde b where a + b == n - 1
seen.add(getValue(a) ^ getValue(n - a - 1));
}
}
@Override
public Long compute(final Long n) {
if (n == 0 || n == -1) {
return 0L;
}
final HashSet<Long> seen = new HashSet<>();
if (n > 0) {
augment(seen, n);
augmentTilde(seen, n);
} else {
augment(seen, -n);
}
return A006016.mex(seen);
}
private long mN = -1;
@Override
public Z next() {
return Z.valueOf(getValue(++mN));
}
}
| true
|
95eebe4e2757f7db2ec029d4941727977ecdc794
|
Java
|
IlyaFX/java-tools
|
/src/test/java/clepto/humanize/HumanizeTest.java
|
UTF-8
| 1,052
| 2.578125
| 3
|
[] |
no_license
|
package clepto.humanize;
import org.junit.Test;
import static org.junit.Assert.*;
public class HumanizeTest {
@Test
public void testPlurals() {
assertEquals(pluralExample(1), "алмаз");
assertEquals(pluralExample(2), "алмаза");
assertEquals(pluralExample(4), "алмаза");
assertEquals(pluralExample(5), "алмазов");
assertEquals(pluralExample(10), "алмазов");
assertEquals(pluralExample(11), "алмазов");
assertEquals(pluralExample(14), "алмазов");
assertEquals(pluralExample(20), "алмазов");
assertEquals(pluralExample(21), "алмаз");
assertEquals(pluralExample(24), "алмаза");
assertEquals(pluralExample(100), "алмазов");
assertEquals(pluralExample(0), "алмазов");
assertEquals(pluralExample(-1), "алмаз");
assertEquals(pluralExample(-2), "алмаза");
assertEquals(pluralExample(-5), "алмазов");
}
private String pluralExample(int n) {
return Humanize.plurals("алмаз", "алмаза", "алмазов", n);
}
}
| true
|
55009f45dc398ab005c8b922c35fd255cdbc2604
|
Java
|
truegff/android-two-payout-demo
|
/app/src/main/java/com/system/itl/ssp_multi_devices/MyIOIOLooperManager.java
|
UTF-8
| 2,068
| 2.734375
| 3
|
[] |
no_license
|
package com.system.itl.ssp_multi_devices;
import ioio.lib.api.exception.ConnectionLostException;
import ioio.lib.util.BaseIOIOLooper;
class MyIOIOLooperManager extends BaseIOIOLooper {
private DeviceManager deviceManager;
MyIOIOLooperManager() {
deviceManager = new DeviceManager();
}
@Override
protected void setup() throws ConnectionLostException, InterruptedException {
/* led flash */
ThreadFlashes fl1 = new ThreadFlashes("LED1");
fl1.setup(ioio_ ,500);
deviceManager.Add(fl1);
/* Bill validator payout device */
ThreadSSPDevice SP0 = new ThreadSSPDevice("SP0");
SP0.setup(deviceManager,ioio_, 7, 5, 6);
deviceManager.Add(SP0);
/* Bill validator payout device */
ThreadSSPDevice SP1 = new ThreadSSPDevice("SP1");
SP1.setup(deviceManager,ioio_, 10, 4, 3);
deviceManager.Add(SP1);
/* start all the device threads that have been added */
deviceManager.StartAll();
}
/* loop not used in this application */
@Override
public void loop() throws ConnectionLostException, InterruptedException {
/* sleep in loop to allow OS */
Thread.sleep(100);
}
@Override
public void disconnected() {
deviceManager.CloseAll();
}
void onDestroy() {
deviceManager.CloseAll();
}
/**
* Get the instance of the Payout device threads for use in other classes
* @param tag : The string name of the instance to return
* @return ThreadSSPDevice: Instance reference to requested PayoutDevice
*/
ThreadSSPDevice GetPayoutInstance(String tag)
{
ThreadSSPDevice payoutInstance = null;
for (ThreadSSPDevice s: deviceManager.GetSSPDevices()
) {
if(s.GetSystemName().equals(tag)){
payoutInstance = s;
break;
}
}
return payoutInstance;
}
DeviceManager GetManagerInstance()
{
return deviceManager;
}
}
| true
|
5ae098f561fd868bc37ee96e3a442ab0c389f1e3
|
Java
|
Mezier/Java-Practice
|
/PracticeAlgorithm/src/atm/Bank.java
|
UTF-8
| 835
| 3.09375
| 3
|
[] |
no_license
|
package atm;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Bank {
private ArrayList<Customer> cus;
public Bank(){
cus=new ArrayList<Customer>();
}
//reads the customer numbers and pins and initialize
public void readCustomer(String fileName) throws Exception{
Scanner sc=new Scanner(new File(fileName));
while(sc.hasNext()){
int number=sc.nextInt();
int pin=sc.nextInt();
Customer c=new Customer(number, pin);
addCustomer(c);
}
sc.close();
}
private void addCustomer(Customer c) {
// TODO Auto-generated method stub
cus.add(c);
}
public Customer findCus(int id, int pin){
for(Customer c:cus){
if(c.match(id, pin)){
return c;
}
}
return null;
}
}
| true
|
d70bba2cc0ca8570084f3d921dfa0fab26c6cf46
|
Java
|
pcsopcso/edu
|
/98.hello/src/main/java/com/docker/example/hello/controller/HelloController.java
|
UTF-8
| 1,704
| 2.6875
| 3
|
[] |
no_license
|
package com.docker.example.hello.controller;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping({ "/", "/{greeting}" })
@ResponseBody
public String defaul(@PathVariable(required = false) String greeting) {
String strTemp = "";
if (greeting == null)
strTemp = "Hello Docker!" + "<br>" + getHostName1();
else
strTemp = "Hello" + " " + greeting + "!" + "<br>" + getHostName1();
return strTemp;
}
public static String getHostName() {
String hostname = System.getenv("HOSTNAME");
if (hostname != null)
return hostname;
String lineStr = "";
try {
Process process = Runtime.getRuntime().exec("hostname");
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((lineStr = br.readLine()) != null) {
hostname = lineStr;
}
} catch (IOException e) {
e.printStackTrace();
hostname = "";
}
return "HostName : " + hostname;
}
public static String getHostName1() {
String hostName = "";
String hostIP = "";
try {
hostName = InetAddress.getLocalHost().getHostName();
hostIP = InetAddress.getLocalHost().getHostAddress();
} catch (Exception e) {
e.printStackTrace();
}
return "HostName : " + hostName + ", " + "HostIP : " + hostIP;
}
}
| true
|
aafd9955dd10fd5a9a1f0df7a354febeaf5762ef
|
Java
|
MaikolLeiva/proyectoBancoEstatal
|
/ProyectoFraude/src/main/java/com/wings/designs/ProyectoFraude/users/UsersConfig.java
|
UTF-8
| 972
| 2.265625
| 2
|
[] |
no_license
|
package com.wings.designs.ProyectoFraude.users;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Arrays;
@Configuration
public class UsersConfig {
@Bean
CommandLineRunner commandLineRunner2(UsersRepository repository) {
return args -> {
Users testUser = new Users("123123123-K",
"password",
"Vin The Hero of Ages",
"MistBorn 1223",
"aasdasdasd@san.cl",
1L
);
Users testUser2 = new Users("225255446-8",
"1234",
"Kellsier ",
"MistBorn 3321",
"kel@lord.cl",
2L
);
repository.saveAll(
Arrays.asList(testUser,testUser2)
);
};
}
}
| true
|
1a3a543a5e6c0078bb16bf62ca8de7b4d43cad23
|
Java
|
SunYi21/xuewenliang
|
/lambda-test/src/test/java/entity/User.java
|
UTF-8
| 481
| 2.125
| 2
|
[] |
no_license
|
package entity;
import lombok.Data;
/**
* @Auther: 薛
* @Date: 2020/4/21 13:25
* @Description:
*/
@Data
public class User {
private String id;
private String name;
private Double money;
private String dd;
public User(String id, String name, Double money,String dd) {
this.id = id;
this.name = name;
this.money = money;
this.dd = dd;
}
public User() {
}
public static void main(String[] args) {
}
}
| true
|
15aa402cad2aae1dc0ad2fe3b34ce381e171a094
|
Java
|
harrycjy1/java-bootcamp
|
/practice_chap09(상속)/src/sec01_exam_captionTv/Tv.java
|
UHC
| 414
| 3.40625
| 3
|
[] |
no_license
|
package sec01_exam_captionTv;
//Ŭ(θ,superŬ) : 5
public class Tv {
boolean power;
int channel;
public Tv() {
System.out.println("Ŭ ȣ");
}
public void power() {
this.power = !power;
}
public void channelup() {
++this.channel;
}
public void channeldown() {
--this.channel;
}
}
| true
|
8b57def35bfce78d4639009b9aa359d3d741752f
|
Java
|
Kavzor/UsefulTools
|
/src/com/kavzor/tools/file/TextHandler.java
|
UTF-8
| 340
| 2.453125
| 2
|
[] |
no_license
|
package com.kavzor.tools.file;
import java.io.File;
public abstract class TextHandler implements FileConvertor{
protected static String SECTION_SEPERATOR = "###";
public TextHandler(File textFile, String section) {
toList(textFile, section);
}
public void setSeperator(String seperator) {
SECTION_SEPERATOR = seperator;
}
}
| true
|
7de53fe45d22a12e48b514f2f0d96db0ef750f9b
|
Java
|
Vladus1980/JavaAd05
|
/Magshop/src/main.java/domain/User.java
|
UTF-8
| 3,504
| 2.578125
| 3
|
[] |
no_license
|
package domain;
public class User {
private Integer id;
private String user_firstname;
private String user_lastname;
private String user_email;
private String user_pass;
private String user_level;
public User(Integer id, String user_firstname, String user_lastname, String user_email,
String user_pass, String user_level) {
this.id = id;
this.user_firstname = user_firstname;
this.user_lastname = user_lastname;
this.user_email = user_email;
this.user_pass = user_pass;
this.user_level = user_level;
}
public User(String user_firstname, String user_lastname, String user_email, String user_pass, String user_level) {
this.user_firstname = user_firstname;
this.user_lastname = user_lastname;
this.user_email = user_email;
this.user_pass = user_pass;
this.user_level = user_level;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUser_firstname() {
return user_firstname;
}
public void setUser_firstname(String user_firstname) {
this.user_firstname = user_firstname;
}
public String getUser_lastname() {
return user_lastname;
}
public void setUser_lastname(String user_lastname) {
this.user_lastname = user_lastname;
}
public String getUser_email() {
return user_email;
}
public void setUser_email(String user_email) {
this.user_email = user_email;
}
public String getUser_pass() {
return user_pass;
}
public void setUser_pass(String user_pass) {
this.user_pass = user_pass;
}
public String getUser_level() {
return user_level;
}
public void setUser_level(String user_level) {
this.user_level = user_level;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((user_email == null) ? 0 : user_email.hashCode());
result = prime * result + ((user_firstname == null) ? 0 : user_firstname.hashCode());
result = prime * result + ((user_lastname == null) ? 0 : user_lastname.hashCode());
result = prime * result + ((user_level == null) ? 0 : user_level.hashCode());
result = prime * result + ((user_pass == null) ? 0 : user_pass.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
User other = (User) obj;
if (id != other.id)
return false;
if (user_email == null) {
if (other.user_email != null)
return false;
} else if (!user_email.equals(other.user_email))
return false;
if (user_firstname == null) {
if (other.user_firstname != null)
return false;
} else if (!user_firstname.equals(other.user_firstname))
return false;
if (user_lastname == null) {
if (other.user_lastname != null)
return false;
} else if (!user_lastname.equals(other.user_lastname))
return false;
if (user_level == null) {
if (other.user_level != null)
return false;
} else if (!user_level.equals(other.user_level))
return false;
if (user_pass == null) {
if (other.user_pass != null)
return false;
} else if (!user_pass.equals(other.user_pass))
return false;
return true;
}
@Override
public String toString() {
return "User [id=" + id + ", user_firstname=" + user_firstname + ", user_lastname=" + user_lastname
+ ", user_email=" + user_email + ", user_pass=" + user_pass + ", user_level=" + user_level + "]";
}
}
| true
|
93f71ce276d086a407fe0f2ece73faec6762969f
|
Java
|
oppian/oikos
|
/src/com/oppian/oikos/model/Account.java
|
UTF-8
| 1,167
| 2.34375
| 2
|
[] |
no_license
|
package com.oppian.oikos.model;
import java.io.Serializable;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
@DatabaseTable
public class Account implements Serializable {
private static final long serialVersionUID = 2044539981769509541L;
@DatabaseField(generatedId = true)
private Integer id;
@DatabaseField(canBeNull = false)
private String name;
@DatabaseField(canBeNull = false)
private int total;
public Account() {
}
public Account(String name, int total) {
this.name = name;
this.total = total;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
@Override
public String toString() {
return "Account [id=" + id + ", name=" + name + ", total=" + total + "]";
}
}
| true
|
45b522210fce35924110e2abdbb736cf26eb4faa
|
Java
|
nabin-kuldeep-jena/iprotech
|
/deft/server/deft-server-common/src/main/java/com/asjngroup/deft/common/resources/ResourceScanner.java
|
UTF-8
| 7,623
| 2.625
| 3
|
[] |
no_license
|
package com.asjngroup.deft.common.resources;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import javassist.bytecode.AnnotationsAttribute;
import javassist.bytecode.ClassFile;
public abstract class ResourceScanner
{
private ClassLoader classLoader;
public ResourceScanner()
{
this( Thread.currentThread().getContextClassLoader() );
}
public ResourceScanner( ClassLoader classLoader )
{
this.classLoader = classLoader;
}
/**
* Override this to handle each item that is identified by the scan.
*
* @param name the scanned item
* @throws IOException
*/
protected abstract void handleItem( String name ) throws IOException;
/**
* Helper method to retrieve the class loader for this scanner.
*
* @return the class loader
*/
protected ClassLoader getClassLoader()
{
if ( classLoader == null )
classLoader = this.getClass().getClassLoader();
return classLoader;
}
/**
* Helper method to convert a resource filename to the corresponding classname.
*
* @param filename name of resource to convert
* @return the classname
*/
protected static String filenameToClassname( String filename )
{
return filename.substring( 0, filename.lastIndexOf( ".class" ) )
.replace( '/', '.' )
.replace( '\\', '.' );
}
/**
* Helper method to get the Java class file details.
*
* @param filename name of resource to get class details for
* @return the Java class details
* @throws IOException
*/
protected ClassFile getClassFile( String filename ) throws IOException
{
InputStream inputStream = null;
DataInputStream dataInputStream = null;
try
{
inputStream = getClassLoader().getResourceAsStream( filename );
dataInputStream = new DataInputStream( inputStream );
return new ClassFile( dataInputStream );
}
finally
{
if ( dataInputStream != null )
dataInputStream.close();
if ( inputStream != null )
inputStream.close();
}
}
/**
* Helper method to check a Java class has the annotation specified.
*
* @param classFile the Java class to check
* @param annotationType the annotation to check for
* @return true if the Java class contains the annotation specified, false otherwise
*/
protected boolean hasAnnotation( ClassFile classFile, Class< ? extends Annotation > annotationType )
{
AnnotationsAttribute visible = (AnnotationsAttribute)classFile.getAttribute( AnnotationsAttribute.visibleTag );
return ( visible != null && visible.getAnnotation( annotationType.getName() ) != null );
}
/**
* Scan all files, jars, folders for the specified resource and process individually.
*
* @param resourceName the resource to scan for
* @throws IOException
*/
protected void scan( String resourceName ) throws IOException
{
Set< UrlPath > urlPaths = new HashSet< UrlPath >();
if ( resourceName == null )
{
// scan the whole class path
for ( URL url : ((URLClassLoader)getClassLoader()).getURLs() )
{
String urlPath = url.getFile();
if ( urlPath.endsWith( "/" ) )
{
urlPath = urlPath.substring( 0, urlPath.length() - 1 );
}
urlPaths.add( new UrlPath( urlPath, null ) );
}
}
else
{
// only scan the resource specified
Enumeration< URL > urlEnum = getClassLoader().getResources( resourceName );
while ( urlEnum.hasMoreElements() )
{
String urlPath = urlEnum.nextElement().getFile();
urlPath = URLDecoder.decode( urlPath, "UTF-8" );
String parent = null;
// check for a file URL
if ( urlPath.startsWith( "file:" ) )
{
// urlPath looks like file:/C: for Windows and file:/home for Linux
// substring(5) works for both
urlPath = urlPath.substring( 5 );
}
// check for a Jar URL
if ( urlPath.indexOf( '!' ) > 0 )
{
urlPath = urlPath.substring( 0, urlPath.indexOf( '!' ) );
}
// check for the metadata resource URL
else if ( resourceName.startsWith( "META-INF" ) )
{
File dirOrArchive = new File( urlPath );
if ( resourceName.lastIndexOf( '/' ) > 0 )
{
// for META-INF/components.xml
dirOrArchive = dirOrArchive.getParentFile();
}
urlPath = dirOrArchive.getParent();
}
// any other resource location URL
else
{
parent = resourceName;
}
urlPaths.add( new UrlPath( urlPath, parent ) );
}
}
// process each of the paths located for the specified resource
for ( UrlPath urlPath: urlPaths )
{
File file = new File( urlPath.getPath() );
if ( file.isDirectory() )
{
handleDirectory( file, urlPath.getParent() );
}
else
{
handleArchive( file );
}
}
}
private void handleArchive( File file ) throws IOException
{
ZipFile archive = new ZipFile( file );
Enumeration< ? extends ZipEntry > entries = archive.entries();
while ( entries.hasMoreElements() )
{
ZipEntry entry = entries.nextElement();
handleItem( entry.getName() );
}
}
private void handleDirectory( File file, String path ) throws IOException
{
// recursively process each file/sub-directory
for ( File child : file.listFiles() )
{
String newPath = ( path == null ? child.getName() : path + '/' + child.getName() );
if ( child.isDirectory() )
{
handleDirectory( child, newPath );
}
else
{
handleItem( newPath );
}
}
}
class UrlPath
{
private String path;
private String parent;
public UrlPath( String path, String parent )
{
this.path = normalisePath( path );
this.parent = normalisePath( parent );
}
public String getPath()
{
return path;
}
public String getParent()
{
return parent;
}
private String normalisePath( String strPath )
{
if ( strPath == null )
return null;
if ( !strPath.endsWith( "/" ) )
return strPath;
return strPath.substring( 0, strPath.length() - 1 );
}
}
}
| true
|
deffba82073d4163a892776c57a675408e327bc8
|
Java
|
longpham041292/java-sample
|
/user-api/src/main/java/asia/cmg/f8/user/entity/AccountEntity.java
|
UTF-8
| 4,246
| 1.859375
| 2
|
[] |
no_license
|
/**
*
*/
package asia.cmg.f8.user.entity;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
/**
* Created on 08/02/20.
*/
@Entity
@Table(name = "account")
@Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class AccountEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "uuid")
private String uuid;
@Column(name = "username")
private String username;
@Column(name = "password")
private String password;
@Column(name = "time_created")
private Timestamp timeCreated;
@Column(name = "time_modified")
private Timestamp timeModified;
@OneToOne
@JoinColumn(name = "uuid", referencedColumnName = "uuid", insertable = false, updatable = false)
@Fetch(FetchMode.JOIN)
private UserInfoEntity userInfo;
@Column(name = "phone")
private String phone;
@Column(name = "email")
private String email;
@Column(name = "apple_id")
private String apple_id;
@Column(name = "fb_id")
private String fbId;
@Column(name = "google_id")
private String googleId;
@Column(name = "phone_validated")
private String phoneValidated;
@Column(name = "email_validated")
private String emailValidated;
@Column(name = "token_access")
private String tokenAccess;
@Column(name = "status")
private String status;
@Column(name = "type")
private String type;
@Column(name = "roles")
private int roles;
public int getRoles() {
return roles;
}
public void setRoles(int roles) {
this.roles = roles;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Timestamp getTimeCreated() {
return timeCreated;
}
public void setTimeCreated(Timestamp timeCreated) {
this.timeCreated = timeCreated;
}
public Timestamp getTimeModified() {
return timeModified;
}
public void setTimeModified(Timestamp timeModified) {
this.timeModified = timeModified;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getApple_id() {
return apple_id;
}
public void setApple_id(String apple_id) {
this.apple_id = apple_id;
}
public String getFbId() {
return fbId;
}
public void setFbId(String fbId) {
this.fbId = fbId;
}
public String getGoogleId() {
return googleId;
}
public void setGoogleId(String googleId) {
this.googleId = googleId;
}
public String getPhoneValidated() {
return phoneValidated;
}
public void setPhoneValidated(String phoneValidated) {
this.phoneValidated = phoneValidated;
}
public String getEmailValidated() {
return emailValidated;
}
public void setEmailValidated(String emailValidated) {
this.emailValidated = emailValidated;
}
public String getTokenAccess() {
return tokenAccess;
}
public void setTokenAccess(String tokenAccess) {
this.tokenAccess = tokenAccess;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public UserInfoEntity getUserInfo() {
return userInfo;
}
public void setUserInfo(UserInfoEntity userInfo) {
this.userInfo = userInfo;
}
public AccountEntity() {
super();
// TODO Auto-generated constructor stub
}
}
| true
|
7eda0ae1010b6916488f9dc13f891e2da16a8d56
|
Java
|
bryan-campos/Calculadora
|
/Calculadora/src/main/java/Operaciones.java
|
UTF-8
| 535
| 3.28125
| 3
|
[] |
no_license
|
public class Operaciones {
public int suma(int num,int num2){
return num + num2;
}
public int resta(int num, int num2){
return num - num2;
}
public int multiplicacion(int num, int num2){
return num * num2;
}
public double division(int num, int num2){
return num/num2;
}
public int exponenciacion(int num, int num2){
return (int) Math.pow(num,num2);
}
}
| true
|
f7c3c49b76e202b0b50658107dd55e4e22aa62a2
|
Java
|
FelixGit4Dev/snowflakeDatawarehouse
|
/AdventureWorksDWH/src/main/java/adventureworks/entitySource/Currencyrate.java
|
UTF-8
| 2,269
| 2.1875
| 2
|
[] |
no_license
|
package adventureworks.entitySource;
import java.io.Serializable;
import javax.persistence.*;
import java.util.Date;
import java.sql.Timestamp;
/**
* The persistent class for the currencyrate database table.
*
*/
@Entity
@Table(name="currencyrate")
@NamedQuery(name="Currencyrate.findAll", query="SELECT c FROM Currencyrate c")
public class Currencyrate implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(unique=true, nullable=false)
private int currencyRateID;
@Column(nullable=false)
private double averageRate;
@Temporal(TemporalType.TIMESTAMP)
@Column(nullable=false)
private Date currencyRateDate;
@Column(nullable=false)
private double endOfDayRate;
@Column(nullable=false, length=3)
private String fromCurrencyCode;
@Column(nullable=false)
private Timestamp modifiedDate;
@Column(nullable=false, length=3)
private String toCurrencyCode;
public Currencyrate() {
}
public int getCurrencyRateID() {
return this.currencyRateID;
}
public void setCurrencyRateID(int currencyRateID) {
this.currencyRateID = currencyRateID;
}
public double getAverageRate() {
return this.averageRate;
}
public void setAverageRate(double averageRate) {
this.averageRate = averageRate;
}
public Date getCurrencyRateDate() {
return this.currencyRateDate;
}
public void setCurrencyRateDate(Date currencyRateDate) {
this.currencyRateDate = currencyRateDate;
}
public double getEndOfDayRate() {
return this.endOfDayRate;
}
public void setEndOfDayRate(double endOfDayRate) {
this.endOfDayRate = endOfDayRate;
}
public String getFromCurrencyCode() {
return this.fromCurrencyCode;
}
public void setFromCurrencyCode(String fromCurrencyCode) {
this.fromCurrencyCode = fromCurrencyCode;
}
public Timestamp getModifiedDate() {
return this.modifiedDate;
}
public void setModifiedDate(Timestamp modifiedDate) {
this.modifiedDate = modifiedDate;
}
public String getToCurrencyCode() {
return this.toCurrencyCode;
}
public void setToCurrencyCode(String toCurrencyCode) {
this.toCurrencyCode = toCurrencyCode;
}
}
| true
|
fbfd2e764680a17a43617a60707a2ec617b3ef90
|
Java
|
YanaSmelik/OOP-with-Java.-Exercises
|
/Part 2. Exercise 47 - Flexible Filtering Criteria/src/reader/criteria/AtLeastOne.java
|
UTF-8
| 941
| 3.546875
| 4
|
[] |
no_license
|
package reader.criteria;
import java.util.ArrayList;
import java.util.List;
//The objects of this class receive as parameter an optional amount of objects with implement the interface Criterion
//the constructor receives a list of variable length as parameter
//AtLeastOne objects accept the lines which comply with at least one of the criteria received as constructor parameter.
public class AtLeastOne implements Criterion {
private List<Criterion> listOfCriteria;
public AtLeastOne(Criterion... criterias) {
listOfCriteria = new ArrayList<>();
for (Criterion criterion : criterias) {
listOfCriteria.add(criterion);
}
}
@Override
public boolean compiles(String line) {
for (Criterion criteria : listOfCriteria) {
if (criteria.compiles(line)) {
return true;
}
}
return false;
}
}
| true
|
0742e7682afff8594150fd74125053206d3e7e6f
|
Java
|
webbisswiftapps/ChelseaNepal
|
/app/src/main/java/com/webbisswift/cfcn/domain/model/MatchEvent.java
|
UTF-8
| 1,201
| 2.3125
| 2
|
[] |
no_license
|
package com.webbisswift.cfcn.domain.model;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by apple on 12/5/17.
*/
public class MatchEvent implements Parcelable {
public String away, home, minute, type;
public String getId(){
return away+home+minute+type;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.away);
dest.writeString(this.home);
dest.writeString(this.minute);
dest.writeString(this.type);
}
public MatchEvent() {
}
protected MatchEvent(Parcel in) {
this.away = in.readString();
this.home = in.readString();
this.minute = in.readString();
this.type = in.readString();
}
public static final Parcelable.Creator<MatchEvent> CREATOR = new Parcelable.Creator<MatchEvent>() {
@Override
public MatchEvent createFromParcel(Parcel source) {
return new MatchEvent(source);
}
@Override
public MatchEvent[] newArray(int size) {
return new MatchEvent[size];
}
};
}
| true
|
220bcf50cdd23d17aaf179bbc6908c2ae34b5caf
|
Java
|
ryank231231/jp.co.penet.gekidanprince
|
/com/ies_net/artemis/R.java
|
UTF-8
| 430
| 1.601563
| 2
|
[] |
no_license
|
package com.ies_net.artemis;
public final class R {
public static final class attr {}
public static final class drawable {
public static final int icon = 2130837504;
}
public static final class string {
public static final int app_name = 2130903040;
}
}
/* Location: Y:\classes2-dex2jar.jar!\com\ies_net\artemis\R.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/
| true
|
951baad0b1dbdcbb1854ef01ee04dec8f9214793
|
Java
|
gt6707a/FinalProject
|
/TellJokes/src/main/java/com/android/gt6707a/telljokes/Joker.java
|
UTF-8
| 136
| 1.75
| 2
|
[] |
no_license
|
package com.android.gt6707a.telljokes;
public class Joker {
public static String joke() {
return "why so serious";
}
}
| true
|
ee33c418b3f7ec4e610647451f4bde8dc7faad5d
|
Java
|
LCHCAPITALHUMAIN/simple-scrum
|
/RooScrum/src/main/java/com/scrumtool/domain/reference/SprintStatus.java
|
UTF-8
| 107
| 1.65625
| 2
|
[] |
no_license
|
package com.scrumtool.domain.reference;
public enum SprintStatus {
NOT_STARTED, STARTED, FINISHED
}
| true
|
31c8809ad882c5e1622775567453d03e279afac5
|
Java
|
thiagobardella/java_exercises
|
/src/main/java/exercise1and2/deserializer/GsonPartnerInputDeserializer.java
|
UTF-8
| 1,088
| 2.609375
| 3
|
[] |
no_license
|
package exercise1and2.deserializer;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import exercise1and2.models.PartnerInput;
import exercise1and2.utils.DateUtils;
import java.lang.reflect.Type;
import java.text.ParseException;
public class GsonPartnerInputDeserializer implements JsonDeserializer<PartnerInput> {
@Override
public PartnerInput deserialize(
JsonElement jElement, Type typeOfT, JsonDeserializationContext context) {
JsonObject jObject = jElement.getAsJsonObject();
int teamId = jObject.get("team_id").getAsInt();
String fullName = jObject.get("full_name").getAsString();
String email = jObject.get("email").getAsString();
String birthDate = jObject.get("birth_date").getAsString();
try {
return new PartnerInput(teamId, fullName, email, DateUtils.formatter.parse(birthDate));
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
}
| true
|
a1207c910f3e035db50eb578c998ba23bf5cd313
|
Java
|
knodafuture/knoda-android
|
/Knoda/src/main/java/views/group/GroupSettingsFragment.java
|
UTF-8
| 9,461
| 1.929688
| 2
|
[] |
no_license
|
package views.group;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.android.volley.toolbox.NetworkImageView;
import com.knoda.knoda.R;
import com.squareup.otto.Subscribe;
import java.util.ArrayList;
import adapters.MembershipAdapter;
import butterknife.InjectView;
import butterknife.OnClick;
import factories.GsonF;
import models.Group;
import models.Member;
import models.ServerError;
import networking.NetworkCallback;
import networking.NetworkListCallback;
import pubsub.ChangeGroupEvent;
import pubsub.GroupChangedEvent;
import views.core.BaseFragment;
import views.predictionlists.GroupPredictionListFragment;
public class GroupSettingsFragment extends BaseFragment implements MembershipCell.MembershipCellCallbacks {
@InjectView(R.id.group_settings_avatar)
NetworkImageView avatarImageView;
@InjectView(R.id.group_settings_description_textview)
TextView descriptionTextView;
@InjectView(R.id.group_settings_name_textview)
TextView nameTextView;
@InjectView(R.id.group_settings_list_view)
ListView listView;
@InjectView(R.id.group_settings_edit_group_button)
RelativeLayout editGroupButton;
@InjectView(R.id.group_settings_join_group_button)
RelativeLayout joinGroupButton;
@InjectView(R.id.group_settings_leave_group_button)
RelativeLayout leaveGroupButton;
@InjectView(R.id.group_settings_invite_view)
LinearLayout inviteView;
private Group group;
private String invitationCode;
public static GroupSettingsFragment newInstance(Group group, String invitationCode) {
GroupSettingsFragment fragment = new GroupSettingsFragment();
Bundle bundle = new Bundle();
bundle.putString("GROUP", GsonF.actory().toJson(group));
if (invitationCode != null) {
bundle.putString("INVITATION_CODE", invitationCode);
}
fragment.setArguments(bundle);
return fragment;
}
@Subscribe
public void groupChanged(GroupChangedEvent event) {
group = event.group;
populate();
}
@OnClick(R.id.group_settings_invite_button)
void onInvite() {
InvitationsFragment fragment = InvitationsFragment.newInstance(group);
pushFragment(fragment);
}
@OnClick(R.id.group_settings_share_button)
void onShare() {
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
String text = "Join my group " + group.name + " on @KNODAfuture! " + group.shareUrl;
share.putExtra(Intent.EXTRA_TEXT, text);
String subject = userManager.getUser().username + " invited you to join a group on Knoda";
share.putExtra(Intent.EXTRA_SUBJECT, subject);
startActivity(Intent.createChooser(share, "How would you like to share?"));
}
@OnClick(R.id.group_settings_leave_group_button)
void onLeave() {
leaveGroup();
}
@OnClick(R.id.group_settings_join_group_button)
void onJoin() {
joinGroup();
}
@OnClick(R.id.group_settings_edit_group_button)
void onEdit() {
EditGroupFragment fragment = EditGroupFragment.newInstance(group);
pushFragment(fragment);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
group = GsonF.actory().fromJson(getArguments().getString("GROUP"), Group.class);
if (getArguments().containsKey("INVITATION_CODE")) {
invitationCode = getArguments().getString("INVITATION_CODE");
}
bus.register(this);
setHasOptionsMenu(true);
getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
}
@Override
public void onDestroyView() {
getActivity().getActionBar().setDisplayHomeAsUpEnabled(false);
super.onDestroyView();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_group_settings, container, false);
return view;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
setTitle("SETTINGS");
populate();
}
@Override
public void onResume() {
super.onResume();
bus.post(new ChangeGroupEvent(group));
}
@Override
public void onPause() {
super.onPause();
bus.post(new ChangeGroupEvent(null));
}
private void populate() {
if (group.avatar != null && group.avatar.small != null)
avatarImageView.setImageUrl(group.avatar.small, networkingManager.getImageLoader());
nameTextView.setText(group.name);
descriptionTextView.setText(group.description);
if (group.myMembership == null && invitationCode != null) {
inviteView.setVisibility(View.INVISIBLE);
editGroupButton.setVisibility(View.GONE);
leaveGroupButton.setVisibility(View.INVISIBLE);
joinGroupButton.setVisibility(View.VISIBLE);
} else {
joinGroupButton.setVisibility(View.INVISIBLE);
if (userManager.getUser().id.equals(group.owner)) {
inviteView.setVisibility(View.VISIBLE);
leaveGroupButton.setVisibility(View.INVISIBLE);
} else {
inviteView.setVisibility(View.INVISIBLE);
editGroupButton.setVisibility(View.GONE);
leaveGroupButton.setVisibility(View.VISIBLE);
}
}
if (group.myMembership != null || invitationCode == null)
refresh();
}
private void refresh() {
networkingManager.getMembersInGroup(group.id, new NetworkListCallback<Member>() {
@Override
public void completionHandler(ArrayList<Member> object, ServerError error) {
if (error != null)
return;
setMembers(object);
}
});
}
private void setMembers(ArrayList<Member> members) {
listView.setAdapter(new MembershipAdapter(getActivity(), group, this, members));
}
@Override
public void memberRemovedAtPosition(int position) {
Member member = (Member) listView.getAdapter().getItem(position);
networkingManager.deleteMembership(member.id, new NetworkCallback<Member>() {
@Override
public void completionHandler(Member object, ServerError error) {
refresh();
}
});
}
private void leaveGroup() {
final AlertDialog alert = new AlertDialog.Builder(getActivity())
.setPositiveButton("Yes", null)
.setNegativeButton("No", null)
.setTitle("Are you sure you wish to leave the group?")
.create();
alert.show();
alert.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
alert.dismiss();
spinner.show();
networkingManager.deleteMembership(group.myMembership.id, new NetworkCallback<Member>() {
@Override
public void completionHandler(Member object, ServerError error) {
userManager.refreshGroups(new NetworkListCallback<Group>() {
@Override
public void completionHandler(ArrayList<Group> object, ServerError error) {
spinner.hide();
popToRootFragment();
}
});
}
});
}
});
alert.getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
alert.dismiss();
}
});
}
public void joinGroup() {
spinner.show();
networkingManager.joinGroup(invitationCode, group.id, new NetworkCallback<Member>() {
@Override
public void completionHandler(final Member membership, ServerError error) {
if (error != null) {
spinner.hide();
errorReporter.showError("Unable to join the group at this time.");
} else {
userManager.refreshGroups(new NetworkListCallback<Group>() {
@Override
public void completionHandler(ArrayList<Group> object, ServerError error) {
spinner.hide();
popFragment();
pushFragment(GroupPredictionListFragment.newInstance(userManager.getGroupById(membership.groupId)));
}
});
}
}
});
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
}
}
| true
|
048bf64cb7ada4bc2212baff372b5104eab7ac95
|
Java
|
samely/findchangeset-plugin
|
/src/org/openstreetmap/josm/plugins/findchangeset/FindChangesetPlugin.java
|
UTF-8
| 781
| 2.0625
| 2
|
[] |
no_license
|
package org.openstreetmap.josm.plugins.findchangeset;
import java.awt.GraphicsEnvironment;
import org.openstreetmap.josm.gui.IconToggleButton;
import org.openstreetmap.josm.gui.MapFrame;
import org.openstreetmap.josm.plugins.Plugin;
import org.openstreetmap.josm.plugins.PluginInformation;
public class FindChangesetPlugin extends Plugin{
private IconToggleButton btn;
protected static FindChangesetDialog findChangeDialog;
public FindChangesetPlugin(PluginInformation info) {
super(info);
}
@Override
public void mapFrameInitialized(MapFrame oldFrame, MapFrame newFrame) {
if (newFrame != null && !GraphicsEnvironment.isHeadless()) {
newFrame.addToggleDialog(findChangeDialog = new FindChangesetDialog());
}
}
}
| true
|
4a102c99d0abc48d9f74a2eddd2a83e7ac563f9f
|
Java
|
dem-v/QSTQuizz_renewed
|
/app/src/main/java/vda/home/qstquizz/FileSelectActivity.java
|
UTF-8
| 3,913
| 2.015625
| 2
|
[] |
no_license
|
package vda.home.qstquizz;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class FileSelectActivity extends AppCompatActivity {
String filePath;
List<String> FilePathRouteRecorder = new ArrayList<String>();
List<String> FilesLister = new ArrayList<String>();
ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_file_select);
final ListView lw = (ListView) this.findViewById(R.id.listOfFiles);
final AssetManager am = FileSelectActivity.this.getAssets();
String[] tt = null;
try {
tt = am.list("KROK");
} catch (IOException e) {
e.printStackTrace();
finish();
}
FilePathRouteRecorder.add("KROK/");
FilesLister = Arrays.asList(tt);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, FilesLister);
lw.setAdapter(adapter);
lw.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String s = TextUtils.join("", FilePathRouteRecorder.toArray());
filePath = s + FilesLister.get(position);
if (!isDir(filePath)) {
Intent answerIntent = new Intent();
answerIntent.putExtra("vda.home.qstquizz.PATH", filePath);
setResult(RESULT_OK, answerIntent);
finish();
} else if (isDir(filePath)) {
String[] tt = null;
FilePathRouteRecorder.add(FilesLister.get(position) + "/");
try {
tt = am.list(filePath);
} catch (IOException e) {
e.printStackTrace();
finish();
}
FilesLister = Arrays.asList(tt);
adapter.notifyDataSetChanged();
adapter = new ArrayAdapter<String>(FileSelectActivity.this, android.R.layout.simple_list_item_1, FilesLister);
lw.setAdapter(adapter);
}
}
});
}
@NonNull
protected Boolean isDir(String path) {
String[] list;
try {
list = FileSelectActivity.this.getAssets().list(path);
} catch (IOException e) {
return false;
}
return list.length > 0;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_file_select, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| true
|
8d32a12c5706a7312899aaffc83a31c7c5619fa0
|
Java
|
SantiagoGM19/OnValve
|
/OnValve/app/src/main/java/com/example/OnValve/agregar_valvula.java
|
UTF-8
| 3,787
| 2.125
| 2
|
[
"MIT"
] |
permissive
|
package com.example.OnValve;
import android.content.Intent;
import android.os.Bundle;
import android.text.Layout;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.OnValve.Modelo.Valvula;
import com.google.firebase.FirebaseApp;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.io.ObjectOutputStream;
import java.util.Objects;
import java.util.UUID;
public class agregar_valvula extends AppCompatActivity {
private EditText txtnombre_valvula;
private EditText txtFabricante;
private EditText txtSerial;
private EditText txtCorreoElectronicoUser;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.agregar_valvula);
txtnombre_valvula = findViewById(R.id.txtnombre_valvula);
txtFabricante = findViewById(R.id.txtFabricante);
txtSerial = findViewById(R.id.txtSerial);
txtCorreoElectronicoUser = findViewById(R.id.txtCorreoElectronicoUser);
inicializarFirebase();
}
private void inicializarFirebase() {
FirebaseApp.initializeApp(this);
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference();
}
public void validacion() {
if (txtnombre_valvula.getText().toString().equals("")) {
txtnombre_valvula.setError("Requerido");
}
if (txtFabricante.getText().toString().equals("")) {
txtFabricante.setError("Requerido");
}
if (txtSerial.getText().toString().equals("")) {
txtSerial.setError("Requerido");
}
if (txtCorreoElectronicoUser.getText().toString().equals("")) {
txtCorreoElectronicoUser.setError("Requerido");
}
}
public boolean DatosVacios() {
if (txtnombre_valvula.getText().toString().equals("")) {
return true;
}
if (txtFabricante.getText().toString().equals("")) {
return true;
}
if (txtSerial.getText().toString().equals("")) {
return true;
}
if (txtCorreoElectronicoUser.getText().toString().equals("")) {
return true;
} else {
return false;
}
}
public void RegistrarValvula(View view)
{
String nombre = txtnombre_valvula.getText().toString();
String fabricante = txtFabricante.getText().toString();
String serial = txtSerial.getText().toString();
String correoElectronicoUsuario = txtCorreoElectronicoUser.getText().toString();
String ValvulaId = UUID.randomUUID().toString();
if (this.DatosVacios())
{
validacion();
}
else
{
Valvula NewValvula = new Valvula(nombre, fabricante, serial, correoElectronicoUsuario, ValvulaId);
databaseReference.child("Valvulas").child(NewValvula.getvalvulaId()).setValue(NewValvula);
Intent main = new Intent(this, perfil_usuario.class);
main.putExtra("ValvulaCreada", NewValvula.getNombre());
txtnombre_valvula.setText("");
txtFabricante.setText("");
txtSerial.setText("");
txtCorreoElectronicoUser.setText("");
Toast.makeText(this, "Datos guardados correctamente", Toast.LENGTH_SHORT).show();
}
}
public void IrPerfilUsuario(View view)
{
Intent main = new Intent(this, perfil_usuario.class);
startActivity(main);
}
}
| true
|
a2c26ef864d34588b28a1d56834fc19a381c8d2e
|
Java
|
lindzh/jetcd
|
/src/test/java/com/lindzh/jetcd/ChangeWatchDirTest.java
|
UTF-8
| 639
| 2.53125
| 3
|
[
"Apache-2.0"
] |
permissive
|
package com.lindzh.jetcd;
public class ChangeWatchDirTest {
public static void main1(String[] args) throws InterruptedException {
final EtcdClient client = new EtcdClient("http://127.0.0.1:2379");
client.start();
String dir = "/mydir";
client.delDir(dir, true);
client.dir(dir);
Thread.currentThread().sleep(10000);
client.set("/mydir/mykey1", "this is a value 1", 30);
Thread.sleep(5000);
client.set("/mydir/mykey2", "this is a value 2", 10);
Thread.sleep(5000);
client.set("/mydir/mykey3", "this is a value 3", 20);
client.set("/mydir2","hahahah");
client.dir("/mydir3");
client.stop();
}
}
| true
|
543116f82f2d1ca2d215ab25422cdedfe8ecd508
|
Java
|
thalabi/StudentNotesService
|
/StudentNotesService/src/test/java/com/kerneldc/education/studentNotesService/service/StudentNotesReportServiceTests.java
|
UTF-8
| 7,378
| 2.453125
| 2
|
[] |
no_license
|
package com.kerneldc.education.studentNotesService.service;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.HashSet;
import javax.xml.bind.JAXBException;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.kerneldc.education.studentNotesService.bean.GradeEnum;
import com.kerneldc.education.studentNotesService.bean.Students;
import com.kerneldc.education.studentNotesService.dto.GradeDto;
import com.kerneldc.education.studentNotesService.dto.NoteDto;
import com.kerneldc.education.studentNotesService.dto.StudentDto;
public class StudentNotesReportServiceTests {
private static final Logger LOGGER = LoggerFactory.getLogger(Thread.currentThread().getStackTrace()[1].getClassName());
private static PdfStudentNotesReportService fixture;
@BeforeClass
public static void setup() {
fixture = new PdfStudentNotesReportService();
}
@Test
public void testBeanToXml() throws JAXBException {
// Create student # 1
String firstName = "first name testBeanToXml";
String lastName = "last name testBeanToXml";
StudentDto student = new StudentDto();
student.setFirstName(firstName);
student.setLastName(lastName);
GradeDto gradeDto = new GradeDto();
gradeDto.setGradeEnum(GradeEnum.JK);
student.setGradeDto(gradeDto);
String note1TimestampText = "2017-01-29 16:11";
String note1Text = "note 1 text testBeanToXml";
String note2TimestampText = "2017-01-29 16:12";
String note2Text = "note 2 text testBeanToXml";
NoteDto note1 = new NoteDto();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime timestamp1 = LocalDateTime.parse(note1TimestampText, formatter);
note1.setTimestamp(Timestamp.valueOf(timestamp1));
note1.setText(note1Text);
NoteDto note2 = new NoteDto();
LocalDateTime timestamp2 = LocalDateTime.parse(note2TimestampText, formatter);
note2.setTimestamp(Timestamp.valueOf(timestamp2));
note2.setText(note2Text);
student.setNoteDtoSet(new HashSet<>(Arrays.asList(note1, note2)));
// Create student # 2
String firstName2 = "first name 2 testBeanToXml";
String lastName2 = "last name 2 testBeanToXml";
//GradeEnum grade2 = GradeEnum.FOUR;
StudentDto student2 = new StudentDto();
student2.setFirstName(firstName2);
student2.setLastName(lastName2);
//student2.setGradeEnum(grade2);
/*
String note1TimestampText = "2017-01-29 16:11";
String note1Text = "note 1 text testBeanToXml";
String note2TimestampText = "2017-01-29 16:12";
String note2Text = "note 2 text testBeanToXml";
Note note1 = new Note();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
LocalDateTime timestamp1 = LocalDateTime.parse(note1TimestampText, formatter);
note1.setTimestamp(Timestamp.valueOf(timestamp1));
note1.setText(note1Text);
Note note2 = new Note();
LocalDateTime timestamp2 = LocalDateTime.parse(note2TimestampText, formatter);
note2.setTimestamp(Timestamp.valueOf(timestamp2));
note2.setText(note2Text);
student.setNoteList(Arrays.asList(note1, note2));
*/
// Student createdStudent = studentRepository.save(student);
// Student createdStudent2 = studentRepository.save(student2);
Students students = new Students();
students.setStudentList(Arrays.asList(student, student2));
// LOGGER.info("createdStudent: {}", createdStudent);
// LOGGER.info("createdStudent2: {}", createdStudent2);
// Verify createdStudent
// assert(
// createdStudent.getId().compareTo(0l) > 0 &&
// createdStudent.getFirstName().equals(firstName) &&
// createdStudent.getLastName().equals(lastName) &&
// createdStudent.getGradeEnum().equals(grade) &&
// createdStudent.getVersion().compareTo(0l) == 0 &&
// createdStudent.getNoteList().size() == 2
// );
//
// assert(
// createdStudent.getNoteList().get(0).getId().compareTo(0l) > 0 &&
// timestampFormat.format(createdStudent.getNoteList().get(0).getTimestamp()).equals(note1TimestampText) &&
// createdStudent.getNoteList().get(0).getText().equals(note1Text) &&
// createdStudent.getNoteList().get(0).getVersion().compareTo(0l) == 0 &&
//
// createdStudent.getNoteList().get(1).getId().compareTo(0l) > 0 &&
// timestampFormat.format(createdStudent.getNoteList().get(1).getTimestamp()).equals(note2TimestampText) &&
// createdStudent.getNoteList().get(1).getText().equals(note2Text) &&
// createdStudent.getNoteList().get(1).getVersion().compareTo(0l) == 0
// );
// Verify createdStudent2
// assert(
// createdStudent2.getId().compareTo(0l) > 0 &&
// createdStudent2.getFirstName().equals(firstName2) &&
// createdStudent2.getLastName().equals(lastName2) &&
// createdStudent2.getGradeEnum().equals(grade2) &&
// createdStudent2.getVersion().compareTo(0l) == 0 //&&
// //createdStudent2.getNoteList().size() == 2
// );
byte[] xmlBytes = fixture.beanToXml(students);
String xmlString = new String(xmlBytes, StandardCharsets.UTF_8);
LOGGER.info("xmlString: {}", xmlString);
/*
assert(
StringUtils.countMatches(xmlString, "<student>") == 1 && StringUtils.countMatches(xmlString, "</student>") == 1
);
assert(
xmlString.contains("<id>"+createdStudent.getId()+"</id>") &&
xmlString.contains("<firstName>"+createdStudent.getFirstName()+"</firstName>") &&
xmlString.contains("<lastName>"+createdStudent.getLastName()+"</lastName>") &&
xmlString.contains("<grade>"+createdStudent.getGrade()+"</grade>") &&
xmlString.contains("<version>0</version>")
);
assert(
StringUtils.countMatches(xmlString, "<noteList>") == 1 && StringUtils.countMatches(xmlString, "</noteList>") == 1 &&
StringUtils.countMatches(xmlString, "<note>") == 2 && StringUtils.countMatches(xmlString, "</note>") == 2
);
assert(
xmlString.contains("<id>"+createdStudent.getNoteList().get(0).getId()+"</id>") &&
xmlString.contains("<timestamp>"+timestampFormat.format(createdStudent.getNoteList().get(0).getTimestamp())+"</timestamp>") &&
xmlString.contains("<text>"+createdStudent.getNoteList().get(0).getText()+"</text>") &&
xmlString.contains("<version>0</version>")
);
assert(
xmlString.contains("<id>"+createdStudent.getNoteList().get(1).getId()+"</id>") &&
xmlString.contains("<timestamp>"+timestampFormat.format(createdStudent.getNoteList().get(1).getTimestamp())+"</timestamp>") &&
xmlString.contains("<text>"+createdStudent.getNoteList().get(1).getText()+"</text>") &&
xmlString.contains("<version>0</version>")
);
*/
}
/*
@Test
public void testXmlToPdf() throws IOException {
byte[] studentsXmlByteArray = IOUtils.toByteArray(ClassLoader.getSystemResourceAsStream("students.xml"));
byte[] pdfByteArray = pdfStudentNotesReportService.xmlToPdf(studentsXmlByteArray);
LOGGER.debug("pdfByteArray.length: {}", pdfByteArray.length);
assert (pdfByteArray.length > 0);
}
@Test
public void testGenerateReport() throws SnsException {
Students students = new Students();
students.setStudentList(studentRepository.getAllStudents());
byte[] pdfByteArray = pdfStudentNotesReportService.generateReport(students);
LOGGER.debug("pdfByteArray.length: {}", pdfByteArray.length);
assert (pdfByteArray.length > 0);
}
*/
}
| true
|
8145281dddb11823e5a0e8b2966f97cb557af70e
|
Java
|
shyf2015/online-edu-star
|
/edu-com/com-wechat-service/src/main/java/com/clark/daxian/wechat/exception/WeChatException.java
|
UTF-8
| 542
| 2.171875
| 2
|
[] |
no_license
|
package com.clark.daxian.wechat.exception;
import com.clark.daxian.api.exception.EduException;
/**
* WeChat业务异常
* @author 大仙
*/
public class WeChatException extends EduException {
public WeChatException(String message) {
super(message);
}
public WeChatException(String message, int code) {
super(message);
this.code = code;
}
public WeChatException(String message, int code, String title) {
super(message);
this.code = code;
this.title = title;
}
}
| true
|
c250531954eaef618309628fac2ff65b0c87026b
|
Java
|
kacperwojaczek/PersonAPI-Android-App
|
/app/src/main/java/com/example/kacper/zaliczenie/MainActivity.java
|
UTF-8
| 6,333
| 2.25
| 2
|
[] |
no_license
|
package com.example.kacper.zaliczenie;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.example.kacper.zaliczenie.Helpers.DownloadDataTask;
import com.example.kacper.zaliczenie.Helpers.UsersDatabase;
import com.example.kacper.zaliczenie.Models.User;
public class MainActivity extends AppCompatActivity {
EditText emailText;
ProgressBar progressBar;
UsersDatabase database;
LinearLayout loginBlock;
Button loginButton;
TextView username;
TextView password;
TextView helloText;
User user = null;
Context myContext = this;
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.favourites:
if (user != null) {
Intent favouritesIntent = new Intent(this, FavouritesActivity.class);
favouritesIntent.putExtra("userId", user.getUuid());
favouritesIntent.putExtra("username", user.getUsername());
myContext.startActivity(favouritesIntent);
} else {
Toast toast = new Toast(this);
toast.makeText(this, "No user", Toast.LENGTH_SHORT).show();
}
break;
case R.id.logout:
user = null;
loginBlock.setVisibility(View.VISIBLE);
helloText.setVisibility(View.GONE);
invalidateOptionsMenu();
Toast toast = new Toast(this);
toast.makeText(this, "Logout successful", Toast.LENGTH_SHORT).show();
break;
default:
break;
}
return true;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (user != null) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
}
getSupportActionBar().setTitle(getString(R.string.appName));
return true;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
emailText = (EditText) findViewById(R.id.emailText);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
Button searchButton = (Button) findViewById(R.id.queryButton);
searchButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!emailText.getText().toString().isEmpty()) {
new DownloadDataTask(myContext, progressBar, emailText, user).execute();
} else {
Toast toast = new Toast(myContext);
toast.makeText(myContext, "Please input email adress!", Toast.LENGTH_SHORT).show();
}
}
});
database = new UsersDatabase(this);
loginBlock = (LinearLayout) findViewById(R.id.loginBlock);
loginButton = (Button) findViewById(R.id.logIn);
username = (TextView) findViewById(R.id.name);
password = (TextView) findViewById(R.id.password);
helloText = (TextView) findViewById(R.id.helloText);
//LOGIN
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
user = database.getUser(username.getText().toString());
if (user != null) {
if (password.getText().toString().equals(user.getPassword())) {
password.setText("");
loginBlock.setVisibility(View.GONE);
helloText.setText(new String("Hello " + user.getUsername() + "!"));
helloText.setVisibility(View.VISIBLE);
invalidateOptionsMenu();
Toast toast = new Toast(myContext);
toast.makeText(myContext, "Login successful", Toast.LENGTH_SHORT).show();
} else {
Toast toast = new Toast(myContext);
toast.makeText(myContext, "Incorrect password", Toast.LENGTH_SHORT).show();
}
} else {
Toast toast = new Toast(myContext);
toast.makeText(myContext, "User doesn't exist", Toast.LENGTH_SHORT).show();
}
}
});
Button registerButton = (Button) findViewById(R.id.register);
registerButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
user = database.getUser(username.getText().toString());
if (user == null) {
user = database.addUser(new User(username.getText().toString(), password.getText().toString()));
if (user != null) {
Toast toast = new Toast(myContext);
toast.makeText(myContext, "Successfully registered", Toast.LENGTH_SHORT).show();
password.setText("");
loginBlock.setVisibility(View.GONE);
helloText.setText(new String("Hello " + user.getUsername() + "!"));
helloText.setVisibility(View.VISIBLE);
invalidateOptionsMenu();
} else {
Toast toast = new Toast(myContext);
toast.makeText(myContext, "Registration failed", Toast.LENGTH_SHORT).show();
}
} else {
Toast toast = new Toast(myContext);
toast.makeText(myContext, "User already registered", Toast.LENGTH_SHORT).show();
}
}
});
}
}
| true
|
922869ea0ba2c56898e8d1d9870649c7041835b4
|
Java
|
dx14/SLogo
|
/src/parser/command/commandlist/turtles/TurtlesCommand.java
|
UTF-8
| 280
| 2
| 2
|
[
"MIT"
] |
permissive
|
package parser.command.commandlist.turtles;
import parser.ParserException;
import parser.command.Command;
public class TurtlesCommand extends Command {
@Override
public double evaluate() throws ParserException {
return myParser.getTurtleContainer().getNumTurtles();
}
}
| true
|
936ec293812369514f829bc507a855c1b0a93ca7
|
Java
|
cypherfox/HarperHallUtil
|
/src/de/harper_hall/util/math/CartesianVector.java
|
UTF-8
| 6,377
| 3.640625
| 4
|
[] |
no_license
|
/**
*
*/
package de.harper_hall.util.math;
/**
*
* While some utility functions exist to aid the use in three dimensions, the package supports arbitrary dimensions.
*
* TODO: basis-operation (sub),
*
* TODO: Funktion die add implementiert mit vektor kleinerer Dimension, mit int parameter um n Dimensionen verschoben
*
* @author sage
*
*/
public class CartesianVector extends Vector {
private final int defaultMaxDimension = 3;
/**
* create cartesian vector from discrete values
*
* @param vals
*/
public CartesianVector(double[] vals) {
int i, dimension = vals.length;
values = new double[dimension];
for (i = 0; i < dimension; i++) {
values[i] = vals[i];
}
}
/**
* create 3D cartesian vector
*
*/
public CartesianVector() {
super();
}
/**
* create 3D cartesian vector
*
*/
public CartesianVector(double x, double y, double z) {
super();
values[0] = x;
values[1] = y;
values[2] = z;
}
/**
*
* @param dimension
*/
public CartesianVector(int dimension) {
super(dimension);
}
/**
* transform a SpericalVector into a cartesian one.
*
* This constructor is only able to convert 3D Vectors. It will throw IndexOutOfBoundsException otherwise
*
* @param a
* a SpericalVector
*/
public CartesianVector(SphericalVector a) throws IndexOutOfBoundsException {
super(a.getDimension());
if (a.getDimension() > defaultMaxDimension) {
throw new IndexOutOfBoundsException("dimension > " + defaultMaxDimension);
}
/*
* x = r * sin(theta) * cos(phi) y = r * sin(theta) * sin(phi) z = r * cos(theta)
*/
values[0] = a.values[0] * Math.sin(a.values[1]) * Math.cos(a.values[2]);
values[0] = a.values[0] * Math.sin(a.values[1]) * Math.sin(a.values[2]);
values[0] = a.values[0] * Math.cos(a.values[1]);
}
/**
*
* @param i
* the position of the element to return
* @return value at the n-th position in the vector
*/
public double getElement(int i) {
return values[i];
}
/**
* Utility accessor
*
* @return distance along the x-axis
* @throws ArrayIndexOutOfBoundsException
* if the vector has less than one dimension
*/
public double getX() throws ArrayIndexOutOfBoundsException {
return values[0];
}
/**
* Utility accessor
*
* @return distance along the y-axis
* @throws ArrayIndexOutOfBoundsException
* if the vector has less than two dimensions
*/
public double getY() throws ArrayIndexOutOfBoundsException {
return values[1];
}
/**
* Utility accessor
*
* @return distance along the z-axis
* @throws ArrayIndexOutOfBoundsException
* if the vector has less than three dimensions
*/
public double getZ() throws ArrayIndexOutOfBoundsException {
return values[2];
}
/**
*
* @param a
* @return
* @throws IndexOutOfBoundsException
*/
public Vector add(Vector a) throws IndexOutOfBoundsException {
int i;
int dimension = getDimension();
if (a instanceof SphericalVector) {
a = new CartesianVector((SphericalVector) a);
}
if (dimension != a.getDimension()) {
throw new IndexOutOfBoundsException("Dimension of vectors differ");
}
Vector retval = new CartesianVector(dimension);
for (i = 0; i < dimension; i++) {
retval.values[i] = this.values[i] + a.values[i];
}
return retval;
}
/**
* subtract vector from this one.
*
* @param a
* a Vector
* @return
* @throws IndexOutOfBoundsException
*/
public Vector sub(Vector a) throws IndexOutOfBoundsException {
int i;
int dimension = getDimension();
if (dimension != a.getDimension()) {
throw new IndexOutOfBoundsException("Dimension of vectors differ");
}
if (a instanceof SphericalVector) {
a = new CartesianVector((SphericalVector) a);
}
Vector retval = new CartesianVector(dimension);
for (i = 0; i < dimension; i++) {
retval.values[i] = this.values[i] - a.values[i];
}
return retval;
}
/**
* scalar multiple
*
* @param factor
* @return
*/
@Override
public Vector mult(double factor) {
int i, dimension = getDimension();
Vector retval = new CartesianVector(dimension);
for (i = 0; i < dimension; i++) {
retval.values[i] = this.values[i] * factor;
}
return retval;
}
/**
* dot product of two vectors with the angle phi between them.
*
* for cartesian coordinate systems, cos_phi is 1;
*
* @param b
* @param phi
* @return
*/
public double dotProduct(CartesianVector b, double cosPhi) {
int i, dimension = getDimension();
double retval = 0;
for (i = 0; i < dimension; i++) {
retval += values[i] * b.values[i];
}
return retval * cosPhi;
}
/**
* get the length of the vector
*
* @return absolute length of the vector
*/
@Override
public double length() {
double len = dotProduct(this, 1);
return Math.sqrt(len);
}
/**
* cross product
*
* The cross multiple is only defined for dimension = 3
*
* @return
* @param b
*/
public Vector xProduct(CartesianVector b) {
int dimension = getDimension();
if (dimension != defaultMaxDimension) {
throw new IndexOutOfBoundsException("Dimension of this vector is not 3");
}
if (b.getDimension() != defaultMaxDimension) {
throw new IndexOutOfBoundsException("Dimension of param b is not 3");
}
Vector retval = new CartesianVector(dimension);
retval.values[0] = values[1] * b.values[2] - values[2] * b.values[1];
retval.values[1] = values[2] * b.values[0] - values[0] * b.values[2];
retval.values[2] = values[0] * b.values[1] - values[1] * b.values[0];
return retval;
}
/**
* normalize the vector
*
* will return a vector with the length of 1, pointing into the same direction as this vector
*
* @return normalized vector
*/
@Override
public Vector normalize() {
int i, dimension = getDimension();
double norm = length();
Vector retval = new CartesianVector(dimension);
for (i = 0; i < dimension; i++) {
retval.values[i] = values[i] / norm;
}
return retval;
}
}
| true
|
db98424587555369d8b0b2ec97de267b1c737f4a
|
Java
|
zoubeidaNM/LostPets
|
/src/main/java/com/example/lostpets/JavaController.java
|
UTF-8
| 4,673
| 2.46875
| 2
|
[] |
no_license
|
package com.example.lostpets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.util.List;
@Controller
public class JavaController {
@Autowired
PetRepository petRepository;
@RequestMapping("/")
public String listPets(Model model) {
model.addAttribute("pets", petRepository.findAll());
return "list";
}
@RequestMapping("/modify")
public String listPetsForUpdate(Model model) {
model.addAttribute("pets", petRepository.findAll());
return "modify";
}
@RequestMapping("/delete")
public String listPetsForDelete(Model model) {
model.addAttribute("pets", petRepository.findAll());
return "delete";
}
@GetMapping("/add")
public String petForm(Model model) {
model.addAttribute("pet", new Pet());
return "petform";
}
@PostMapping("/process")
public String processForm(@Valid Pet pet, BindingResult result) {
if (result.hasErrors()) {
return "petform";
}
petRepository.save(pet);
return "redirect:/";
}
@RequestMapping("/detail/{id}")
public String showPet(@PathVariable("id") long id, Model model) {
model.addAttribute("pet", petRepository.findOne(id));
return "show";
}
@RequestMapping("/update/{id}")
public String updatePet(@PathVariable("id") long id, Model model) {
model.addAttribute("pet", petRepository.findOne(id));
return "petform";
}
@RequestMapping("/delete/{id}")
public String delPet(@PathVariable("id") long id, Model model) {
petRepository.delete(id);
return "redirect:/";
}
@RequestMapping("/search")
public String getSearchString() {
return "search";
}
@PostMapping("/searchlist")
public String searchRepository(@RequestParam String searchfield,
@RequestParam String searchStr, Model model) {
if (searchfield.equalsIgnoreCase("name")) {
List<Pet> list = petRepository.findAllByNameContains(searchStr);
model.addAttribute("list", list);
model.addAttribute("field","name");
model.addAttribute("searchstr", searchStr);
} else if (searchfield.equalsIgnoreCase("age")) {
List<Pet> list = petRepository.findAllByAgeContains(searchStr);
model.addAttribute("list", list);
model.addAttribute("field","age");
model.addAttribute("searchstr", searchStr);
} else if (searchfield.equalsIgnoreCase("type")) {
List<Pet> list = petRepository.findAllByTypeContains (searchStr);
model.addAttribute("list", list);
model.addAttribute("field","type");
model.addAttribute("searchstr", searchStr);
} else if (searchfield.equalsIgnoreCase("breed")) {
List<Pet> list = petRepository.findAllByBreedContains(searchStr);
model.addAttribute("list", list);
model.addAttribute("field","breed");
model.addAttribute("searchstr", searchStr);
} else if (searchfield.equalsIgnoreCase("color")) {
List<Pet> list = petRepository.findAllByColorContains(searchStr);
model.addAttribute("list", list);
model.addAttribute("field","color");
model.addAttribute("searchstr", searchStr);
} else if (searchfield.equalsIgnoreCase("features")) {
List<Pet> list = petRepository.findAllByFeaturesContains(searchStr);
model.addAttribute("list", list);
model.addAttribute("field","features");
model.addAttribute("searchstr", searchStr);
} else if (searchfield.equalsIgnoreCase("phone")) {
List<Pet> list = petRepository.findAllByPhoneContains(searchStr);
model.addAttribute("list", list);
model.addAttribute("field","phone");
model.addAttribute("searchstr", searchStr);
} else if (searchfield.equalsIgnoreCase("currentstatus")) {
List<Pet> list = petRepository.findAllByCurrentStatusContains(searchStr);
model.addAttribute("field","status");
model.addAttribute("list", list);
model.addAttribute("searchstr", searchStr);
}
return "searchlist";
}
@RequestMapping("/home")
public String goHome () {
return "home";
}
}
| true
|
ebcc841159ff7b779261919ef2f3863f7c560148
|
Java
|
tesfai05/jenkins-exercise
|
/src/main/java/com/tesfai/jenkins/controller/SampleController.java
|
UTF-8
| 512
| 2.203125
| 2
|
[] |
no_license
|
package com.tesfai.jenkins.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SampleController {
@GetMapping("/home")
public String sampleMethod() {
return "Jenkins is working fine";
}
@GetMapping("/welcome/{name}")
public String welcomeMethod(@PathVariable String name) {
return name+", Welcome to Jenkins tutorial !";
}
}
| true
|
0b726ce328cf58171da7dff7295a375625278043
|
Java
|
MelyukhovDmitrii/Messenger
|
/src/me/melyukhov/messenger/common/packages/MessageType.java
|
UTF-8
| 162
| 1.554688
| 2
|
[
"MIT"
] |
permissive
|
package me.melyukhov.messenger.common.packages;
public enum MessageType {
USER_NAME,
PASSWORD,
TEXT_MESSAGE,
PUBLIC_KEY,
PRIVATE_KEY,
AES_KEY
}
| true
|
410f40f8f14ac9ceb3c23176a64898b4ab4a75c0
|
Java
|
fizzy-bubalech/ClientChessApp
|
/app/src/main/java/com/example/clientchessapp/MainActivity.java
|
UTF-8
| 3,559
| 2.25
| 2
|
[] |
no_license
|
package com.example.clientchessapp;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
OkHttpClient client = new OkHttpClient();
ProtocolObject deadman_switch = new ProtocolObject();
Call get(String url, Callback callback) {
Request request = new Request.Builder()
.url(url)
.build();
Call call = client.newCall(request);
call.enqueue(callback);
return call;
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(this.deadman_switch == null) {
this.deadman_switch = new ProtocolObject();
this.deadman_switch.deadman_start();
}
Button play_online = findViewById(R.id.play_online);
final TextView tv1 = findViewById(R.id.test);
String used_url = "https://fizzychess-server.herokuapp.com/";
ProtocolObject request = new ProtocolObject(getApplicationContext());
request.writeToFile("cock",getApplicationContext());
final TextView test = findViewById(R.id.file_test);
test.setText(request.readFile(getFilesDir().toString(),"game.txt"));
Callback callback = new Callback() {
@Override
public void onFailure(@NotNull Call call, @NotNull IOException e) {
e.printStackTrace();
tv1.setText("SERVER:Failed 2 Connect");
}
@Override
public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
if (response.isSuccessful()) {
final String rs = response.body().string();
MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
tv1.setText("SERVER:Connected Successfully");
}
});
}
}
};
this.get(used_url,callback);
play_online.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this , MatchSetup.class);
startActivity(intent);
}
});
}
@Override
protected void onStart() {
super.onStart();
if(this.deadman_switch == null) {
this.deadman_switch = new ProtocolObject();
this.deadman_switch.deadman_start();
}
}
@Override
protected void onPause(){
super.onPause();
Handler deadman_handler = this.deadman_switch.get_deadman_handler();
Runnable deadman_runnable = this.deadman_switch.getDeadman_runnable();
if(deadman_runnable != null) {
deadman_handler.removeCallbacks(deadman_runnable); //Stops the deadman switch on this activity
}
}
}
| true
|
c313d061664fbaa48047b5af6f858da092f24375
|
Java
|
crazyhand89/Zane-Xtras-11.2
|
/src/main/java/zanextras/items/armor/ZaneArmorMaterial.java
|
UTF-8
| 1,681
| 2.21875
| 2
|
[] |
no_license
|
package zanextras.items.armor;
import net.minecraft.init.SoundEvents;
import net.minecraft.item.ItemArmor.ArmorMaterial;
import net.minecraftforge.common.util.EnumHelper;
public class ZaneArmorMaterial {
public static ArmorMaterial BUTTER = EnumHelper.addArmorMaterial("Butter",
"zanextras:butter", 15, new int[] { 2, 7, 6, 2 }, 11,
SoundEvents.ITEM_ARMOR_EQUIP_IRON, 0);
public static ArmorMaterial EMERALD = EnumHelper.addArmorMaterial("Emerald",
"zanextras:emerald", 50, new int[] { 3, 9, 6, 2 }, 20,
SoundEvents.ITEM_ARMOR_EQUIP_DIAMOND, 3.0F);
public static ArmorMaterial STARIA = EnumHelper.addArmorMaterial("Staria",
"zanextras:staria", 200, new int[] { 4, 9, 6, 3 }, 95,
SoundEvents.ITEM_ARMOR_EQUIP_DIAMOND, 6.0F);
public static ArmorMaterial ZANIUM = EnumHelper.addArmorMaterial("Zanium",
"zanextras:zanium", 200, new int[] { 4, 9, 6, 3 }, 95,
SoundEvents.ITEM_ARMOR_EQUIP_DIAMOND, 6.0F);
public static ArmorMaterial SKYIUM = EnumHelper.addArmorMaterial("Skyium",
"zanextras:skyium", 70, new int[] { 3, 9, 6, 2 }, 80,
SoundEvents.ITEM_ARMOR_EQUIP_DIAMOND, 3.0F);
public static ArmorMaterial ZOGITE = EnumHelper.addArmorMaterial("Zogite",
"zanextras:zogite", 70, new int[] { 3, 9, 6, 2 }, 80,
SoundEvents.ITEM_ARMOR_EQUIP_DIAMOND, 3.0F);
public static ArmorMaterial RADITE = EnumHelper.addArmorMaterial("Radite",
"zanextras:radite", 70, new int[] { 3, 9, 6, 2 }, 80,
SoundEvents.ITEM_ARMOR_EQUIP_DIAMOND, 3.0F);
public static ArmorMaterial FOOLSTARIA = EnumHelper.addArmorMaterial(
"FoolStaria", "zanextras:foolstaria", 70, new int[] { 2, 7, 6, 2 },
11, SoundEvents.ITEM_ARMOR_EQUIP_IRON, 0.0F);
}
| true
|
a3eb6946d28ccac143f372da7d0ef26350d39625
|
Java
|
DeanHe/Practice
|
/LeetCodePractice/src/contest/RemovingMinimumAndMaximumFromArray.java
|
UTF-8
| 2,281
| 4.25
| 4
|
[] |
no_license
|
package contest;
/*
You are given a 0-indexed array of distinct integers nums.
There is an element in nums that has the lowest value and an element that has the highest value. We call them the minimum and maximum respectively. Your goal is to remove both these elements from the array.
A deletion is defined as either removing an element from the front of the array or removing an element from the back of the array.
Return the minimum number of deletions it would take to remove both the minimum and maximum element from the array.
Example 1:
Input: nums = [2,10,7,5,4,1,8,6]
Output: 5
Explanation:
The minimum element in the array is nums[5], which is 1.
The maximum element in the array is nums[1], which is 10.
We can remove both the minimum and maximum by removing 2 elements from the front and 3 elements from the back.
This results in 2 + 3 = 5 deletions, which is the minimum number possible.
Example 2:
Input: nums = [0,-4,19,1,8,-2,-3,5]
Output: 3
Explanation:
The minimum element in the array is nums[1], which is -4.
The maximum element in the array is nums[2], which is 19.
We can remove both the minimum and maximum by removing 3 elements from the front.
This results in only 3 deletions, which is the minimum number possible.
Example 3:
Input: nums = [101]
Output: 1
Explanation:
There is only one element in the array, which makes it both the minimum and maximum element.
We can remove it with 1 deletion.
Constraints:
1 <= nums.length <= 10^5
-10^5 <= nums[i] <= 10^5
The integers in nums are distinct.
*/
public class RemovingMinimumAndMaximumFromArray {
public int minimumDeletions(int[] nums) {
int len = nums.length, most = Integer.MIN_VALUE, least = Integer.MAX_VALUE, mostIdx = -1, leastIdx = -1;
for(int i = 0; i < len; i++){
if(nums[i] > most){
most = nums[i];
mostIdx = i;
}
if(nums[i] < least){
least = nums[i];
leastIdx = i;
}
}
int res = Math.max(mostIdx + 1, leastIdx + 1);
res = Math.min(res, Math.max(len - mostIdx, len - leastIdx));
res = Math.min(res, mostIdx + 1 + len - leastIdx);
res = Math.min(res, leastIdx + 1 + len - mostIdx);
return res;
}
}
| true
|
777f010c9478e3671a79b77020ae4e8a38d05872
|
Java
|
skkuse-adv/2019Fall_team2
|
/analysis/reverse-engineering/decompile-fitts-20191031-2200/sources/kr/co/popone/fitts/viewmodel/home/HomeModule.java
|
UTF-8
| 1,519
| 1.507813
| 2
|
[
"Apache-2.0"
] |
permissive
|
package kr.co.popone.fitts.viewmodel.home;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModel;
import androidx.lifecycle.ViewModelProvider.Factory;
import androidx.lifecycle.ViewModelProviders;
import kotlin.jvm.internal.Intrinsics;
import kr.co.popone.fitts.eventtracker.EventTracker;
import kr.co.popone.fitts.feature.home.HomeFragment;
import kr.co.popone.fitts.repository.home.HomeRepository;
import org.jetbrains.annotations.NotNull;
public final class HomeModule {
@NotNull
public final HomeViewModel provideHomeViewModel(@NotNull HomeFragment homeFragment, @NotNull HomeViewModelFactory homeViewModelFactory) {
Intrinsics.checkParameterIsNotNull(homeFragment, "fragment");
Intrinsics.checkParameterIsNotNull(homeViewModelFactory, "viewModelFactory");
ViewModel viewModel = ViewModelProviders.of((Fragment) homeFragment, (Factory) homeViewModelFactory).get(HomeViewModel.class);
Intrinsics.checkExpressionValueIsNotNull(viewModel, "ViewModelProviders.of(fr…meViewModel::class.java)]");
return (HomeViewModel) viewModel;
}
@NotNull
public final HomeViewModelFactory providesViewModelFactory(@NotNull HomeRepository homeRepository, @NotNull EventTracker eventTracker) {
Intrinsics.checkParameterIsNotNull(homeRepository, "repository");
Intrinsics.checkParameterIsNotNull(eventTracker, "eventTracker");
return new HomeViewModelFactory(homeRepository, eventTracker);
}
}
| true
|
c0c10a0ab154b9b0e9650d951ad1191beda6624e
|
Java
|
atcrew/a13
|
/src/java/atcrew/ce2mapper/ce2mapper/serial/SerialNavStroke.java
|
UTF-8
| 2,320
| 1.867188
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package atcrew.ce2mapper.ce2mapper.serial;
import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* @author atcrew
*/
//@XmlRootElement
public class SerialNavStroke /*implements Serializable*/ {
private static final long serialVersionUID = 1L;
private String ACTION;
private String FLD;
private String EVENT;
private String COND;
private String OP;
private String COMM;
private String status;
private String NAVN;
private String from;
private String cuser;
private String cdate;
public SerialNavStroke() {
}
public String getACTION() {
return ACTION;
}
public void setACTION(String ACTION) {
this.ACTION = ACTION;
}
public String getFLD() {
return FLD;
}
public void setFLD(String FLD) {
this.FLD = FLD;
}
public String getEVENT() {
return EVENT;
}
public void setEVENT(String EVENT) {
this.EVENT = EVENT;
}
public String getCOND() {
return COND;
}
public void setCOND(String COND) {
this.COND = COND;
}
public String getOP() {
return OP;
}
public void setOP(String OP) {
this.OP = OP;
}
public String getCOMM() {
return COMM;
}
public void setCOMM(String COMM) {
this.COMM = COMM;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getNAVN() {
return NAVN;
}
public void setNAVN(String NAVN) {
this.NAVN = NAVN;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getCuser() {
return cuser;
}
public void setCuser(String cuser) {
this.cuser = cuser;
}
public String getCdate() {
return cdate;
}
public void setCdate(String cdate) {
this.cdate = cdate;
}
}
| true
|
d329ba568c5f9f61dc9a519bf32a8344282563b6
|
Java
|
apache/lenya
|
/org.apache.lenya.core.impl/src/main/java/org/apache/lenya/xml/XLink.java
|
UTF-8
| 3,238
| 2.125
| 2
|
[
"Apache-2.0"
] |
permissive
|
/*
* 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.
*
*/
/* $Id$ */
package org.apache.lenya.xml;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
/**
* Helper class for XLinks
*/
public class XLink {
/**
* <code>type</code> The Xlink type
*/
public String type = null;
/**
* <code>href</code> The XLink href
*/
public String href = null;
/**
* <code>show</code> The value of the show attribute
*/
public String show = null;
/**
* <code>name</code> The Xlink name
*/
public String name = null;
/**
* <code>element</code> The Xlink element
*/
public Element element = null;
/**
* <code>XLINK_NAMESPACE</code> The XLink namespace
*/
public static final String XLINK_NAMESPACE = "http://www.w3.org/1999/xlink";
/**
* <code>ATTRIBUTE_HREF</code> The href attribte
*/
public static final String ATTRIBUTE_HREF = "href";
/**
* <code>ATTRIBUTE_SHOW</code> The show attribute
*/
public static final String ATTRIBUTE_SHOW = "show";
/**
* <code>ATTRIBUTE_TYPE</code> The type attribute
*/
public static final String ATTRIBUTE_TYPE = "type";
/**
* Constructor
*/
public XLink() {
this.type = "simple";
this.show = "undefined";
}
/**
* Constructor
* @param _element The element
*/
public XLink(Element _element) {
this();
this.element = _element;
this.name = _element.getNodeName();
Attr hrefAttribute = _element.getAttributeNodeNS(XLINK_NAMESPACE, ATTRIBUTE_HREF);
if (hrefAttribute != null) {
this.href = hrefAttribute.getNodeValue();
}
Attr typeAttribute = _element.getAttributeNodeNS(XLINK_NAMESPACE, ATTRIBUTE_TYPE);
if (typeAttribute != null) {
this.type = typeAttribute.getNodeValue();
}
Attr showAttribute = _element.getAttributeNodeNS(XLINK_NAMESPACE, ATTRIBUTE_SHOW);
if (showAttribute != null) {
this.show = showAttribute.getNodeValue();
}
}
/**
* Returns a printout of the XLink values
* @return The printout
*/
public String toString() {
return "XLink: type=\""
+ this.type
+ "\", href=\""
+ this.href
+ "\", show=\""
+ this.show
+ "\", name=\""
+ this.name
+ "\"";
}
}
| true
|
6e0509434404707cd111a800a825860bfa31b6bd
|
Java
|
YuriDomingos/Sistema-Solar-Completo-
|
/Planetas.java
|
UTF-8
| 1,449
| 2.609375
| 3
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sistemasolare21711;
import java.awt.Image;
import javax.swing.ImageIcon;
/**
*
* @author : Yuri Domingos
* Data : 11 - 11 - 2020
* Objectivo : Sistema Solar completo ( Com as leis de Kepler )
* UCAN : Universidade Católica de angola
* Disçciplina : Computacao Gráfica
*/
public class Planetas {
private int coordX ;
private int coordY;
private int largura;
private int altura;
/*
Podemos não ter uma class construtor aqui
*/
public Planetas() {
this.setCoordX(10);
this.setCoordY(10);
this.setLargura(10);
this.setAltura(10);
}
public int getCoordX() {
return coordX;
}
public void setCoordX(int coordX) {
this.coordX = coordX;
}
public int getCoordY() {
return coordY;
}
public void setCoordY(int coordY) {
this.coordY = coordY;
}
public int getLargura() {
return largura;
}
public void setLargura(int largura) {
this.largura = largura;
}
public int getAltura() {
return altura;
}
public void setAltura(int altura) {
this.altura = altura;
}
}
| true
|
1577c95f84fb649cb24ee4586fb424cdf4cb8b25
|
Java
|
Poovithapoovi/poovi.
|
/substringg.java
|
UTF-8
| 462
| 2.34375
| 2
|
[] |
no_license
|
#include<iostream>
using namespace std;
int main(){
string s1,s2;
cin>>s1;
cin>>s2;
int l1=s1.length();
int l2=s2.length();
int c=0;
string ss;
for(int i=0;i<l1;i++){
for(int j=0;j<=l1-i;j++){
ss="\0";
ss=s1.substr(i,j);
if(ss==s2){
c++;
break;
}
}
} if(c==1){
cout<<"yes"<<endl;
} else{
cout<<"no"<<endl;
}
}
| true
|
1f7592a536ca12feb29ce4317c561ef555fb0284
|
Java
|
juan987/Variaciones
|
/app/src/main/java/com/juan/variaciones/MainActivity.java
|
UTF-8
| 9,536
| 2.28125
| 2
|
[] |
no_license
|
package com.juan.variaciones;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import com.github.hiteshsondhi88.libffmpeg.ExecuteBinaryResponseHandler;
import com.github.hiteshsondhi88.libffmpeg.FFmpeg;
import com.github.hiteshsondhi88.libffmpeg.LoadBinaryResponseHandler;
import com.github.hiteshsondhi88.libffmpeg.exceptions.FFmpegCommandAlreadyRunningException;
import com.github.hiteshsondhi88.libffmpeg.exceptions.FFmpegNotSupportedException;
public class MainActivity extends AppCompatActivity {
public String xxx = this.getClass().getSimpleName();
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(xxx, "en onCreate" );
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
ejecutar();
}
});
//Para hacer la configuracion inicial de ffmpeg.
//Como en:
//http://writingminds.github.io/ffmpeg-android-java/
//y
//https://github.com/WritingMinds/ffmpeg-android-java
final ConfiguracionInicial configuracionInicial = new ConfiguracionInicial(this);
String dato = configuracionInicial.getValor();
if(dato == null){
//ejecutar la instalacion inicial
FFmpeg ffmpeg = FFmpeg.getInstance(this);
try {
ffmpeg.loadBinary(new LoadBinaryResponseHandler() {
@Override
public void onStart() {
Log.d(xxx, "en onCreate, ffmpeg.loadBinary, onStart" );
}
@Override
public void onFailure() {
Log.d(xxx, "en onCreate, ffmpeg.loadBinary, onFailure" );
}
@Override
public void onSuccess() {
Log.d(xxx, "en onCreate, ffmpeg.loadBinary, onSuccess" );
}
@Override
public void onFinish() {
Log.d(xxx, "en onCreate, ffmpeg.loadBinary, onFinish" );
configuracionInicial.setValor("Configuracion valida");
}
});
} catch (FFmpegNotSupportedException e) {
// Handle if FFmpeg is not supported by device
Log.d(xxx, "en onCreate, FFmpegNotSupportedException: " +e.getMessage());
}
ffmpeg = null;
}else {
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void ejecutar(){
//prueba_1_ffmpeg();
concat_two_videos_ffmpeg();
}
private void prueba_1_ffmpeg(){
//Este metodo es solo para obtener la version
FFmpeg ffmpeg = FFmpeg.getInstance(this);
try {
// to execute "ffmpeg -version" command you just need to pass "-version"
String[] cmd = new String[1];
cmd[0] ="-version";
ffmpeg.execute(cmd, new ExecuteBinaryResponseHandler() {
@Override
public void onStart() {
Log.d(xxx, "en prueba_1_ffmpeg, ffmpeg.execute, onStart" );
}
@Override
public void onProgress(String message) {
Log.d(xxx, "en prueba_1_ffmpeg, ffmpeg.execute, onProgress: " +message);
}
@Override
public void onFailure(String message) {
Log.d(xxx, "en prueba_1_ffmpeg, ffmpeg.execute, onFailure: " +message);
}
@Override
public void onSuccess(String message) {
Log.d(xxx, "en prueba_1_ffmpeg, ffmpeg.execute, onSuccess: " +message);
}
@Override
public void onFinish() {
Log.d(xxx, "en prueba_1_ffmpeg, ffmpeg.execute, onFinish" );
}
});
} catch (FFmpegCommandAlreadyRunningException e) {
// Handle if FFmpeg is already running
Log.d(xxx, "en prueba_1_ffmpeg, FFmpegCommandAlreadyRunningException: " +e.getMessage());
}
}//FIN de prueba_1_ffmpeg
private void concat_two_videos_ffmpeg(){
//Para los path de los ficheros, como en:
//http://oocms.org/question/2514896/how-to-mix-overlay-two-mp3-audio-file-into-one-mp3-file-not-concatenate
//Este metodo para concatenar 2 videos
String video_1 = Environment.getExternalStorageDirectory() + "/Variaciones/" +"video1.mp4";
String video_2 = Environment.getExternalStorageDirectory() + "/Variaciones/" +"video2.mp4";
String video_result = Environment.getExternalStorageDirectory() + "/Variaciones/" +"videoresult.mp4";
String audio_result = Environment.getExternalStorageDirectory() + "/Variaciones/" +"sound_test.mp3";
String audio_1 = Environment.getExternalStorageDirectory() + "/Variaciones/" +"ruido.mp3";
String audio_2 = Environment.getExternalStorageDirectory() + "/Variaciones/" +"Intro.mp3";
String audio_mezclado = Environment.getExternalStorageDirectory() + "/Variaciones/" +"audio-mezclado.mp3";
//Obtiene el audio del video mp4
/* este funciona
String[] cmd = new String[4];
cmd[0] = "-y";
cmd[1] = "-i";
cmd[2] = video_1;
cmd[3] = audio_result; */
//para concatenar dos videos, funciona
//como en
//https://github.com/bgrins/videoconverter.js/issues/18
/* String[] cmd = {"-i", video_1, "-i", video_2, "-v", "debug", "-strict", "-2", "-filter_complex",
"[0:v] [0:a:0] [1:v] [1:a:0] concat=n=2:v=1:a=1 [v] [a]", "-map", "[v]", "-map", "[a]", video_result}; */
//para mezclar 2 audios, mp3
//Como en
//https://stackoverflow.com/questions/31187153/merging-two-mp3-audio-files-using-ffmpeg
//String res = "-y -i " + a.getAbsolutePath() + " -i " + b.getAbsolutePath()
// + " -filter_complex '[0:0][1:0] amix=inputs=2:duration=longest' -c:a libmp3lame " + c.getAbsolutePath();
String[] cmd = {"-y", "-i", audio_1, "-i", audio_2, "-filter_complex",
//"[0:0][1:0] amix=inputs=2:duration=longest", "-c:a", "libmp3lame", audio_mezclado};
"[0:0][1:0] amix=inputs=2:duration=shortest", "-c:a", "libmp3lame", audio_mezclado};
//Con shortest o longer selecciono que dure el audio mas corto o mas largo
FFmpeg ffmpeg = FFmpeg.getInstance(this);
try {
// to execute "ffmpeg -version" command you just need to pass "-version"
//String[] cmd = new String[1];
//cmd[0] = stringComando;
ffmpeg.execute(cmd, new ExecuteBinaryResponseHandler() {
@Override
public void onStart() {
Log.d(xxx, "en concat_two_videos_ffmpeg, ffmpeg.execute, onStart" );
}
@Override
public void onProgress(String message) {
Log.d(xxx, "en concat_two_videos_ffmpeg, ffmpeg.execute, onProgress: " +message);
}
@Override
public void onFailure(String message) {
Log.d(xxx, "en concat_two_videos_ffmpeg, ffmpeg.execute, onFailure: " +message);
}
@Override
public void onSuccess(String message) {
Log.d(xxx, "en concat_two_videos_ffmpeg, ffmpeg.execute, onSuccess: " +message);
}
@Override
public void onFinish() {
Log.d(xxx, "en concat_two_videos_ffmpeg, ffmpeg.execute, onFinish" );
}
});
} catch (FFmpegCommandAlreadyRunningException e) {
// Handle if FFmpeg is already running
Log.d(xxx, "en concat_two_videos_ffmpeg, FFmpegCommandAlreadyRunningException: " +e.getMessage());
}
}//FIN de prueba_1_ffmpeg
}
| true
|
e0ab0d998917c0c8a013548beef2849513356dc7
|
Java
|
rajashekarvys/TestAnt
|
/webrtc-android-sample-app/src/main/java/io/antmedia/webrtc_android_sample_app/LoginActivity.java
|
UTF-8
| 3,941
| 2.015625
| 2
|
[] |
no_license
|
package io.antmedia.webrtc_android_sample_app;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.runtimepermissions.PermissionCallBack;
import com.runtimepermissions.PermissionsManager;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class LoginActivity extends AppCompatActivity {
private List<String> permissionsGrantee;
private TextView txtName,txtRoomId;
private Button btnConference;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
txtName = findViewById(R.id.name);
txtRoomId = findViewById(R.id.roomId);
btnConference = findViewById(R.id.btnConference);
checkPermission();
btnConference.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finishActivity();
}
});
}
private void checkPermission() {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
int camera = checkSelfPermission(Manifest.permission.CAMERA);
int audioSettings = checkSelfPermission(Manifest.permission.MODIFY_AUDIO_SETTINGS);
int recordAudio = checkSelfPermission(Manifest.permission.RECORD_AUDIO);
permissionsGrantee = new ArrayList<>();
if (audioSettings != PackageManager.PERMISSION_GRANTED) {
permissionsGrantee.add(Manifest.permission.MODIFY_AUDIO_SETTINGS);
}
if (recordAudio != PackageManager.PERMISSION_GRANTED) {
permissionsGrantee.add(Manifest.permission.RECORD_AUDIO);
}
if (camera != PackageManager.PERMISSION_GRANTED) {
permissionsGrantee.add(Manifest.permission.CAMERA);
}
if (!permissionsGrantee.isEmpty()) {
requestPermissions(permissionsGrantee.toArray(new String[permissionsGrantee.size()]), 11);
}
} else {
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 11) {
checkPermissionAfterResult(permissions, grantResults);
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void checkPermissionAfterResult(String[] permissions, int[] grantResults) {
int isAllGranteed = 0;
for (int i = 0; i < permissions.length; i++) {
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
isAllGranteed++;
} else if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
isAllGranteed--;
}
}
if (isAllGranteed == permissionsGrantee.size()) {
} else {
Toast.makeText(this, getResources().getString(R.string.enable_all_permission), Toast.LENGTH_SHORT).show();
finish();
}
}
void finishActivity(){
String streamId =txtName.getText().toString().trim();
String roomId =txtRoomId.getText().toString().trim();
String randomNum = String.valueOf((new Random().nextInt((999 - 100) + 1) + 100));
if (streamId.length()>0 && roomId.length()>0) {
Intent intent = new Intent(this, ConferenceActivity.class);
intent.putExtra("streamId",streamId + randomNum);
intent.putExtra("roomId", roomId);
startActivity(intent);
}
}
}
| true
|
2a4b596fda55da736bcc367fc1af494004c19648
|
Java
|
GSIL-Monitor/test-6
|
/src/main/java/com/yyq/car/portal/common/mapper/product/StoreMapper.java
|
UTF-8
| 824
| 1.84375
| 2
|
[] |
no_license
|
package com.yyq.car.portal.common.mapper.product;
import java.util.List;
import org.apache.ibatis.session.RowBounds;
import org.ufa.mybatis.stereotype.UfaMapper;
import com.yyq.car.portal.common.model.product.Store;
@UfaMapper
public interface StoreMapper {
int deleteByPrimaryKey(Integer id);
int insert(Store record);
int insertSelective(Store record);
Store selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(Store record);
int updateByPrimaryKey(Store record);
List<Store> selectByCriteria(Store record, RowBounds rowBounds);
List<Store> selectByCriteria(Store record);
int countByCriteria(Store record);
List<Store> jndstore();
List<Store> cStoreid();
//国外地区登录时查询相应的仓库
List<Store> userjndstore(Integer type);
List<Store> selectByCountry(Store st);
}
| true
|
81a3473ce399a3dd2f3fb027a4419899c95f0e34
|
Java
|
agaveplatform/science-apis
|
/agave-common/common-legacy-api/src/main/java/org/iplantc/service/common/representation/IplantSuccessRepresentation.java
|
UTF-8
| 839
| 2.390625
| 2
|
[
"BSD-3-Clause"
] |
permissive
|
/**
*
*/
package org.iplantc.service.common.representation;
/**
* @author dooley
*
*/
public class IplantSuccessRepresentation extends IplantRepresentation {
/**
* Creates a success response with no message and empty response body
*/
public IplantSuccessRepresentation()
{
this(null, null);
}
/**
* Create success representation with the JSON response
* @param jsonObject serialized response object
*/
public IplantSuccessRepresentation(String json)
{
this(null, json);
}
/**
* Create success representation with the message and JSON response
* @param message
* @param json serialized response object
*/
public IplantSuccessRepresentation(String message, String json)
{
super("success", message, json);
}
}
| true
|
c39ff5283537961e58008334524f09c5b6c7d43d
|
Java
|
lucaspetto/csv-marshaling
|
/src/main/java/com/example/demo/routes/MarshalRoute.java
|
UTF-8
| 509
| 2.0625
| 2
|
[] |
no_license
|
package com.example.demo.routes;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.dataformat.bindy.csv.BindyCsvDataFormat;
import org.apache.camel.spi.DataFormat;
import com.example.demo.repository.Person;
public class MarshalRoute extends RouteBuilder{
private DataFormat bindy = new BindyCsvDataFormat(Person.class);
@Override
public void configure() throws Exception {
from("direct:inputValue")
.marshal(bindy)
.to("file:data/csv/output/?fileName=output.txt");
}
}
| true
|
11abaf35081b4602f62e554580021751f890b822
|
Java
|
googleapis/google-cloud-java
|
/java-recaptchaenterprise/proto-google-cloud-recaptchaenterprise-v1beta1/src/main/java/com/google/recaptchaenterprise/v1beta1/TokenProperties.java
|
UTF-8
| 48,515
| 1.820313
| 2
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
/*
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/recaptchaenterprise/v1beta1/recaptchaenterprise.proto
package com.google.recaptchaenterprise.v1beta1;
/** Protobuf type {@code google.cloud.recaptchaenterprise.v1beta1.TokenProperties} */
public final class TokenProperties extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.recaptchaenterprise.v1beta1.TokenProperties)
TokenPropertiesOrBuilder {
private static final long serialVersionUID = 0L;
// Use TokenProperties.newBuilder() to construct.
private TokenProperties(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private TokenProperties() {
invalidReason_ = 0;
hostname_ = "";
action_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new TokenProperties();
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.recaptchaenterprise.v1beta1.RecaptchaEnterpriseProto
.internal_static_google_cloud_recaptchaenterprise_v1beta1_TokenProperties_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.recaptchaenterprise.v1beta1.RecaptchaEnterpriseProto
.internal_static_google_cloud_recaptchaenterprise_v1beta1_TokenProperties_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.recaptchaenterprise.v1beta1.TokenProperties.class,
com.google.recaptchaenterprise.v1beta1.TokenProperties.Builder.class);
}
/**
*
*
* <pre>
* Enum that represents the types of invalid token reasons.
* </pre>
*
* Protobuf enum {@code google.cloud.recaptchaenterprise.v1beta1.TokenProperties.InvalidReason}
*/
public enum InvalidReason implements com.google.protobuf.ProtocolMessageEnum {
/**
*
*
* <pre>
* Default unspecified type.
* </pre>
*
* <code>INVALID_REASON_UNSPECIFIED = 0;</code>
*/
INVALID_REASON_UNSPECIFIED(0),
/**
*
*
* <pre>
* If the failure reason was not accounted for.
* </pre>
*
* <code>UNKNOWN_INVALID_REASON = 1;</code>
*/
UNKNOWN_INVALID_REASON(1),
/**
*
*
* <pre>
* The provided user verification token was malformed.
* </pre>
*
* <code>MALFORMED = 2;</code>
*/
MALFORMED(2),
/**
*
*
* <pre>
* The user verification token had expired.
* </pre>
*
* <code>EXPIRED = 3;</code>
*/
EXPIRED(3),
/**
*
*
* <pre>
* The user verification had already been seen.
* </pre>
*
* <code>DUPE = 4;</code>
*/
DUPE(4),
/**
*
*
* <pre>
* The user verification token did not match the provided site key.
* This may be a configuration error (for example, development keys used in
* production) or end users trying to use verification tokens from other
* sites.
* </pre>
*
* <code>SITE_MISMATCH = 5 [deprecated = true];</code>
*/
@java.lang.Deprecated
SITE_MISMATCH(5),
/**
*
*
* <pre>
* The user verification token was not present. It is a required input.
* </pre>
*
* <code>MISSING = 6;</code>
*/
MISSING(6),
/**
*
*
* <pre>
* A retriable error (such as network failure) occurred on the browser.
* Could easily be simulated by an attacker.
* </pre>
*
* <code>BROWSER_ERROR = 7;</code>
*/
BROWSER_ERROR(7),
UNRECOGNIZED(-1),
;
/**
*
*
* <pre>
* Default unspecified type.
* </pre>
*
* <code>INVALID_REASON_UNSPECIFIED = 0;</code>
*/
public static final int INVALID_REASON_UNSPECIFIED_VALUE = 0;
/**
*
*
* <pre>
* If the failure reason was not accounted for.
* </pre>
*
* <code>UNKNOWN_INVALID_REASON = 1;</code>
*/
public static final int UNKNOWN_INVALID_REASON_VALUE = 1;
/**
*
*
* <pre>
* The provided user verification token was malformed.
* </pre>
*
* <code>MALFORMED = 2;</code>
*/
public static final int MALFORMED_VALUE = 2;
/**
*
*
* <pre>
* The user verification token had expired.
* </pre>
*
* <code>EXPIRED = 3;</code>
*/
public static final int EXPIRED_VALUE = 3;
/**
*
*
* <pre>
* The user verification had already been seen.
* </pre>
*
* <code>DUPE = 4;</code>
*/
public static final int DUPE_VALUE = 4;
/**
*
*
* <pre>
* The user verification token did not match the provided site key.
* This may be a configuration error (for example, development keys used in
* production) or end users trying to use verification tokens from other
* sites.
* </pre>
*
* <code>SITE_MISMATCH = 5 [deprecated = true];</code>
*/
@java.lang.Deprecated public static final int SITE_MISMATCH_VALUE = 5;
/**
*
*
* <pre>
* The user verification token was not present. It is a required input.
* </pre>
*
* <code>MISSING = 6;</code>
*/
public static final int MISSING_VALUE = 6;
/**
*
*
* <pre>
* A retriable error (such as network failure) occurred on the browser.
* Could easily be simulated by an attacker.
* </pre>
*
* <code>BROWSER_ERROR = 7;</code>
*/
public static final int BROWSER_ERROR_VALUE = 7;
public final int getNumber() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalArgumentException(
"Can't get the number of an unknown enum value.");
}
return value;
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
* @deprecated Use {@link #forNumber(int)} instead.
*/
@java.lang.Deprecated
public static InvalidReason valueOf(int value) {
return forNumber(value);
}
/**
* @param value The numeric wire value of the corresponding enum entry.
* @return The enum associated with the given numeric wire value.
*/
public static InvalidReason forNumber(int value) {
switch (value) {
case 0:
return INVALID_REASON_UNSPECIFIED;
case 1:
return UNKNOWN_INVALID_REASON;
case 2:
return MALFORMED;
case 3:
return EXPIRED;
case 4:
return DUPE;
case 5:
return SITE_MISMATCH;
case 6:
return MISSING;
case 7:
return BROWSER_ERROR;
default:
return null;
}
}
public static com.google.protobuf.Internal.EnumLiteMap<InvalidReason> internalGetValueMap() {
return internalValueMap;
}
private static final com.google.protobuf.Internal.EnumLiteMap<InvalidReason> internalValueMap =
new com.google.protobuf.Internal.EnumLiteMap<InvalidReason>() {
public InvalidReason findValueByNumber(int number) {
return InvalidReason.forNumber(number);
}
};
public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() {
if (this == UNRECOGNIZED) {
throw new java.lang.IllegalStateException(
"Can't get the descriptor of an unrecognized enum value.");
}
return getDescriptor().getValues().get(ordinal());
}
public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() {
return getDescriptor();
}
public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() {
return com.google.recaptchaenterprise.v1beta1.TokenProperties.getDescriptor()
.getEnumTypes()
.get(0);
}
private static final InvalidReason[] VALUES = values();
public static InvalidReason valueOf(com.google.protobuf.Descriptors.EnumValueDescriptor desc) {
if (desc.getType() != getDescriptor()) {
throw new java.lang.IllegalArgumentException("EnumValueDescriptor is not for this type.");
}
if (desc.getIndex() == -1) {
return UNRECOGNIZED;
}
return VALUES[desc.getIndex()];
}
private final int value;
private InvalidReason(int value) {
this.value = value;
}
// @@protoc_insertion_point(enum_scope:google.cloud.recaptchaenterprise.v1beta1.TokenProperties.InvalidReason)
}
public static final int VALID_FIELD_NUMBER = 1;
private boolean valid_ = false;
/**
*
*
* <pre>
* Whether the provided user response token is valid. When valid = false, the
* reason could be specified in invalid_reason or it could also be due to
* a user failing to solve a challenge or a sitekey mismatch (i.e the sitekey
* used to generate the token was different than the one specified in the
* assessment).
* </pre>
*
* <code>bool valid = 1;</code>
*
* @return The valid.
*/
@java.lang.Override
public boolean getValid() {
return valid_;
}
public static final int INVALID_REASON_FIELD_NUMBER = 2;
private int invalidReason_ = 0;
/**
*
*
* <pre>
* Reason associated with the response when valid = false.
* </pre>
*
* <code>
* .google.cloud.recaptchaenterprise.v1beta1.TokenProperties.InvalidReason invalid_reason = 2;
* </code>
*
* @return The enum numeric value on the wire for invalidReason.
*/
@java.lang.Override
public int getInvalidReasonValue() {
return invalidReason_;
}
/**
*
*
* <pre>
* Reason associated with the response when valid = false.
* </pre>
*
* <code>
* .google.cloud.recaptchaenterprise.v1beta1.TokenProperties.InvalidReason invalid_reason = 2;
* </code>
*
* @return The invalidReason.
*/
@java.lang.Override
public com.google.recaptchaenterprise.v1beta1.TokenProperties.InvalidReason getInvalidReason() {
com.google.recaptchaenterprise.v1beta1.TokenProperties.InvalidReason result =
com.google.recaptchaenterprise.v1beta1.TokenProperties.InvalidReason.forNumber(
invalidReason_);
return result == null
? com.google.recaptchaenterprise.v1beta1.TokenProperties.InvalidReason.UNRECOGNIZED
: result;
}
public static final int CREATE_TIME_FIELD_NUMBER = 3;
private com.google.protobuf.Timestamp createTime_;
/**
*
*
* <pre>
* The timestamp corresponding to the generation of the token.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 3;</code>
*
* @return Whether the createTime field is set.
*/
@java.lang.Override
public boolean hasCreateTime() {
return createTime_ != null;
}
/**
*
*
* <pre>
* The timestamp corresponding to the generation of the token.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 3;</code>
*
* @return The createTime.
*/
@java.lang.Override
public com.google.protobuf.Timestamp getCreateTime() {
return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_;
}
/**
*
*
* <pre>
* The timestamp corresponding to the generation of the token.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 3;</code>
*/
@java.lang.Override
public com.google.protobuf.TimestampOrBuilder getCreateTimeOrBuilder() {
return createTime_ == null ? com.google.protobuf.Timestamp.getDefaultInstance() : createTime_;
}
public static final int HOSTNAME_FIELD_NUMBER = 4;
@SuppressWarnings("serial")
private volatile java.lang.Object hostname_ = "";
/**
*
*
* <pre>
* The hostname of the page on which the token was generated.
* </pre>
*
* <code>string hostname = 4;</code>
*
* @return The hostname.
*/
@java.lang.Override
public java.lang.String getHostname() {
java.lang.Object ref = hostname_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
hostname_ = s;
return s;
}
}
/**
*
*
* <pre>
* The hostname of the page on which the token was generated.
* </pre>
*
* <code>string hostname = 4;</code>
*
* @return The bytes for hostname.
*/
@java.lang.Override
public com.google.protobuf.ByteString getHostnameBytes() {
java.lang.Object ref = hostname_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
hostname_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
public static final int ACTION_FIELD_NUMBER = 5;
@SuppressWarnings("serial")
private volatile java.lang.Object action_ = "";
/**
*
*
* <pre>
* Action name provided at token generation.
* </pre>
*
* <code>string action = 5;</code>
*
* @return The action.
*/
@java.lang.Override
public java.lang.String getAction() {
java.lang.Object ref = action_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
action_ = s;
return s;
}
}
/**
*
*
* <pre>
* Action name provided at token generation.
* </pre>
*
* <code>string action = 5;</code>
*
* @return The bytes for action.
*/
@java.lang.Override
public com.google.protobuf.ByteString getActionBytes() {
java.lang.Object ref = action_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
action_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (valid_ != false) {
output.writeBool(1, valid_);
}
if (invalidReason_
!= com.google.recaptchaenterprise.v1beta1.TokenProperties.InvalidReason
.INVALID_REASON_UNSPECIFIED
.getNumber()) {
output.writeEnum(2, invalidReason_);
}
if (createTime_ != null) {
output.writeMessage(3, getCreateTime());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(hostname_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 4, hostname_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(action_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 5, action_);
}
getUnknownFields().writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (valid_ != false) {
size += com.google.protobuf.CodedOutputStream.computeBoolSize(1, valid_);
}
if (invalidReason_
!= com.google.recaptchaenterprise.v1beta1.TokenProperties.InvalidReason
.INVALID_REASON_UNSPECIFIED
.getNumber()) {
size += com.google.protobuf.CodedOutputStream.computeEnumSize(2, invalidReason_);
}
if (createTime_ != null) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(3, getCreateTime());
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(hostname_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(4, hostname_);
}
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(action_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(5, action_);
}
size += getUnknownFields().getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.recaptchaenterprise.v1beta1.TokenProperties)) {
return super.equals(obj);
}
com.google.recaptchaenterprise.v1beta1.TokenProperties other =
(com.google.recaptchaenterprise.v1beta1.TokenProperties) obj;
if (getValid() != other.getValid()) return false;
if (invalidReason_ != other.invalidReason_) return false;
if (hasCreateTime() != other.hasCreateTime()) return false;
if (hasCreateTime()) {
if (!getCreateTime().equals(other.getCreateTime())) return false;
}
if (!getHostname().equals(other.getHostname())) return false;
if (!getAction().equals(other.getAction())) return false;
if (!getUnknownFields().equals(other.getUnknownFields())) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + VALID_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashBoolean(getValid());
hash = (37 * hash) + INVALID_REASON_FIELD_NUMBER;
hash = (53 * hash) + invalidReason_;
if (hasCreateTime()) {
hash = (37 * hash) + CREATE_TIME_FIELD_NUMBER;
hash = (53 * hash) + getCreateTime().hashCode();
}
hash = (37 * hash) + HOSTNAME_FIELD_NUMBER;
hash = (53 * hash) + getHostname().hashCode();
hash = (37 * hash) + ACTION_FIELD_NUMBER;
hash = (53 * hash) + getAction().hashCode();
hash = (29 * hash) + getUnknownFields().hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.recaptchaenterprise.v1beta1.TokenProperties parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.recaptchaenterprise.v1beta1.TokenProperties parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.recaptchaenterprise.v1beta1.TokenProperties parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.recaptchaenterprise.v1beta1.TokenProperties parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.recaptchaenterprise.v1beta1.TokenProperties parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.recaptchaenterprise.v1beta1.TokenProperties parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.recaptchaenterprise.v1beta1.TokenProperties parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.recaptchaenterprise.v1beta1.TokenProperties parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.recaptchaenterprise.v1beta1.TokenProperties parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.recaptchaenterprise.v1beta1.TokenProperties parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.recaptchaenterprise.v1beta1.TokenProperties parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.recaptchaenterprise.v1beta1.TokenProperties parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.recaptchaenterprise.v1beta1.TokenProperties prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/** Protobuf type {@code google.cloud.recaptchaenterprise.v1beta1.TokenProperties} */
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.recaptchaenterprise.v1beta1.TokenProperties)
com.google.recaptchaenterprise.v1beta1.TokenPropertiesOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.recaptchaenterprise.v1beta1.RecaptchaEnterpriseProto
.internal_static_google_cloud_recaptchaenterprise_v1beta1_TokenProperties_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.recaptchaenterprise.v1beta1.RecaptchaEnterpriseProto
.internal_static_google_cloud_recaptchaenterprise_v1beta1_TokenProperties_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.recaptchaenterprise.v1beta1.TokenProperties.class,
com.google.recaptchaenterprise.v1beta1.TokenProperties.Builder.class);
}
// Construct using com.google.recaptchaenterprise.v1beta1.TokenProperties.newBuilder()
private Builder() {}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
}
@java.lang.Override
public Builder clear() {
super.clear();
bitField0_ = 0;
valid_ = false;
invalidReason_ = 0;
createTime_ = null;
if (createTimeBuilder_ != null) {
createTimeBuilder_.dispose();
createTimeBuilder_ = null;
}
hostname_ = "";
action_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.recaptchaenterprise.v1beta1.RecaptchaEnterpriseProto
.internal_static_google_cloud_recaptchaenterprise_v1beta1_TokenProperties_descriptor;
}
@java.lang.Override
public com.google.recaptchaenterprise.v1beta1.TokenProperties getDefaultInstanceForType() {
return com.google.recaptchaenterprise.v1beta1.TokenProperties.getDefaultInstance();
}
@java.lang.Override
public com.google.recaptchaenterprise.v1beta1.TokenProperties build() {
com.google.recaptchaenterprise.v1beta1.TokenProperties result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.recaptchaenterprise.v1beta1.TokenProperties buildPartial() {
com.google.recaptchaenterprise.v1beta1.TokenProperties result =
new com.google.recaptchaenterprise.v1beta1.TokenProperties(this);
if (bitField0_ != 0) {
buildPartial0(result);
}
onBuilt();
return result;
}
private void buildPartial0(com.google.recaptchaenterprise.v1beta1.TokenProperties result) {
int from_bitField0_ = bitField0_;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.valid_ = valid_;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.invalidReason_ = invalidReason_;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.createTime_ = createTimeBuilder_ == null ? createTime_ : createTimeBuilder_.build();
}
if (((from_bitField0_ & 0x00000008) != 0)) {
result.hostname_ = hostname_;
}
if (((from_bitField0_ & 0x00000010) != 0)) {
result.action_ = action_;
}
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.recaptchaenterprise.v1beta1.TokenProperties) {
return mergeFrom((com.google.recaptchaenterprise.v1beta1.TokenProperties) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.recaptchaenterprise.v1beta1.TokenProperties other) {
if (other == com.google.recaptchaenterprise.v1beta1.TokenProperties.getDefaultInstance())
return this;
if (other.getValid() != false) {
setValid(other.getValid());
}
if (other.invalidReason_ != 0) {
setInvalidReasonValue(other.getInvalidReasonValue());
}
if (other.hasCreateTime()) {
mergeCreateTime(other.getCreateTime());
}
if (!other.getHostname().isEmpty()) {
hostname_ = other.hostname_;
bitField0_ |= 0x00000008;
onChanged();
}
if (!other.getAction().isEmpty()) {
action_ = other.action_;
bitField0_ |= 0x00000010;
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 8:
{
valid_ = input.readBool();
bitField0_ |= 0x00000001;
break;
} // case 8
case 16:
{
invalidReason_ = input.readEnum();
bitField0_ |= 0x00000002;
break;
} // case 16
case 26:
{
input.readMessage(getCreateTimeFieldBuilder().getBuilder(), extensionRegistry);
bitField0_ |= 0x00000004;
break;
} // case 26
case 34:
{
hostname_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000008;
break;
} // case 34
case 42:
{
action_ = input.readStringRequireUtf8();
bitField0_ |= 0x00000010;
break;
} // case 42
default:
{
if (!super.parseUnknownField(input, extensionRegistry, tag)) {
done = true; // was an endgroup tag
}
break;
} // default:
} // switch (tag)
} // while (!done)
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.unwrapIOException();
} finally {
onChanged();
} // finally
return this;
}
private int bitField0_;
private boolean valid_;
/**
*
*
* <pre>
* Whether the provided user response token is valid. When valid = false, the
* reason could be specified in invalid_reason or it could also be due to
* a user failing to solve a challenge or a sitekey mismatch (i.e the sitekey
* used to generate the token was different than the one specified in the
* assessment).
* </pre>
*
* <code>bool valid = 1;</code>
*
* @return The valid.
*/
@java.lang.Override
public boolean getValid() {
return valid_;
}
/**
*
*
* <pre>
* Whether the provided user response token is valid. When valid = false, the
* reason could be specified in invalid_reason or it could also be due to
* a user failing to solve a challenge or a sitekey mismatch (i.e the sitekey
* used to generate the token was different than the one specified in the
* assessment).
* </pre>
*
* <code>bool valid = 1;</code>
*
* @param value The valid to set.
* @return This builder for chaining.
*/
public Builder setValid(boolean value) {
valid_ = value;
bitField0_ |= 0x00000001;
onChanged();
return this;
}
/**
*
*
* <pre>
* Whether the provided user response token is valid. When valid = false, the
* reason could be specified in invalid_reason or it could also be due to
* a user failing to solve a challenge or a sitekey mismatch (i.e the sitekey
* used to generate the token was different than the one specified in the
* assessment).
* </pre>
*
* <code>bool valid = 1;</code>
*
* @return This builder for chaining.
*/
public Builder clearValid() {
bitField0_ = (bitField0_ & ~0x00000001);
valid_ = false;
onChanged();
return this;
}
private int invalidReason_ = 0;
/**
*
*
* <pre>
* Reason associated with the response when valid = false.
* </pre>
*
* <code>
* .google.cloud.recaptchaenterprise.v1beta1.TokenProperties.InvalidReason invalid_reason = 2;
* </code>
*
* @return The enum numeric value on the wire for invalidReason.
*/
@java.lang.Override
public int getInvalidReasonValue() {
return invalidReason_;
}
/**
*
*
* <pre>
* Reason associated with the response when valid = false.
* </pre>
*
* <code>
* .google.cloud.recaptchaenterprise.v1beta1.TokenProperties.InvalidReason invalid_reason = 2;
* </code>
*
* @param value The enum numeric value on the wire for invalidReason to set.
* @return This builder for chaining.
*/
public Builder setInvalidReasonValue(int value) {
invalidReason_ = value;
bitField0_ |= 0x00000002;
onChanged();
return this;
}
/**
*
*
* <pre>
* Reason associated with the response when valid = false.
* </pre>
*
* <code>
* .google.cloud.recaptchaenterprise.v1beta1.TokenProperties.InvalidReason invalid_reason = 2;
* </code>
*
* @return The invalidReason.
*/
@java.lang.Override
public com.google.recaptchaenterprise.v1beta1.TokenProperties.InvalidReason getInvalidReason() {
com.google.recaptchaenterprise.v1beta1.TokenProperties.InvalidReason result =
com.google.recaptchaenterprise.v1beta1.TokenProperties.InvalidReason.forNumber(
invalidReason_);
return result == null
? com.google.recaptchaenterprise.v1beta1.TokenProperties.InvalidReason.UNRECOGNIZED
: result;
}
/**
*
*
* <pre>
* Reason associated with the response when valid = false.
* </pre>
*
* <code>
* .google.cloud.recaptchaenterprise.v1beta1.TokenProperties.InvalidReason invalid_reason = 2;
* </code>
*
* @param value The invalidReason to set.
* @return This builder for chaining.
*/
public Builder setInvalidReason(
com.google.recaptchaenterprise.v1beta1.TokenProperties.InvalidReason value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000002;
invalidReason_ = value.getNumber();
onChanged();
return this;
}
/**
*
*
* <pre>
* Reason associated with the response when valid = false.
* </pre>
*
* <code>
* .google.cloud.recaptchaenterprise.v1beta1.TokenProperties.InvalidReason invalid_reason = 2;
* </code>
*
* @return This builder for chaining.
*/
public Builder clearInvalidReason() {
bitField0_ = (bitField0_ & ~0x00000002);
invalidReason_ = 0;
onChanged();
return this;
}
private com.google.protobuf.Timestamp createTime_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>
createTimeBuilder_;
/**
*
*
* <pre>
* The timestamp corresponding to the generation of the token.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 3;</code>
*
* @return Whether the createTime field is set.
*/
public boolean hasCreateTime() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
*
*
* <pre>
* The timestamp corresponding to the generation of the token.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 3;</code>
*
* @return The createTime.
*/
public com.google.protobuf.Timestamp getCreateTime() {
if (createTimeBuilder_ == null) {
return createTime_ == null
? com.google.protobuf.Timestamp.getDefaultInstance()
: createTime_;
} else {
return createTimeBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* The timestamp corresponding to the generation of the token.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 3;</code>
*/
public Builder setCreateTime(com.google.protobuf.Timestamp value) {
if (createTimeBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
createTime_ = value;
} else {
createTimeBuilder_.setMessage(value);
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* The timestamp corresponding to the generation of the token.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 3;</code>
*/
public Builder setCreateTime(com.google.protobuf.Timestamp.Builder builderForValue) {
if (createTimeBuilder_ == null) {
createTime_ = builderForValue.build();
} else {
createTimeBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* The timestamp corresponding to the generation of the token.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 3;</code>
*/
public Builder mergeCreateTime(com.google.protobuf.Timestamp value) {
if (createTimeBuilder_ == null) {
if (((bitField0_ & 0x00000004) != 0)
&& createTime_ != null
&& createTime_ != com.google.protobuf.Timestamp.getDefaultInstance()) {
getCreateTimeBuilder().mergeFrom(value);
} else {
createTime_ = value;
}
} else {
createTimeBuilder_.mergeFrom(value);
}
bitField0_ |= 0x00000004;
onChanged();
return this;
}
/**
*
*
* <pre>
* The timestamp corresponding to the generation of the token.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 3;</code>
*/
public Builder clearCreateTime() {
bitField0_ = (bitField0_ & ~0x00000004);
createTime_ = null;
if (createTimeBuilder_ != null) {
createTimeBuilder_.dispose();
createTimeBuilder_ = null;
}
onChanged();
return this;
}
/**
*
*
* <pre>
* The timestamp corresponding to the generation of the token.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 3;</code>
*/
public com.google.protobuf.Timestamp.Builder getCreateTimeBuilder() {
bitField0_ |= 0x00000004;
onChanged();
return getCreateTimeFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* The timestamp corresponding to the generation of the token.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 3;</code>
*/
public com.google.protobuf.TimestampOrBuilder getCreateTimeOrBuilder() {
if (createTimeBuilder_ != null) {
return createTimeBuilder_.getMessageOrBuilder();
} else {
return createTime_ == null
? com.google.protobuf.Timestamp.getDefaultInstance()
: createTime_;
}
}
/**
*
*
* <pre>
* The timestamp corresponding to the generation of the token.
* </pre>
*
* <code>.google.protobuf.Timestamp create_time = 3;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>
getCreateTimeFieldBuilder() {
if (createTimeBuilder_ == null) {
createTimeBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.protobuf.Timestamp,
com.google.protobuf.Timestamp.Builder,
com.google.protobuf.TimestampOrBuilder>(
getCreateTime(), getParentForChildren(), isClean());
createTime_ = null;
}
return createTimeBuilder_;
}
private java.lang.Object hostname_ = "";
/**
*
*
* <pre>
* The hostname of the page on which the token was generated.
* </pre>
*
* <code>string hostname = 4;</code>
*
* @return The hostname.
*/
public java.lang.String getHostname() {
java.lang.Object ref = hostname_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
hostname_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* The hostname of the page on which the token was generated.
* </pre>
*
* <code>string hostname = 4;</code>
*
* @return The bytes for hostname.
*/
public com.google.protobuf.ByteString getHostnameBytes() {
java.lang.Object ref = hostname_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
hostname_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* The hostname of the page on which the token was generated.
* </pre>
*
* <code>string hostname = 4;</code>
*
* @param value The hostname to set.
* @return This builder for chaining.
*/
public Builder setHostname(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
hostname_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
/**
*
*
* <pre>
* The hostname of the page on which the token was generated.
* </pre>
*
* <code>string hostname = 4;</code>
*
* @return This builder for chaining.
*/
public Builder clearHostname() {
hostname_ = getDefaultInstance().getHostname();
bitField0_ = (bitField0_ & ~0x00000008);
onChanged();
return this;
}
/**
*
*
* <pre>
* The hostname of the page on which the token was generated.
* </pre>
*
* <code>string hostname = 4;</code>
*
* @param value The bytes for hostname to set.
* @return This builder for chaining.
*/
public Builder setHostnameBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
hostname_ = value;
bitField0_ |= 0x00000008;
onChanged();
return this;
}
private java.lang.Object action_ = "";
/**
*
*
* <pre>
* Action name provided at token generation.
* </pre>
*
* <code>string action = 5;</code>
*
* @return The action.
*/
public java.lang.String getAction() {
java.lang.Object ref = action_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
action_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Action name provided at token generation.
* </pre>
*
* <code>string action = 5;</code>
*
* @return The bytes for action.
*/
public com.google.protobuf.ByteString getActionBytes() {
java.lang.Object ref = action_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
action_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Action name provided at token generation.
* </pre>
*
* <code>string action = 5;</code>
*
* @param value The action to set.
* @return This builder for chaining.
*/
public Builder setAction(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
action_ = value;
bitField0_ |= 0x00000010;
onChanged();
return this;
}
/**
*
*
* <pre>
* Action name provided at token generation.
* </pre>
*
* <code>string action = 5;</code>
*
* @return This builder for chaining.
*/
public Builder clearAction() {
action_ = getDefaultInstance().getAction();
bitField0_ = (bitField0_ & ~0x00000010);
onChanged();
return this;
}
/**
*
*
* <pre>
* Action name provided at token generation.
* </pre>
*
* <code>string action = 5;</code>
*
* @param value The bytes for action to set.
* @return This builder for chaining.
*/
public Builder setActionBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
action_ = value;
bitField0_ |= 0x00000010;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.recaptchaenterprise.v1beta1.TokenProperties)
}
// @@protoc_insertion_point(class_scope:google.cloud.recaptchaenterprise.v1beta1.TokenProperties)
private static final com.google.recaptchaenterprise.v1beta1.TokenProperties DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.recaptchaenterprise.v1beta1.TokenProperties();
}
public static com.google.recaptchaenterprise.v1beta1.TokenProperties getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<TokenProperties> PARSER =
new com.google.protobuf.AbstractParser<TokenProperties>() {
@java.lang.Override
public TokenProperties parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
Builder builder = newBuilder();
try {
builder.mergeFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(builder.buildPartial());
} catch (com.google.protobuf.UninitializedMessageException e) {
throw e.asInvalidProtocolBufferException().setUnfinishedMessage(builder.buildPartial());
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e)
.setUnfinishedMessage(builder.buildPartial());
}
return builder.buildPartial();
}
};
public static com.google.protobuf.Parser<TokenProperties> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<TokenProperties> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.recaptchaenterprise.v1beta1.TokenProperties getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| true
|
0fb7e3f67bf17d2f63295801d80e70205f3cb2f0
|
Java
|
xhaiben/LeetCode
|
/src/TotalHammingDistance/Main.java
|
UTF-8
| 1,214
| 3.640625
| 4
|
[] |
no_license
|
package TotalHammingDistance;
/**
* Created by xhaiben on 2017/2/14.
*/
public class Main {
public static void main(String[] args) {
int[] nums = {4, 14, 2};
System.out.println(totalHammingDistance2(nums));
}
/**
* 循环相加 超时
*
* @param nums
* @return
*/
public static int totalHammingDistance(int[] nums) {
int n = 0;
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
n += hammingDistance(nums[i], nums[j]);
}
}
return n;
}
public static int hammingDistance(int a, int b) {
int x = a ^ b;
int count = 0;
while (x != 0) {
count++;
x &= (x - 1);
}
return count;
}
public static int totalHammingDistance2(int[] nums) {
int n = 0;
int length = nums.length;
for (int i = 0; i < 32; i++) {
int count = 0;
for (int num : nums) {
if (((num >> i) & 1) == 0) {
count++;
}
}
n += count * (length - count);
}
return n;
}
}
| true
|
12f19659fa7321edffca0c148714a6e59d933a1a
|
Java
|
pyp163/BlueTooth
|
/app/src/main/java/com/facebook/soloader/ExoSoSource.java
|
UTF-8
| 14,040
| 1.914063
| 2
|
[] |
no_license
|
package com.facebook.soloader;
import android.content.Context;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
public final class ExoSoSource extends UnpackingSoSource
{
public ExoSoSource(Context paramContext, String paramString)
{
super(paramContext, paramString);
}
protected UnpackingSoSource.Unpacker makeUnpacker()
throws IOException
{
return new ExoUnpacker(this);
}
private final class ExoUnpacker extends UnpackingSoSource.Unpacker
{
private final ExoSoSource.FileDso[] mDsos;
// ERROR //
ExoUnpacker(UnpackingSoSource arg2)
throws IOException
{
// Byte code:
// 0: aload_0
// 1: aload_1
// 2: putfield 22 com/facebook/soloader/ExoSoSource$ExoUnpacker:this$0 Lcom/facebook/soloader/ExoSoSource;
// 5: aload_0
// 6: invokespecial 25 com/facebook/soloader/UnpackingSoSource$Unpacker:<init> ()V
// 9: aload_1
// 10: getfield 29 com/facebook/soloader/ExoSoSource:mContext Landroid/content/Context;
// 13: astore_1
// 14: new 31 java/lang/StringBuilder
// 17: dup
// 18: invokespecial 32 java/lang/StringBuilder:<init> ()V
// 21: astore 8
// 23: aload 8
// 25: ldc 34
// 27: invokevirtual 38 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 30: pop
// 31: aload 8
// 33: aload_1
// 34: invokevirtual 44 android/content/Context:getPackageName ()Ljava/lang/String;
// 37: invokevirtual 38 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 40: pop
// 41: aload 8
// 43: ldc 46
// 45: invokevirtual 38 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 48: pop
// 49: new 48 java/io/File
// 52: dup
// 53: aload 8
// 55: invokevirtual 51 java/lang/StringBuilder:toString ()Ljava/lang/String;
// 58: invokespecial 54 java/io/File:<init> (Ljava/lang/String;)V
// 61: astore_1
// 62: new 56 java/util/ArrayList
// 65: dup
// 66: invokespecial 57 java/util/ArrayList:<init> ()V
// 69: astore 11
// 71: new 59 java/util/LinkedHashSet
// 74: dup
// 75: invokespecial 60 java/util/LinkedHashSet:<init> ()V
// 78: astore 12
// 80: invokestatic 66 com/facebook/soloader/SysUtil:getSupportedAbis ()[Ljava/lang/String;
// 83: astore 13
// 85: aload 13
// 87: arraylength
// 88: istore 5
// 90: iconst_0
// 91: istore_3
// 92: iload_3
// 93: iload 5
// 95: if_icmpge +417 -> 512
// 98: aload 13
// 100: iload_3
// 101: aaload
// 102: astore 9
// 104: new 48 java/io/File
// 107: dup
// 108: aload_1
// 109: aload 9
// 111: invokespecial 69 java/io/File:<init> (Ljava/io/File;Ljava/lang/String;)V
// 114: astore 8
// 116: aload 8
// 118: invokevirtual 73 java/io/File:isDirectory ()Z
// 121: ifne +6 -> 127
// 124: goto +291 -> 415
// 127: aload 12
// 129: aload 9
// 131: invokeinterface 79 2 0
// 136: pop
// 137: new 48 java/io/File
// 140: dup
// 141: aload 8
// 143: ldc 81
// 145: invokespecial 69 java/io/File:<init> (Ljava/io/File;Ljava/lang/String;)V
// 148: astore 9
// 150: aload 9
// 152: invokevirtual 84 java/io/File:isFile ()Z
// 155: ifne +6 -> 161
// 158: goto -34 -> 124
// 161: new 86 java/io/FileReader
// 164: dup
// 165: aload 9
// 167: invokespecial 89 java/io/FileReader:<init> (Ljava/io/File;)V
// 170: astore 9
// 172: new 91 java/io/BufferedReader
// 175: dup
// 176: aload 9
// 178: invokespecial 94 java/io/BufferedReader:<init> (Ljava/io/Reader;)V
// 181: astore 10
// 183: iconst_0
// 184: istore 4
// 186: aload 10
// 188: invokevirtual 97 java/io/BufferedReader:readLine ()Ljava/lang/String;
// 191: astore 14
// 193: aload 14
// 195: ifnull +191 -> 386
// 198: aload 14
// 200: invokevirtual 103 java/lang/String:length ()I
// 203: ifne +6 -> 209
// 206: goto -23 -> 183
// 209: aload 14
// 211: bipush 32
// 213: invokevirtual 107 java/lang/String:indexOf (I)I
// 216: istore 6
// 218: iload 6
// 220: iconst_m1
// 221: if_icmpne +44 -> 265
// 224: new 31 java/lang/StringBuilder
// 227: dup
// 228: invokespecial 32 java/lang/StringBuilder:<init> ()V
// 231: astore_1
// 232: aload_1
// 233: ldc 109
// 235: invokevirtual 38 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 238: pop
// 239: aload_1
// 240: aload 14
// 242: invokevirtual 38 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 245: pop
// 246: aload_1
// 247: ldc 111
// 249: invokevirtual 38 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 252: pop
// 253: new 113 java/lang/RuntimeException
// 256: dup
// 257: aload_1
// 258: invokevirtual 51 java/lang/StringBuilder:toString ()Ljava/lang/String;
// 261: invokespecial 114 java/lang/RuntimeException:<init> (Ljava/lang/String;)V
// 264: athrow
// 265: new 31 java/lang/StringBuilder
// 268: dup
// 269: invokespecial 32 java/lang/StringBuilder:<init> ()V
// 272: astore 15
// 274: aload 15
// 276: aload 14
// 278: iconst_0
// 279: iload 6
// 281: invokevirtual 118 java/lang/String:substring (II)Ljava/lang/String;
// 284: invokevirtual 38 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 287: pop
// 288: aload 15
// 290: ldc 120
// 292: invokevirtual 38 java/lang/StringBuilder:append (Ljava/lang/String;)Ljava/lang/StringBuilder;
// 295: pop
// 296: aload 15
// 298: invokevirtual 51 java/lang/StringBuilder:toString ()Ljava/lang/String;
// 301: astore 15
// 303: aload 11
// 305: invokevirtual 123 java/util/ArrayList:size ()I
// 308: istore 7
// 310: iload 4
// 312: iload 7
// 314: if_icmpge +252 -> 566
// 317: aload 11
// 319: iload 4
// 321: invokevirtual 127 java/util/ArrayList:get (I)Ljava/lang/Object;
// 324: checkcast 129 com/facebook/soloader/ExoSoSource$FileDso
// 327: getfield 133 com/facebook/soloader/ExoSoSource$FileDso:name Ljava/lang/String;
// 330: aload 15
// 332: invokevirtual 136 java/lang/String:equals (Ljava/lang/Object;)Z
// 335: ifeq +222 -> 557
// 338: iconst_1
// 339: istore 4
// 341: goto +228 -> 569
// 344: aload 14
// 346: iload 6
// 348: iconst_1
// 349: iadd
// 350: invokevirtual 139 java/lang/String:substring (I)Ljava/lang/String;
// 353: astore 14
// 355: aload 11
// 357: new 129 com/facebook/soloader/ExoSoSource$FileDso
// 360: dup
// 361: aload 15
// 363: aload 14
// 365: new 48 java/io/File
// 368: dup
// 369: aload 8
// 371: aload 14
// 373: invokespecial 69 java/io/File:<init> (Ljava/io/File;Ljava/lang/String;)V
// 376: invokespecial 142 com/facebook/soloader/ExoSoSource$FileDso:<init> (Ljava/lang/String;Ljava/lang/String;Ljava/io/File;)V
// 379: invokevirtual 143 java/util/ArrayList:add (Ljava/lang/Object;)Z
// 382: pop
// 383: goto +191 -> 574
// 386: aload_1
// 387: astore 8
// 389: aload 10
// 391: ifnull +8 -> 399
// 394: aload 10
// 396: invokevirtual 146 java/io/BufferedReader:close ()V
// 399: aload 8
// 401: astore_1
// 402: aload 9
// 404: ifnull +11 -> 415
// 407: aload 9
// 409: invokevirtual 147 java/io/FileReader:close ()V
// 412: aload 8
// 414: astore_1
// 415: iload_3
// 416: iconst_1
// 417: iadd
// 418: istore_3
// 419: goto -327 -> 92
// 422: astore_1
// 423: aconst_null
// 424: astore_2
// 425: goto +7 -> 432
// 428: astore_2
// 429: aload_2
// 430: athrow
// 431: astore_1
// 432: aload 10
// 434: ifnull +31 -> 465
// 437: aload_2
// 438: ifnull +22 -> 460
// 441: aload 10
// 443: invokevirtual 146 java/io/BufferedReader:close ()V
// 446: goto +19 -> 465
// 449: astore 8
// 451: aload_2
// 452: aload 8
// 454: invokevirtual 151 java/lang/Throwable:addSuppressed (Ljava/lang/Throwable;)V
// 457: goto +8 -> 465
// 460: aload 10
// 462: invokevirtual 146 java/io/BufferedReader:close ()V
// 465: aload_1
// 466: athrow
// 467: astore_1
// 468: aconst_null
// 469: astore_2
// 470: goto +7 -> 477
// 473: astore_2
// 474: aload_2
// 475: athrow
// 476: astore_1
// 477: aload 9
// 479: ifnull +31 -> 510
// 482: aload_2
// 483: ifnull +22 -> 505
// 486: aload 9
// 488: invokevirtual 147 java/io/FileReader:close ()V
// 491: goto +19 -> 510
// 494: astore 8
// 496: aload_2
// 497: aload 8
// 499: invokevirtual 151 java/lang/Throwable:addSuppressed (Ljava/lang/Throwable;)V
// 502: goto +8 -> 510
// 505: aload 9
// 507: invokevirtual 147 java/io/FileReader:close ()V
// 510: aload_1
// 511: athrow
// 512: aload_2
// 513: aload 12
// 515: aload 12
// 517: invokeinterface 152 1 0
// 522: anewarray 99 java/lang/String
// 525: invokeinterface 156 2 0
// 530: checkcast 158 [Ljava/lang/String;
// 533: invokevirtual 164 com/facebook/soloader/UnpackingSoSource:setSoSourceAbis ([Ljava/lang/String;)V
// 536: aload_0
// 537: aload 11
// 539: aload 11
// 541: invokevirtual 123 java/util/ArrayList:size ()I
// 544: anewarray 129 com/facebook/soloader/ExoSoSource$FileDso
// 547: invokevirtual 165 java/util/ArrayList:toArray ([Ljava/lang/Object;)[Ljava/lang/Object;
// 550: checkcast 166 [Lcom/facebook/soloader/ExoSoSource$FileDso;
// 553: putfield 168 com/facebook/soloader/ExoSoSource$ExoUnpacker:mDsos [Lcom/facebook/soloader/ExoSoSource$FileDso;
// 556: return
// 557: iload 4
// 559: iconst_1
// 560: iadd
// 561: istore 4
// 563: goto -253 -> 310
// 566: iconst_0
// 567: istore 4
// 569: iload 4
// 571: ifeq -227 -> 344
// 574: goto -391 -> 183
//
// Exception table:
// from to target type
// 186 193 422 finally
// 198 206 422 finally
// 209 218 422 finally
// 224 265 422 finally
// 265 310 422 finally
// 317 338 422 finally
// 344 383 422 finally
// 186 193 428 java/lang/Throwable
// 198 206 428 java/lang/Throwable
// 209 218 428 java/lang/Throwable
// 224 265 428 java/lang/Throwable
// 265 310 428 java/lang/Throwable
// 317 338 428 java/lang/Throwable
// 344 383 428 java/lang/Throwable
// 429 431 431 finally
// 441 446 449 java/lang/Throwable
// 172 183 467 finally
// 394 399 467 finally
// 441 446 467 finally
// 451 457 467 finally
// 460 465 467 finally
// 465 467 467 finally
// 172 183 473 java/lang/Throwable
// 394 399 473 java/lang/Throwable
// 451 457 473 java/lang/Throwable
// 460 465 473 java/lang/Throwable
// 465 467 473 java/lang/Throwable
// 474 476 476 finally
// 486 491 494 java/lang/Throwable
}
protected UnpackingSoSource.DsoManifest getDsoManifest()
throws IOException
{
return new UnpackingSoSource.DsoManifest(this.mDsos);
}
protected UnpackingSoSource.InputDsoIterator openDsoIterator()
throws IOException
{
return new FileBackedInputDsoIterator(null);
}
private final class FileBackedInputDsoIterator extends UnpackingSoSource.InputDsoIterator
{
private int mCurrentDso;
private FileBackedInputDsoIterator()
{
}
public boolean hasNext()
{
return this.mCurrentDso < ExoSoSource.ExoUnpacker.this.mDsos.length;
}
public UnpackingSoSource.InputDso next()
throws IOException
{
Object localObject1 = ExoSoSource.ExoUnpacker.this.mDsos;
int i = this.mCurrentDso;
this.mCurrentDso = (i + 1);
Object localObject2 = localObject1[i];
localObject1 = new FileInputStream(((ExoSoSource.FileDso)localObject2).backingFile);
try
{
localObject2 = new UnpackingSoSource.InputDso((UnpackingSoSource.Dso)localObject2, (InputStream)localObject1);
return localObject2;
}
finally
{
if (localObject1 != null)
((FileInputStream)localObject1).close();
}
}
}
}
private static final class FileDso extends UnpackingSoSource.Dso
{
final File backingFile;
FileDso(String paramString1, String paramString2, File paramFile)
{
super(paramString2);
this.backingFile = paramFile;
}
}
}
| true
|
b3e6603df1acc49f60c094e2a41234835808f104
|
Java
|
patelkrunal/puzzles
|
/ConcurrentExample/src/accounts/ConcurTest.java
|
UTF-8
| 5,430
| 3.609375
| 4
|
[] |
no_license
|
package accounts;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import javax.naming.InsufficientResourcesException;
/* This is kind of simulation of two bank accounts. Program below transfers money between them
in multithread environment
*
*/
class Transfer implements Callable<Boolean> {
Account acc1 = null;
Account acc2 = null;
int amount;
CountDownLatch startLatch = null;
static AtomicInteger id = new AtomicInteger(0);
public Transfer(Account acc1, Account acc2, int amount) {
this.acc1 = acc1;
this.acc2 = acc2;
this.amount = amount;
id.incrementAndGet();
System.out.println("New Thread created. id=" + id.get());
}
public Transfer(Account acc1, Account acc2, int amount, CountDownLatch cdl) {
this(acc1,acc2,amount);
System.out.println("New Thread created. id=" + id.get());
this.startLatch = cdl;
}
@Override
public Boolean call() throws Exception {
System.out.println("Waiting to start. id="+id);
startLatch.await();
if (acc1.getLock().tryLock(3, TimeUnit.SECONDS)) {
try {
if (acc2.getLock().tryLock(3, TimeUnit.SECONDS)) {
try {
if (acc1.getBalance() < 0) {
throw new InsufficientFundsException();
}
System.out.println("Got account 1,2 locks!");
acc1.withdraw(amount);
acc2.deposit(amount);
Thread.sleep(new Random().nextInt(1000));
} finally {
System.out.println("transfer completed. amount:"
+ amount);
System.out.println("Account 1: " + acc1.getBalance());
System.out.println("Account 2: " + acc2.getBalance());
acc2.getLock().unlock();
System.out.println("acc2 unlocked");
}
} else {
System.out.println("Fail! Account 2 is locked");
acc2.failCounter.incrementAndGet();
}
} finally {
acc1.getLock().unlock();
System.out.println("acc1 unlocked");
}
} else {
System.out.println("Fail! Account 1 is locked");
acc1.failCounter.incrementAndGet();
}
return true;
}
}
class Account {
private int balance = 0;
private Lock lock = new ReentrantLock();
AtomicInteger failCounter = new AtomicInteger();
public Account(int initalBalance) {
this.balance = initalBalance;
}
public Lock getLock() {
return this.lock;
}
public void withdraw(int amount) {
balance -= amount;
}
public void deposit(int amount) {
balance += amount;
}
public int getBalance() {
return balance;
}
public int getFailCount() {
return failCounter.get();
}
}
public class ConcurTest {
// transfer money from account1 to account2
public static void transfer(Account acc1, Account acc2, int amount)
throws InsufficientFundsException, InterruptedException {
if (acc1.getBalance() < 0)
throw new InsufficientFundsException();
if (acc1.getLock().tryLock(3, TimeUnit.SECONDS)) {
try {
if (acc2.getLock().tryLock(3, TimeUnit.SECONDS)) {
try {
System.out.println("Got account 1,2 locks!");
acc1.withdraw(amount);
acc2.deposit(amount);
} finally {
System.out.println("transfer completed. amount:"
+ amount);
System.out.println("Account 1: " + acc1.getBalance());
System.out.println("Account 2: " + acc2.getBalance());
acc2.getLock().unlock();
System.out.println("acc2 unlocked");
}
}
} finally {
System.out.println("acc1 unlocked");
acc1.getLock().unlock();
}
} else {
System.out.println("Account is locked");
acc1.failCounter.incrementAndGet();
acc2.failCounter.incrementAndGet();
}
}
public static void main(String[] args) {
final Account acc1 = new Account(1000);
final Account acc2 = new Account(3000);
CountDownLatch cdl = new CountDownLatch(1);
final ExecutorService service = Executors.newFixedThreadPool(3);
List<Future> futures = new ArrayList<Future>();
new Thread(new Runnable() {
@Override
public void run() {
while (!service.isTerminated()) {
try {
Thread.sleep(1050);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out
.println("Monitor: number of failed transfers (Account1): "
+ acc1.getFailCount());
System.out
.println("Monitor: number of failed transfers (Account2): "
+ acc2.getFailCount());
}
}
}).start();
for (int i = 0; i < 10; i++) {
futures.add(service.submit(new Transfer(acc1, acc2, new Random()
.nextInt(400),cdl
)));
cdl.countDown();
// futures.add(service.submit(new Transfer(acc2, acc1, new Random()
// .nextInt(400))));
}
service.shutdown();
System.out.println("Shutdown called!!");
for (Future future : futures) {
try {
future.get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("--- post execution dump:");
System.out.println("Account 1 info");
System.out.println(acc1.getBalance());
System.out.println(acc1.failCounter);
System.out.println("Account 2 info");
System.out.println(acc2.getBalance());
System.out.println(acc2.failCounter);
}
}
| true
|
635bdc8f0fc481c5254647ada3330a5e70762d04
|
Java
|
zjohnso/rs3-ge-app
|
/app/src/main/java/com/example/projectscape/Objects/DataEntry.java
|
UTF-8
| 784
| 2.890625
| 3
|
[] |
no_license
|
package com.example.projectscape.Objects;
import androidx.annotation.NonNull;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class DataEntry {
private Date date;
private int price;
private int index;
public DataEntry(long date, int price, int index) {
this.date = new Date(date);
this.price = price;
this.index = index;
}
public Date getDate() {
return date;
}
public int getPrice() {
return price;
}
public int getIndex() {
return index;
}
@Override
@NonNull
public String toString() {
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy", Locale.US);
return format.format(date) + " | " + price;
}
}
| true
|
584f08ee2946ffe27fd856e5c8a5f784c91019d0
|
Java
|
Training360/strukturavalto-java-public
|
/solutions/collectionsset/src/test/java/collectionshashset/StringsHandlerTest.java
|
UTF-8
| 1,155
| 2.59375
| 3
|
[] |
no_license
|
package collectionshashset;
import org.junit.jupiter.api.Test;
import helper.RandomStringGenerator;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class StringsHandlerTest {
@Test
public void checkNumberOfElementsInSet() {
Collection<String> testCollection = new RandomStringGenerator().createStrings(4, 500_000);
//When
Set<String> strings = new StringsHandler().filterUniqueStrings(testCollection);
//Then
assertTrue(strings.size() < testCollection.size());
}
@Test
public void checkNumberOfIdenticalElementsInSets() {
//Given
Set<String> strings = new HashSet<>(new RandomStringGenerator().createStrings(4, 500_000));
Set<String> anotherStrings = new HashSet<>(new RandomStringGenerator().createStrings(4, 500_000));
int a = strings.size();
int b = anotherStrings.size();
//When
strings = new StringsHandler().selectIdenticalStrings(strings, anotherStrings);
//Then
assertTrue(strings.size() < (a + b));
}
}
| true
|
abc2eca57d73ec6492de08a0d03542096dd2c387
|
Java
|
gmstrbytes/geode
|
/geode-apis-compatible-with-redis/src/distributedTest/java/org/apache/geode/redis/internal/executor/sortedset/ZAddDUnitTest.java
|
UTF-8
| 5,819
| 2.078125
| 2
|
[
"Apache-2.0",
"LicenseRef-scancode-unknown",
"BSD-3-Clause",
"MIT",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] |
permissive
|
/*
* 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 org.apache.geode.redis.internal.executor.sortedset;
import static org.apache.geode.distributed.ConfigurationProperties.MAX_WAIT_TIME_RECONNECT;
import static org.apache.geode.test.dunit.rules.RedisClusterStartupRule.DEFAULT_MAX_WAIT_TIME_RECONNECT;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import org.apache.geode.redis.ConcurrentLoopingThreads;
import org.apache.geode.test.awaitility.GeodeAwaitility;
import org.apache.geode.test.dunit.rules.MemberVM;
import org.apache.geode.test.dunit.rules.RedisClusterStartupRule;
public class ZAddDUnitTest {
@ClassRule
public static RedisClusterStartupRule clusterStartUp = new RedisClusterStartupRule(4);
private static final String LOCAL_HOST = "127.0.0.1";
private static final int SET_SIZE = 1000;
private static final int JEDIS_TIMEOUT =
Math.toIntExact(GeodeAwaitility.getTimeout().toMillis());
private static JedisCluster jedis;
private static MemberVM server1;
private static MemberVM server2;
private static MemberVM server3;
@BeforeClass
public static void classSetup() {
Properties locatorProperties = new Properties();
locatorProperties.setProperty(MAX_WAIT_TIME_RECONNECT, DEFAULT_MAX_WAIT_TIME_RECONNECT);
MemberVM locator = clusterStartUp.startLocatorVM(0, locatorProperties);
server1 = clusterStartUp.startRedisVM(1, locator.getPort());
server2 = clusterStartUp.startRedisVM(2, locator.getPort());
server3 = clusterStartUp.startRedisVM(3, locator.getPort());
int redisServerPort = clusterStartUp.getRedisPort(1);
jedis = new JedisCluster(new HostAndPort(LOCAL_HOST, redisServerPort), JEDIS_TIMEOUT);
}
@Before
public void testSetup() {
try (Jedis conn = jedis.getConnectionFromSlot(0)) {
conn.flushAll();
}
}
@AfterClass
public static void tearDown() {
jedis.close();
server1.stop();
server2.stop();
server3.stop();
}
@Test
public void shouldDistributeDataAmongCluster() {
String key = "key";
Map<String, Double> memberScoreMap = makeMemberScoreMap("member1-");
jedis.zadd(key, memberScoreMap);
for (String member : memberScoreMap.keySet()) {
Double score = jedis.zscore(key, member);
assertThat(score).isEqualTo(memberScoreMap.get(member));
}
}
@Test
public void shouldDistributeDataAmongCluster_givenConcurrentlyAddingDifferentDataToSameSet() {
String key = "key";
Map<String, Double> memberScoreMap1 = makeMemberScoreMap("member1-");
Map<String, Double> memberScoreMap2 = makeMemberScoreMap("member2-");
new ConcurrentLoopingThreads(SET_SIZE,
(i) -> jedis.zadd(key, memberScoreMap1),
(i) -> jedis.zadd(key, memberScoreMap2)).runInLockstep();
for (String member1 : memberScoreMap1.keySet()) {
Double score = jedis.zscore(key, member1);
assertThat(score).isEqualTo(memberScoreMap1.get(member1));
}
for (String member2 : memberScoreMap2.keySet()) {
Double score = jedis.zscore(key, member2);
assertThat(score).isEqualTo(memberScoreMap2.get(member2));
}
}
@Test
public void shouldDistributeDataAmongCluster_givenConcurrentlyAddingSameDataToSameSet() {
String key = "key";
Map<String, Double> memberScoreMap = makeMemberScoreMap("member1-");
new ConcurrentLoopingThreads(SET_SIZE,
(i) -> jedis.zadd(key, memberScoreMap),
(i) -> jedis.zadd(key, memberScoreMap)).run();
for (String member : memberScoreMap.keySet()) {
Double score = jedis.zscore(key, member);
assertThat(score).isEqualTo(memberScoreMap.get(member));
}
}
@Test
public void shouldDistributeDataAmongCluster_givenConcurrentlyAddingDifferentSets() {
String key1 = "key1";
String key2 = "key2";
Map<String, Double> memberScoreMap1 = makeMemberScoreMap("member1-");
Map<String, Double> memberScoreMap2 = makeMemberScoreMap("member2-");
new ConcurrentLoopingThreads(SET_SIZE,
(i) -> jedis.zadd(key1, memberScoreMap1),
(i) -> jedis.zadd(key2, memberScoreMap2)).runInLockstep();
for (String member1 : memberScoreMap1.keySet()) {
Double score = jedis.zscore(key1, member1);
assertThat(score).isEqualTo(memberScoreMap1.get(member1));
}
for (String member2 : memberScoreMap2.keySet()) {
Double score = jedis.zscore(key2, member2);
assertThat(score).isEqualTo(memberScoreMap2.get(member2));
}
}
private Map<String, Double> makeMemberScoreMap(String baseString) {
Map<String, Double> scoreMemberPairs = new HashMap<>();
for (int i = 0; i < SET_SIZE; i++) {
scoreMemberPairs.put(baseString + i, Double.valueOf(i + ""));
}
return scoreMemberPairs;
}
}
| true
|
5a111e154ae8858f556c1abd2aa8b8340011cb87
|
Java
|
TAIJI-zhanghd/homework
|
/springboot_security_hello/src/main/java/com/zhd/WebSecurityConfig.java
|
UTF-8
| 3,671
| 2.171875
| 2
|
[] |
no_license
|
package com.zhd;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import com.zhd.config.MyAuthenticationSuccessHandler;
import com.zhd.config.MyLogoutSuccessHandler;
@EnableWebSecurity(debug = true) //查看过滤器链
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
// @Bean
// public UserDetailsService userDetailsService() {
// InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
// manager.createUser(User.withUsername("1").password("1").roles("USER").build());
// manager.createUser(User.withUsername("2").password("2").roles("ADMIN").build());
// manager.createUser(User.withUsername("3").password("3").roles("DBA").build());
// manager.createUser(User.withUsername("4").password("4").roles("DBA","ADMIN").build());
// return manager;
// }
/**
* 认证管理相关
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// super.configure(auth);
auth.inMemoryAuthentication().withUser("1").password("1").roles("USER")
.and().withUser("2").password("2").roles("ADMIN")
.and().withUser("3").password("3").roles("DBA")
.and().withUser("4").password("4").roles("ADMIN","DBA");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/prelogin","/login","/resources/**", "/signup", "/about").permitAll()
.antMatchers("/admin/**").hasAnyRole("ADMIN", "USER")
.regexMatchers("^/a$").hasRole("ADMIN")
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")
.anyRequest().authenticated();
http
.formLogin()
.loginPage("/prelogin")
.loginProcessingUrl("/login")
.usernameParameter("username")
.passwordParameter("password")
//匿名内部类 实际开发中为避免new对象线程安全问题
//建议新创建一个类 并用@Bean 加载到容器中(也可以用Complent进行注入 但是不灵活)
.successHandler(MyAuthenticationSuccessHandler())
// .permitAll()
;
http
.logout()
.logoutUrl("/logout") //默认时/logout
// .logoutSuccessUrl("/prelogin")
.logoutSuccessHandler(MyLogoutSuccessHandler())
.deleteCookies("ZSESSIONID")
// .permitAll()
;
}
@Bean
public MyAuthenticationSuccessHandler MyAuthenticationSuccessHandler() {
return new MyAuthenticationSuccessHandler();
}
@Bean
public MyLogoutSuccessHandler MyLogoutSuccessHandler() {
return new MyLogoutSuccessHandler();
}
@Override
public void configure(WebSecurity web) throws Exception {
super.configure(web);
}
}
| true
|
8e58af847deee90efe4d31a434b62533c0b3cd8c
|
Java
|
franklinzou/lcslns
|
/java src/BinaryTreeMaximumPathSum.java
|
UTF-8
| 879
| 3.578125
| 4
|
[] |
no_license
|
/*
* Binary Tree Maximum Path Sum
* Tag: Tree
* Tag: Depth-first Search
*/
import java.util.*;
public class BinaryTreeMaximumPathSum {
int res = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
getLeftRightMax(root);
return res;
}
// get maximal result when AT MOST one branch is accessed through root
private int getLeftRightMax(TreeNode root){
if(root == null) return 0;
int lRes = getLeftRightMax(root.left), rRes = getLeftRightMax(root.right);
// the maximal result when AT MOST one branch is accessed through root
int singleRes = Math.max(Math.max(lRes, rRes), 0) + root.val;
// the maximal result when two branches are accessed through root
int doubleRes = lRes + rRes + root.val;
res = Math.max(res, Math.max(singleRes, doubleRes));
return singleRes;
}
}
| true
|
80a717aa84c2f21cc87b7be17fd644eff89780c2
|
Java
|
mal67/DungeonCraft
|
/src/main/java/greenteam/dungeoncraft/Util/FileReader.java
|
UTF-8
| 810
| 2.875
| 3
|
[] |
no_license
|
package greenteam.dungeoncraft.Util;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.io.File;
//read string from file
public class FileReader {
public String ReadFile(String FileLoc) {
StringBuilder source = new StringBuilder();
String filePath = new File("").getAbsolutePath();
List<String> lines = new ArrayList<String>();
try {
lines = Files.readAllLines(Paths.get(filePath + FileLoc));
for (String line : lines) {
source.append(line).append("\n");
}
} catch (IOException e) {
System.err.println( "FileReader could not load file from path: " + filePath + FileLoc );
e.printStackTrace();
}
return source.toString();
}
}
| true
|
0b7422ebaa0e262615e9b2577a0d0dd5d015a840
|
Java
|
hurtus/App
|
/GoShopping/app/src/main/java/com/goshopping/usx/goshopping/view/FilterView.java
|
UTF-8
| 7,426
| 1.890625
| 2
|
[] |
no_license
|
package com.goshopping.usx.goshopping.view;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.goshopping.usx.goshopping.R;
import java.util.ArrayList;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
/**
* Created by Si on 2016/11/5.
*/
public class FilterView extends LinearLayout implements View.OnClickListener {
//filer的文字和图标
@Bind(R.id.tv_brand)
TextView tvBrand;
@Bind(R.id.iv_brand_arrow)
ImageView ivBrandArrow;
@Bind(R.id.tv_city)
TextView tvCity;
@Bind(R.id.iv_city_arrow)
ImageView ivCityArrow;
@Bind(R.id.tv_rating)
TextView tvRating;
@Bind(R.id.iv_rating_arrow)
ImageView ivRatingArrow;
//包含了两个listview的linearlayout
@Bind(R.id.ll_content_list_view)
LinearLayout llContentListView;
//半透明的背景
@Bind(R.id.view_mask_bg)
View viewMaskBg;
//左边的listview
@Bind(R.id.lv_left)
ListView lvLeft;
//右边的listview
@Bind(R.id.lv_right)
ListView lvRight;
//品牌
@Bind(R.id.ll_brand)
LinearLayout llBrand;
//全城
@Bind(R.id.ll_city)
LinearLayout llCity;
//好评
@Bind(R.id.ll_rating)
LinearLayout llRating;
private Context mContext;
private boolean isShowing = false;
private int filterPosition = -1;
private int panelHeight;
private List<String> mBrandList;
private List<String> mCityList;
private List<String> mRatingList;
private List<String> mCityDetailList;
public FilterView(Context context) {
super(context);
Init(context);
}
public FilterView(Context context, AttributeSet attrs) {
super(context, attrs);
Init(context);
}
private void Init(Context context) {
mContext = context;
View view = LayoutInflater.from(context).inflate(R.layout.view_filter_layout, this);
ButterKnife.bind(this, view);
initData();
initView();
initListener();
}
private void initListener() {
llBrand.setOnClickListener(this);
llCity.setOnClickListener(this);
llRating.setOnClickListener(this);
viewMaskBg.setOnClickListener(this);
}
private void initView() {
viewMaskBg.setVisibility(GONE);
llContentListView.setVisibility(GONE);
}
private void initData() {
mBrandList = new ArrayList<>();
mBrandList.add("星美国际银城");
mBrandList.add("大地影院");
mBrandList.add("万达影院");
mBrandList.add("咸亨国际影城");
mCityList = new ArrayList<>();
mCityList.add("诸暨市");
mCityList.add("越城区");
mCityList.add("柯桥区");
mCityList.add("上虞区");
mRatingList = new ArrayList<>();
mRatingList.add("离我最近");
mRatingList.add("好评优先");
mRatingList.add("价格最低");
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.ll_brand:
updateTabState(0);
break;
case R.id.ll_city:
updateTabState(1);
break;
case R.id.ll_rating:
updateTabState(2);
break;
case R.id.view_mask_bg:
hide();
break;
}
}
//当发生点击事件的时候 ,判断点击的情况,更新tabs
public void updateTabState(int clickTabPos) {
hide();
if (filterPosition == clickTabPos) {
hide();
} else {
filterPosition = clickTabPos;
if (clickTabPos == 0) {
tvBrand.setTextColor(mContext.getResources().getColor(R.color.font_black_2));
ivBrandArrow.setImageResource(R.mipmap.home_up_arrow);
} else if (clickTabPos == 1) {
tvCity.setTextColor(mContext.getResources().getColor(R.color.font_black_2));
ivCityArrow.setImageResource(R.mipmap.home_up_arrow);
} else {
tvRating.setTextColor(mContext.getResources().getColor(R.color.font_black_2));
ivRatingArrow.setImageResource(R.mipmap.home_up_arrow);
}
show();
}
}
public void hide() {
isShowing = false;
resetFilterStatus();
viewMaskBg.setVisibility(View.GONE);
ObjectAnimator.ofFloat(llContentListView, "translationY", 0, -panelHeight).setDuration(200).start();
}
private void show() {
isShowing = true;
viewMaskBg.setVisibility(VISIBLE);
llContentListView.setVisibility(VISIBLE);
llContentListView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
llContentListView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
panelHeight = llContentListView.getHeight();
ObjectAnimator.ofFloat(llContentListView, "translationY", -panelHeight, 0).setDuration(200).start();
}
});
//my
lvRight.setVisibility(View.VISIBLE);
lvRight.setAdapter(new BaseAdapter() {
@Override
public int getCount() {
return mBrandList.size();
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.filter_right_item, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tv.setText(mBrandList.get(position));
return convertView;
}
});
}
// 复位筛选的显示状态
public void resetFilterStatus() {
filterPosition = -1;
tvBrand.setTextColor(mContext.getResources().getColor(R.color.font_black_2));
ivBrandArrow.setImageResource(R.mipmap.home_down_arrow);
tvCity.setTextColor(mContext.getResources().getColor(R.color.font_black_2));
ivCityArrow.setImageResource(R.mipmap.home_down_arrow);
tvRating.setTextColor(mContext.getResources().getColor(R.color.font_black_2));
ivRatingArrow.setImageResource(R.mipmap.home_down_arrow);
}
class ViewHolder {
public TextView tv;
ViewHolder(View v){
tv= (TextView) v.findViewById(R.id.tv);
}
}
}
| true
|
93435a07ef33ce57764fc08956ba26f9ef5fc77b
|
Java
|
TimofeyShved/SimbirSoft_2021
|
/src/main/java/com/example/SimbirSoft_2021/service/interfaceService/TaskServiceInterface.java
|
UTF-8
| 965
| 1.84375
| 2
|
[] |
no_license
|
package com.example.SimbirSoft_2021.service.interfaceService;
import com.example.SimbirSoft_2021.Dto.TaskDto;
import com.example.SimbirSoft_2021.exception.ReleaseNotFoundException;
import com.example.SimbirSoft_2021.exception.RoleNotFoundException;
import com.example.SimbirSoft_2021.exception.TaskNotFoundException;
import java.util.List;
public interface TaskServiceInterface {
public TaskDto findByReleaseId(Long releaseId) throws TaskNotFoundException;
public boolean deleteTaskByProjectId(Long projectId) throws TaskNotFoundException, ReleaseNotFoundException, RoleNotFoundException;
public boolean deleteReleaseInTask(Long id) throws TaskNotFoundException;
public List<TaskDto> getAllByStatus(Long projectId, String status) throws TaskNotFoundException;
public Long getCountByStatus(Long projectId, String status) throws TaskNotFoundException;
public List<TaskDto> getAllCustom(TaskDto cusomtaskDto) throws TaskNotFoundException;
}
| true
|
c17600c94fb260e24354539526dc6dc7ae7cc695
|
Java
|
nanosai/grid-ops-java
|
/src/main/java/com/nanosai/gridops/ion/read/IonFieldReaderNop.java
|
UTF-8
| 2,266
| 2.765625
| 3
|
[
"Apache-2.0"
] |
permissive
|
package com.nanosai.gridops.ion.read;
import com.nanosai.gridops.ion.IonFieldTypes;
/**
* Created by jjenkov on 05-11-2015.
*/
public class IonFieldReaderNop implements IIonFieldReader {
@Override
public int read(byte[] source, int sourceOffset, Object destination) {
int leadByte = 255 & source[sourceOffset++];
int fieldType = leadByte >> 4;
int lengthLength = leadByte & 15; // 7 = binary 00000111 - filters out 5 top bits
if(lengthLength == 0){
return 1; //field with null value is always 1 byte long
}
//todo skip correct amount of bytes - depending on field type. Not all field types have explicit length bytes.
switch(fieldType){
case IonFieldTypes.BOOLEAN: {
return 1;
}
case IonFieldTypes.UTF_8_SHORT: ;
case IonFieldTypes.UTC_DATE_TIME: ;
//case IonFieldTypes.COMPLEX_TYPE_ID_SHORT: ;
case IonFieldTypes.KEY_SHORT: ;
case IonFieldTypes.INT_POS: ;
case IonFieldTypes.INT_NEG: ;
case IonFieldTypes.FLOAT : {
return 1 + lengthLength;
}
case IonFieldTypes.EXTENDED : {
int fieldTypeExtended = source[sourceOffset++]; //read extended field type - first byte after lead byte
switch(fieldTypeExtended) {
case IonFieldTypes.ELEMENT_COUNT : {
return 1 + 1 + lengthLength; //element count uses extended short encoding.
}
}
return 1 + 1 + lengthLength; //default extended element encoding uses 1 byte for extended type
}
//fine for all fields that use the lengthLength field normally - meaning Normal length fields (not Short and Tiny).
default : {
int fieldLength = 0;
for(int i=0; i<lengthLength; i++){
fieldLength <<= 8;
fieldLength |= 255 & source[sourceOffset++];
}
return 1 + lengthLength + fieldLength;
}
}
}
@Override
public void setNull(Object destination) {
//do nothing, right?
}
}
| true
|
e33f13bbdff1253a2d933c0a2ea7fe06fe41814a
|
Java
|
ganlu19940318/Head-First
|
/Factory Pattern/Abstract Factory Pattern/src/PersonFactory.java
|
UTF-8
| 86
| 2.15625
| 2
|
[] |
no_license
|
public interface PersonFactory {
Car getCar();
Breakfirst getBreakfirst();
}
| true
|
4e3baa8386dff87aaadc842ddeae2fdd81796099
|
Java
|
Catherine22/WebServices
|
/WebServices/app/src/main/java/com/catherine/webservices/entities/WebViewAttr.java
|
UTF-8
| 20,371
| 1.773438
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.catherine.webservices.entities;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Build;
import android.webkit.WebSettings;
import com.catherine.webservices.R;
import java.util.Arrays;
/**
* Created by Catherine on 2017/10/23.
* Soft-World Inc.
* catherine919@soft-world.com.tw
*/
public class WebViewAttr {
private SharedPreferences sp;
private Context ctx;
//WebView Attribute
private boolean VerticalScrollBarEnabled = true;
private boolean HorizontalScrollBarEnabled = true;
//WebSettings
private boolean UseWideViewPort = true;
private boolean LoadWithOverviewMode = true;
private boolean BuiltInZoomControls = false;
private boolean SupportZoom = true;
private int TextZoom = 100;
private boolean DisplayZoomControls = false;
private boolean NeedInitialFocus = true;
private boolean JavaScriptEnabled = true;
private boolean JavaScriptCanOpenWindowsAutomatically = false;
private boolean LoadsImagesAutomatically = true;
private boolean GeolocationEnabled = true;
private boolean AllowContentAccess = true;
private boolean AllowFileAccess = true;
private boolean AllowUniversalAccessFromFileURLs = false;
private boolean AllowFileAccessFromFileURLs = false;
private boolean MediaPlaybackRequiresUserGesture = true;
private boolean SafeBrowsingEnabled = true;
private int DefaultFontSize = 16;
private int MinimumFontSize = 8;
private String DefaultTextEncodingName = "UTF-8";
private String StandardFontFamily = "sans-serif";
private int MixedContentMode = WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE;
private String UserAgent;
private String[] user_agent, user_agent_detail;
//Cache
private boolean SaveFormData = true;
private boolean DomStorageEnabled = true;
private boolean DatabaseEnabled = true;
private boolean AppCacheEnabled = true;
private int CacheMode = WebSettings.LOAD_DEFAULT;
public WebViewAttr(Context ctx) {
this.ctx = ctx;
user_agent = ctx.getResources().getStringArray(R.array.user_agent);
user_agent_detail = ctx.getResources().getStringArray(R.array.user_agent_detail);
sp = ctx.getSharedPreferences("wv_settings", Context.MODE_PRIVATE);
VerticalScrollBarEnabled = sp.getBoolean("VerticalScrollBarEnabled", true);
HorizontalScrollBarEnabled = sp.getBoolean("HorizontalScrollBarEnabled", true);
UseWideViewPort = sp.getBoolean("UseWideViewPort", true);
LoadWithOverviewMode = sp.getBoolean("LoadWithOverviewMode", true);
BuiltInZoomControls = sp.getBoolean("BuiltInZoomControls", false);
SupportZoom = sp.getBoolean("SupportZoom", true);
DisplayZoomControls = sp.getBoolean("DisplayZoomControls", false);
NeedInitialFocus = sp.getBoolean("NeedInitialFocus", true);
JavaScriptEnabled = sp.getBoolean("JavaScriptEnabled", true);
JavaScriptCanOpenWindowsAutomatically = sp.getBoolean("JavaScriptCanOpenWindowsAutomatically", false);
LoadsImagesAutomatically = sp.getBoolean("LoadsImagesAutomatically", true);
GeolocationEnabled = sp.getBoolean("GeolocationEnabled", true);
SaveFormData = sp.getBoolean("SaveFormData", true);
DomStorageEnabled = sp.getBoolean("DomStorageEnabled", true);
DatabaseEnabled = sp.getBoolean("DatabaseEnabled", true);
AppCacheEnabled = sp.getBoolean("AppCacheEnabled", true);
AllowContentAccess = sp.getBoolean("AllowContentAccess", true);
AllowFileAccess = sp.getBoolean("AllowFileAccess", true);
AllowUniversalAccessFromFileURLs = sp.getBoolean("AllowUniversalAccessFromFileURLs", false);
AllowFileAccessFromFileURLs = sp.getBoolean("AllowFileAccessFromFileURLs", false);
MediaPlaybackRequiresUserGesture = sp.getBoolean("MediaPlaybackRequiresUserGesture", true);
SafeBrowsingEnabled = sp.getBoolean("SafeBrowsingEnabled", true);
TextZoom = sp.getInt("TextZoom", 100);
DefaultFontSize = sp.getInt("DefaultFontSize", 16);
MinimumFontSize = sp.getInt("MinimumFontSize", 8);
DefaultTextEncodingName = sp.getString("DefaultTextEncodingName", "UTF-8");
StandardFontFamily = sp.getString("StandardFontFamily", "sans-serif");
CacheMode = sp.getInt("CacheMode", WebSettings.LOAD_DEFAULT);
MixedContentMode = sp.getInt("MixedContentMode", WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
UserAgent = sp.getString("UserAgent", user_agent[0]);
}
public boolean isVerticalScrollBarEnabled() {
VerticalScrollBarEnabled = sp.getBoolean("VerticalScrollBarEnabled", true);
return VerticalScrollBarEnabled;
}
public boolean isHorizontalScrollBarEnabled() {
HorizontalScrollBarEnabled = sp.getBoolean("HorizontalScrollBarEnabled", true);
return HorizontalScrollBarEnabled;
}
public boolean isUseWideViewPort() {
UseWideViewPort = sp.getBoolean("UseWideViewPort", true);
return UseWideViewPort;
}
public boolean isLoadWithOverviewMode() {
LoadWithOverviewMode = sp.getBoolean("LoadWithOverviewMode", true);
return LoadWithOverviewMode;
}
public boolean isBuiltInZoomControls() {
BuiltInZoomControls = sp.getBoolean("BuiltInZoomControls", false);
return BuiltInZoomControls;
}
public boolean isSupportZoom() {
SupportZoom = sp.getBoolean("SupportZoom", true);
return SupportZoom;
}
public boolean isDisplayZoomControls() {
DisplayZoomControls = sp.getBoolean("DisplayZoomControls", false);
return DisplayZoomControls;
}
public boolean isNeedInitialFocus() {
NeedInitialFocus = sp.getBoolean("NeedInitialFocus", true);
return NeedInitialFocus;
}
public boolean isJavaScriptEnabled() {
JavaScriptEnabled = sp.getBoolean("JavaScriptEnabled", true);
return JavaScriptEnabled;
}
public boolean isJavaScriptCanOpenWindowsAutomatically() {
JavaScriptCanOpenWindowsAutomatically = sp.getBoolean("JavaScriptCanOpenWindowsAutomatically", false);
return JavaScriptCanOpenWindowsAutomatically;
}
public boolean isAppCacheEnabled() {
AppCacheEnabled = sp.getBoolean("AppCacheEnabled", true);
return AppCacheEnabled;
}
public boolean isDatabaseEnabled() {
DatabaseEnabled = sp.getBoolean("DatabaseEnabled", true);
return DatabaseEnabled;
}
public boolean isSaveFormData() {
SaveFormData = sp.getBoolean("SaveFormData", true);
return SaveFormData;
}
public boolean isDomStorageEnabled() {
DomStorageEnabled = sp.getBoolean("DomStorageEnabled", true);
return DomStorageEnabled;
}
public boolean isLoadsImagesAutomatically() {
LoadsImagesAutomatically = sp.getBoolean("LoadsImagesAutomatically", true);
return LoadsImagesAutomatically;
}
public boolean isGeolocationEnabled() {
GeolocationEnabled = sp.getBoolean("GeolocationEnabled", true);
return GeolocationEnabled;
}
public boolean isAllowContentAccess() {
AllowContentAccess = sp.getBoolean("AllowContentAccess", true);
return AllowContentAccess;
}
public boolean isAllowFileAccess() {
AllowFileAccess = sp.getBoolean("AllowFileAccess", true);
return AllowFileAccess;
}
public boolean isAllowUniversalAccessFromFileURLs() {
AllowUniversalAccessFromFileURLs = sp.getBoolean("AllowUniversalAccessFromFileURLs", false);
return AllowUniversalAccessFromFileURLs;
}
public boolean isAllowFileAccessFromFileURLs() {
AllowFileAccessFromFileURLs = sp.getBoolean("AllowFileAccessFromFileURLs", false);
return AllowFileAccessFromFileURLs;
}
public boolean isMediaPlaybackRequiresUserGesture() {
MediaPlaybackRequiresUserGesture = sp.getBoolean("MediaPlaybackRequiresUserGesture", true);
return MediaPlaybackRequiresUserGesture;
}
public boolean isSafeBrowsingEnabled() {
SafeBrowsingEnabled = sp.getBoolean("SafeBrowsingEnabled", true);
return SafeBrowsingEnabled;
}
public int getTextZoom() {
TextZoom = sp.getInt("TextZoom", 100);
return TextZoom;
}
public int getDefaultFontSize() {
DefaultFontSize = sp.getInt("DefaultFontSize", 16);
return DefaultFontSize;
}
public int getMinimumFontSize() {
MinimumFontSize = sp.getInt("MinimumFontSize", 8);
return MinimumFontSize;
}
public String getDefaultTextEncodingName() {
DefaultTextEncodingName = sp.getString("DefaultTextEncodingName", "UTF-8");
return DefaultTextEncodingName;
}
public String getStandardFontFamily() {
StandardFontFamily = sp.getString("StandardFontFamily", "sans-serif");
return StandardFontFamily;
}
public int getCacheMode() {
CacheMode = sp.getInt("CacheMode", WebSettings.LOAD_DEFAULT);
return CacheMode;
}
//from WebSettings
public int getCacheMode(String name) {
if ("LOAD_DEFAULT".equals(name))
return -1;
else if ("LOAD_NORMAL".equals(name))
return 0;
else if ("LOAD_CACHE_ELSE_NETWORK".equals(name))
return 1;
else if ("LOAD_NO_CACHE".equals(name))
return 2;
else if ("LOAD_CACHE_ONLY".equals(name))
return 3;
else
return Integer.MAX_VALUE;
}
//from WebSettings
public String getCacheModeName(int cacheMode) {
switch (cacheMode) {
case -1:
return "LOAD_DEFAULT";
case 0:
return "LOAD_NORMAL";
case 1:
return "LOAD_CACHE_ELSE_NETWORK";
case 2:
return "LOAD_NO_CACHE";
case 3:
return "LOAD_CACHE_ONLY";
default:
return "NULL";
}
}
public int getMixedContentMode() {
MixedContentMode = sp.getInt("MixedContentMode", WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
return MixedContentMode;
}
//from WebSettings
public int getMixedContentMode(String name) {
if ("MIXED_CONTENT_ALWAYS_ALLOW".equals(name))
return 0;
else if ("MIXED_CONTENT_NEVER_ALLOW".equals(name))
return 1;
else if ("MIXED_CONTENT_COMPATIBILITY_MODE".equals(name))
return 2;
else
return Integer.MAX_VALUE;
}
public String getMixedContentModeName(int MixedContentMode) {
switch (MixedContentMode) {
case 0:
return "MIXED_CONTENT_ALWAYS_ALLOW";
case 1:
return "MIXED_CONTENT_NEVER_ALLOW";
case 2:
return "MIXED_CONTENT_COMPATIBILITY_MODE";
default:
return "NULL";
}
}
public String getUserAgent() {
UserAgent = sp.getString("UserAgent", user_agent[0]);
return UserAgent;
}
public String getUserAgentString(String UserAgent) {
String temp = "N/A";
for (int i = 0; i < user_agent.length; i++) {
if (user_agent[i].equals(UserAgent)) {
temp = user_agent_detail[i];
break;
}
}
if (user_agent[0].equals(UserAgent)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
temp = WebSettings.getDefaultUserAgent(ctx);
} else {
temp = System.getProperty("http.agent");
}
}
return temp;
}
public void setVerticalScrollBarEnabled(boolean VerticalScrollBarEnabled) {
this.VerticalScrollBarEnabled = VerticalScrollBarEnabled;
sp.edit().putBoolean("VerticalScrollBarEnabled", VerticalScrollBarEnabled).apply();
}
public void setHorizontalScrollBarEnabled(boolean HorizontalScrollBarEnabled) {
this.HorizontalScrollBarEnabled = HorizontalScrollBarEnabled;
sp.edit().putBoolean("HorizontalScrollBarEnabled", HorizontalScrollBarEnabled).apply();
}
public void setUseWideViewPort(boolean UseWideViewPort) {
this.UseWideViewPort = UseWideViewPort;
sp.edit().putBoolean("UseWideViewPort", UseWideViewPort).apply();
}
public void setLoadWithOverviewMode(boolean LoadWithOverviewMode) {
this.LoadWithOverviewMode = LoadWithOverviewMode;
sp.edit().putBoolean("LoadWithOverviewMode", LoadWithOverviewMode).apply();
}
public void setBuiltInZoomControls(boolean BuiltInZoomControls) {
this.BuiltInZoomControls = BuiltInZoomControls;
sp.edit().putBoolean("BuiltInZoomControls", BuiltInZoomControls).apply();
}
public void setSupportZoom(boolean SupportZoom) {
this.SupportZoom = SupportZoom;
sp.edit().putBoolean("SupportZoom", SupportZoom).apply();
}
public void setDisplayZoomControls(boolean DisplayZoomControls) {
this.DisplayZoomControls = DisplayZoomControls;
sp.edit().putBoolean("DisplayZoomControls", DisplayZoomControls).apply();
}
public void setNeedInitialFocus(boolean NeedInitialFocus) {
this.NeedInitialFocus = NeedInitialFocus;
sp.edit().putBoolean("NeedInitialFocus", NeedInitialFocus).apply();
}
public void setJavaScriptEnabled(boolean JavaScriptEnabled) {
this.JavaScriptEnabled = JavaScriptEnabled;
sp.edit().putBoolean("JavaScriptEnabled", JavaScriptEnabled).apply();
}
public void setJavaScriptCanOpenWindowsAutomatically(boolean JavaScriptCanOpenWindowsAutomatically) {
this.JavaScriptCanOpenWindowsAutomatically = JavaScriptCanOpenWindowsAutomatically;
sp.edit().putBoolean("JavaScriptCanOpenWindowsAutomatically", JavaScriptCanOpenWindowsAutomatically).apply();
}
public void setAppCacheEnabled(boolean AppCacheEnabled) {
this.AppCacheEnabled = AppCacheEnabled;
sp.edit().putBoolean("AppCacheEnabled", AppCacheEnabled).apply();
}
public void setSaveFormData(boolean SaveFormData) {
this.SaveFormData = SaveFormData;
sp.edit().putBoolean("SaveFormData", SaveFormData).apply();
}
public void setDomStorageEnabled(boolean DomStorageEnabled) {
this.DomStorageEnabled = DomStorageEnabled;
sp.edit().putBoolean("DomStorageEnabled", DomStorageEnabled).apply();
}
public void setDatabaseEnabled(boolean DatabaseEnabled) {
this.DatabaseEnabled = DatabaseEnabled;
sp.edit().putBoolean("DatabaseEnabled", DatabaseEnabled).apply();
}
public void setLoadsImagesAutomatically(boolean LoadsImagesAutomatically) {
this.LoadsImagesAutomatically = LoadsImagesAutomatically;
sp.edit().putBoolean("LoadsImagesAutomatically", LoadsImagesAutomatically).apply();
}
public void setGeolocationEnabled(boolean GeolocationEnabled) {
this.GeolocationEnabled = GeolocationEnabled;
sp.edit().putBoolean("GeolocationEnabled", GeolocationEnabled).apply();
}
public void setAllowContentAccess(boolean AllowContentAccess) {
this.AllowContentAccess = AllowContentAccess;
sp.edit().putBoolean("AllowContentAccess", AllowContentAccess).apply();
}
public void setAllowFileAccess(boolean AllowFileAccess) {
this.AllowFileAccess = AllowFileAccess;
sp.edit().putBoolean("AllowFileAccess", AllowFileAccess).apply();
}
public void setAllowUniversalAccessFromFileURLs(boolean AllowUniversalAccessFromFileURLs) {
this.AllowUniversalAccessFromFileURLs = AllowUniversalAccessFromFileURLs;
sp.edit().putBoolean("AllowUniversalAccessFromFileURLs", AllowUniversalAccessFromFileURLs).apply();
}
public void setAllowFileAccessFromFileURLs(boolean AllowFileAccessFromFileURLs) {
this.AllowFileAccessFromFileURLs = AllowFileAccessFromFileURLs;
sp.edit().putBoolean("AllowFileAccessFromFileURLs", AllowFileAccessFromFileURLs).apply();
}
public void setMediaPlaybackRequiresUserGesture(boolean MediaPlaybackRequiresUserGesture) {
this.MediaPlaybackRequiresUserGesture = MediaPlaybackRequiresUserGesture;
sp.edit().putBoolean("MediaPlaybackRequiresUserGesture", MediaPlaybackRequiresUserGesture).apply();
}
public void setSafeBrowsingEnabled(boolean SafeBrowsingEnabled) {
this.SafeBrowsingEnabled = SafeBrowsingEnabled;
sp.edit().putBoolean("SafeBrowsingEnabled", SafeBrowsingEnabled).apply();
}
public void setTextZoom(int TextZoom) {
this.TextZoom = TextZoom;
sp.edit().putInt("TextZoom", TextZoom).apply();
}
public void setDefaultFontSize(int DefaultFontSize) {
this.DefaultFontSize = DefaultFontSize;
sp.edit().putInt("DefaultFontSize", DefaultFontSize).apply();
}
public void setMinimumFontSize(int MinimumFontSize) {
this.MinimumFontSize = MinimumFontSize;
sp.edit().putInt("MinimumFontSize", MinimumFontSize).apply();
}
public void setDefaultTextEncodingName(String DefaultTextEncodingName) {
this.DefaultTextEncodingName = DefaultTextEncodingName;
sp.edit().putString("DefaultTextEncodingName", DefaultTextEncodingName).apply();
}
public void setStandardFontFamily(String StandardFontFamily) {
this.StandardFontFamily = StandardFontFamily;
sp.edit().putString("StandardFontFamily", StandardFontFamily).apply();
}
public void setCacheMode(int CacheMode) {
this.CacheMode = CacheMode;
sp.edit().putInt("CacheMode", CacheMode).apply();
}
public void setMixedContentMode(int MixedContentMode) {
this.MixedContentMode = MixedContentMode;
sp.edit().putInt("MixedContentMode", MixedContentMode).apply();
}
public void setUserAgent(String UserAgent) {
this.UserAgent = UserAgent;
sp.edit().putString("UserAgent", UserAgent).apply();
}
@Override
public String toString() {
return "WebViewAttr{" +
"sp=" + sp +
", ctx=" + ctx +
", VerticalScrollBarEnabled=" + VerticalScrollBarEnabled +
", HorizontalScrollBarEnabled=" + HorizontalScrollBarEnabled +
", UseWideViewPort=" + UseWideViewPort +
", LoadWithOverviewMode=" + LoadWithOverviewMode +
", BuiltInZoomControls=" + BuiltInZoomControls +
", SupportZoom=" + SupportZoom +
", TextZoom=" + TextZoom +
", DisplayZoomControls=" + DisplayZoomControls +
", NeedInitialFocus=" + NeedInitialFocus +
", JavaScriptEnabled=" + JavaScriptEnabled +
", JavaScriptCanOpenWindowsAutomatically=" + JavaScriptCanOpenWindowsAutomatically +
", LoadsImagesAutomatically=" + LoadsImagesAutomatically +
", GeolocationEnabled=" + GeolocationEnabled +
", SaveFormData=" + SaveFormData +
", DomStorageEnabled=" + DomStorageEnabled +
", DatabaseEnabled=" + DatabaseEnabled +
", AppCacheEnabled=" + AppCacheEnabled +
", AllowContentAccess=" + AllowContentAccess +
", AllowFileAccess=" + AllowFileAccess +
", AllowUniversalAccessFromFileURLs=" + AllowUniversalAccessFromFileURLs +
", AllowFileAccessFromFileURLs=" + AllowFileAccessFromFileURLs +
", MediaPlaybackRequiresUserGesture=" + MediaPlaybackRequiresUserGesture +
", SafeBrowsingEnabled=" + SafeBrowsingEnabled +
", DefaultFontSize=" + DefaultFontSize +
", MinimumFontSize=" + MinimumFontSize +
", DefaultTextEncodingName='" + DefaultTextEncodingName + '\'' +
", StandardFontFamily='" + StandardFontFamily + '\'' +
", CacheMode=" + CacheMode +
", MixedContentMode=" + MixedContentMode +
", UserAgent='" + UserAgent + '\'' +
", user_agent=" + Arrays.toString(user_agent) +
", user_agent_detail=" + Arrays.toString(user_agent_detail) +
'}';
}
}
| true
|
f48e79d61e1a70c5c8d1b446a07febf2c21f308f
|
Java
|
a2937/SubnetCalculator
|
/src/test/java/io/github/a2937/subnetcalc/SubnetCalcUtilTest.java
|
UTF-8
| 5,080
| 3.09375
| 3
|
[
"MIT"
] |
permissive
|
package io.github.a2937.subnetcalc;
import org.junit.Assert;
import org.junit.Test;
import org.junit.Before;
import org.junit.After;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/**
* SubnetCalcUtil Tester.
* This class
* @author <Authors name>
* @since <pre>Dec 5, 2018</pre>
* @version 1.0
*/
public class SubnetCalcUtilTest {
@Before
public void before() throws Exception {
}
@After
public void after() throws Exception {
}
/**
*
* Method: calculateNetMaskLength(String netMask)
* The method takes a standard Subnet mask like
* 255.255.255.0 and converts it a length instead.
*/
@Test
public void testCalculateNetMaskLength() throws Exception
{
Assert.assertEquals(24,SubnetCalcUtil.calculateNetMaskLength("255.255.255.0"));
}
/**
*
* Method: calculateBroadCastAddress(String ipAddress, String netMask)
* The method is supposed to be calculate the address that a computers uses
* to message all the others with.
*/
@Test
public void testCalculateBroadCastAddress() throws Exception
{
Assert.assertEquals("192.168.0.255",SubnetCalcUtil.calculateBroadCastAddress("192.168.0.2","255.255.255.0"));
}
/**
*
* Method: getRequiredSubNetMaskLengthForHosts(int hostsCount)
* It takes the host requirements and turns into a subnet mask length.
* All math is already performed by the program.
*/
@Test
public void testGetRequiredSubNetMaskLengthForHosts() throws Exception
{
Assert.assertEquals(25,SubnetCalcUtil.getRequiredSubNetMaskLengthForHosts(100));
}
/**
*
* Method: calculateNetworkAddress(String ipAddress, int netMaskLength)
* The method is virtually identical to calculate network mask with two strings.
* It takes the length then gets the subnet mask from it first though.
*/
@Test
public void testCalculateNetworkAddressForIpAddressNetMaskLength() throws Exception
{
Assert.assertEquals("404.404.404.0",SubnetCalcUtil.calculateNetworkAddress("404.404.404.002",24));
}
/**
*
* Method: calculateNetworkAddress(String ipAddress, String netMask)
* The method was used as a blueprint for the other function.
*/
@Test
public void testCalculateNetworkAddressForIpAddressNetMask() throws Exception
{
Assert.assertEquals("404.404.404.0",SubnetCalcUtil.calculateNetworkAddress("404.404.404.002","255.255.255.0"));
}
/**
*
* Method: getSubnetMaskFromPrefix(int prefixLength)
* This particular provides the padding for each grouping of eight bits.
*/
@Test
public void testGetSubnetMaskFromPrefix() throws Exception
{
Assert.assertEquals("255.255.255.000",SubnetCalcUtil.getSubnetMaskFromPrefix(24));
}
/**
*
* Method: getMaximumHostsInSubnet(int maskLength)
* The formula is 2 to power of the amount of host bits minus 2.
*/
@Test
public void testGetMaximumHostsInSubnet() throws Exception
{
Assert.assertEquals(2046,SubnetCalcUtil.getMaximumHostsInSubnet(21));
}
/**
*
* Method: getMaximumNetmaskForTwoAddresses(String addressOne, String addressTwo)
*
*/
@Test
public void testGetMaximumNetmaskForTwoAddresses() throws Exception
{
Assert.assertEquals(25,SubnetCalcUtil.getMaximumNetmaskForTwoAddresses("128.42.5.17","128.42.5.67"));
}
/**
*
* Method: convertDecimalToBinary(int decimal)
* In order to test the method, reflection was used.
* If the method name was to change, this test would
* no longer unless the name change was updated here too.
*/
@Test
public void testConvertDecimalToBinary() throws Exception {
try {
Method method = SubnetCalcUtil.class.getMethod("convertDecimalToBinary", int.class);
method.setAccessible(true);
String binaryReturnValue = (String)method.invoke(null, 69);
Assert.assertEquals("01000101",binaryReturnValue);
} catch(NoSuchMethodException e) {
} catch(IllegalAccessException e) {
} catch(InvocationTargetException e) {
}
}
/**
*
* Method: convertBinaryToDecimal(String binary)
* In order to test the method, reflection was used.
* If the method name was to change, this test would
* no longer unless the name change was updated here too.
*/
@Test
public void testConvertBinaryToDecimal() throws Exception
{
try
{
Method method = SubnetCalcUtil.class.getMethod("convertBinaryToDecimal", String.class);
method.setAccessible(true);
int returnValue = (int)method.invoke(null,"1000101");
Assert.assertEquals(69,returnValue);
} catch(NoSuchMethodException e) {
} catch(IllegalAccessException e) {
} catch(InvocationTargetException e) {
}
}
/**
*
* Method: reverse(String input)
* In order to test the method, reflection was used.
* If the method name was to change, this test would
* no longer unless the name change was updated here too.
*/
@Test
public void testReverse() throws Exception
{
try {
Method method = SubnetCalcUtil.class.getMethod("reverse", String.class);
method.setAccessible(true);
String returnValue = (String)method.invoke(null, "1000101");
Assert.assertEquals("1010001",returnValue);
} catch(NoSuchMethodException e) {
} catch(IllegalAccessException e) {
} catch(InvocationTargetException e) {
}
}
}
| true
|
b78acae3f355e5ed3e218262b0001d8bfcdb82b7
|
Java
|
vsop-479/shiyan
|
/shiyan-api-test/src/main/java/thinking/in/java/chapter15/demo/tuple/Holder3.java
|
UTF-8
| 581
| 3.359375
| 3
|
[] |
no_license
|
package thinking.in.java.chapter15.demo.tuple;
/**
* Created by Administrator on 2016/10/27.
* 类型参数
* 告诉便西起想使用什么类型,然后编译器帮你处理一切细节。
*/
public class Holder3<T> {
private T a;
// 类型参数
public Holder3(T a){
this.a = a;
}
public T getA() {
return a;
}
public void setA(T a) {
this.a = a;
}
public static void main(String[] args){
Holder3<String> h1 = new Holder3<String>("dsf");
Holder3<Integer> h2 = new Holder3<Integer>(23);
}
}
| true
|
d126e9e2d040c88761f39a8400ad55b4153403af
|
Java
|
tingwhere/wenbaotong
|
/WBT/Asocket/src/com/example/asocket/ExREG.java
|
UTF-8
| 901
| 2.265625
| 2
|
[] |
no_license
|
package com.example.asocket;
public class ExREG { //存什么类型
public byte TypeL;
public byte TypeH;
public byte LenL;
public byte LenH;
// public byte clientID; //java中一个char占2个字节
public String clientName;
public byte Endflag;
public ExREG(byte typel, byte typeh, byte lenl, byte lenh, String clientname, byte endflag)//对应每一个元素,增加构造函数,初始化:A a = new A();自动分配内存
//http://zhidao.baidu.com/link?url=AB6Lton3JPEI8TtmjMHpLXZUOr_bt0E247beV77T8IV7r1Km61hq3JwNPZDQktnj8pisxrcsBVdOePsMkc-MrEqp7SWK5zZ5WWkgsS-6zYq
{
this.TypeL = typel;
this.TypeH = typeh;
this.LenL = lenl;
this.LenH = lenh;
// this.clientID = clientid;
this.clientName = clientname;
this.Endflag =endflag;
}
}
| true
|
28782758af9d2cc9f6449a34f3eb573429d080b3
|
Java
|
sq1235/repair
|
/src/main/java/org/tysf/gt/service/ISimageService.java
|
UTF-8
| 153
| 1.5625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.tysf.gt.service;
import org.tysf.gt.pojo.SImage;
public interface ISimageService {
public void addSImage(SImage sImage);//添加图片
}
| true
|
827ecff19375f7d1d32daa3dbe0ba396a87f1fb8
|
Java
|
AmaniChou/jarb
|
/jarb-constraints/src/test/java/org/jarbframework/constraint/domain/Contact.java
|
UTF-8
| 373
| 2.328125
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.jarbframework.constraint.domain;
import javax.persistence.Embeddable;
import javax.persistence.Embedded;
@Embeddable
public class Contact {
@Embedded
private Address address;
public Contact() {
}
public Contact(Address address) {
this.address = address;
}
public Address getAddress() {
return address;
}
}
| true
|
a8a17275faf5ba5964f57c633d94beca446bc742
|
Java
|
Lymero/BulldOzer
|
/src/main/java/types/PairType.java
|
UTF-8
| 941
| 2.984375
| 3
|
[] |
no_license
|
package types;
import java.util.Objects;
public final class PairType extends Type {
public Type keyTypes;
public Type valueTypes;
private PairType() {
}
public PairType(Type keyTypes, Type valueTypes) {
this.keyTypes = keyTypes;
this.valueTypes = valueTypes;
}
@Override
public boolean isPrimitive() {
return true;
}
@Override
public String name() {
return String.format("<%s, %s>", keyTypes.name(), valueTypes.name());
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
PairType pairType = (PairType) o;
return Objects.equals(keyTypes, pairType.keyTypes) &&
Objects.equals(valueTypes, pairType.valueTypes);
}
@Override
public int hashCode() {
return Objects.hash(keyTypes, valueTypes);
}
}
| true
|
a061b7801a6a4ec2bee3b7b0ad5791d2002ca557
|
Java
|
blurock/webReaction
|
/ReactImport/src/graph/DrawGraph.java
|
UTF-8
| 25,646
| 2.78125
| 3
|
[] |
no_license
|
/* FILE DrawGraph.java
** PACKAGE ANALYSIS
** AUTHOR Edward S. Blurock
**
** CONTENT
**
** REFERENCES
**
** COPYRIGHT (C) 1995 ANALYSIS Project / Edward S. Blurock
*/
package graph;
import java.awt.event.*;
import java.awt.Color;
import java.awt.Canvas;
import java.awt.FontMetrics;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.util.Vector;
import java.lang.*;
import graph.DrawGraphNode;
import java.util.Hashtable;
/** DrawGraph
* <ul>
* <li> XOffSet, YOffSet: The offset of the graph coordinates
* <li> XRelative,YRelative: The relative multiplicative factor
* </ul>
*/
public class DrawGraph extends Canvas
implements MouseListener {
DrawGraphNode pick = null;
boolean pickfixed;
public boolean EdgeAdjust = true;
public double edgeLength = 50.0;
double baseMove = edgeLength/2.0;
public int xMax = 500;
public int yMax = 500;
public int xOffSet = 0;
public int yOffSet = 0;
public int yIncrement = 50;
public int yInitial = 50;
public int xTotalMax = 2000;
/** The relative multiplicative factors
*/
int XRelative = 50;
int YRelative = 50;
/** The bonds and nodes of the graph
*/
public Vector Nodes = new Vector();
public Vector Bonds = new Vector();
/** The default color of the graph
*/
Color DefaultNodeColor = Color.orange;
Color DefaultBondColor = Color.black;
/** The default type of the graph
*/
/** The default node font
*/
FontMetrics DefaultNodeFont;
/** The default graph, node and bond types
*/
int DefaultGraphType = 0;
int DefaultNodeType = 0;
int DefaultBondType = 0;
public boolean treeGraph = false;
public int countMove = 0;
String GraphCommand = new String();
String BestChosenNode;
String BestChosenParent;
String BestChosenSon;
/** DrawGraph() . . . . . . . . . . . . . . . . . . . . empty constructor
*/
public DrawGraph() {
}
public void clearGraph() {
Bonds = new Vector();
Nodes = new Vector();
}
/** setDefaultNodeFont(font) . . . . . . . . . . . . . . . . . set name of node
* <ul>
* <li> font: The font of the node
* </ul>
*/
public void setDefaultNodeFont(FontMetrics font) {
DefaultNodeFont = font;
}
/** font = getDefaultNodeFont() . . . . . . . . . . . . . . . . . get name
* <ul>
* <li> font: The font of the node string
* </ul>
*/
public FontMetrics getdDefaultNodeFont() {
return DefaultNodeFont;
}
/** setDefaultNodeColor(color) . . . . . . . . . . . . . . . . set color of node
* <ul>
* <li> color: The color of the node
* </ul>
*/
public void setDefaultNodeColor(Color color) {
DefaultNodeColor = color;
}
/** color = getDefaultNodeColor() . . . . . . . . . . . . . . get color of node
* <ul>
* <li> color: The color of the node
* </ul>
*/
public Color getDefaultNodeColor() {
return DefaultNodeColor;
}
/** setDefaultNodeColor(color) . . . . . . . . . . . . . . . . set color of node
* <ul>
* <li> color: The color of the node
* </ul>
*/
public void setDefaultBondColor(Color color) {
DefaultBondColor = color;
}
/** color = getDefaultBondColor() . . . . . . . . . . . . . . get color of node
* <ul>
* <li> color: The color of the node
* </ul>
*/
public Color getDefaultBondColor() {
return DefaultBondColor;
}
/** setDefaultNodeType(type)
* <ul>
* <li> type: The type of the node:
* </ul>
*/
public void setDefaultNodeType(int type) {
DefaultNodeType = type;
}
/** type = getDefaultNodeType()
* <ul>
* <li> type: The type of the node:
* </ul>
*/
public int getDefaultNodeType() {
return DefaultNodeType;
}
/** setDefaultBondType(type)
* <ul>
* <li> type: The type of the node:
* </ul>
*/
public void setDefaultBondType(int type) {
DefaultBondType = type;
}
/** type = getDefaultBondType()
* <ul>
* <li> type: The type of the node:
* </ul>
*/
public int getDefaultBondType() {
return DefaultBondType;
}
/** setDefaultGraphType(type)
* <ul>
* <li> type: The type of the node:
* </ul>
*/
public void setDefaultGraphType(int type) {
DefaultGraphType = type;
}
/** type = getDefaultGraphType()
* <ul>
* <li> type: The type of the node:
* </ul>
*/
public int getDefaultGraphType() {
return DefaultGraphType;
}
/** addNode(node) . . . . . . . . . . . . . . . add node to set of nodes
* <ul>
* <li> node: The node to add. the color, font and type are set to the default settings of the graph
* </ul>
*/
public void addNode(DrawGraphNode node) {
node.setNodeColor(DefaultNodeColor);
node.setNodeFont(DefaultNodeFont);
node.setNodeType(DefaultNodeType);
Nodes.addElement(node);
}
/** addBond(node1,node2) . . . . . . . . . . . add node to set of nodes
* <ul>
* <li> node1: The names of the nodes in the bond.
* <li> node2: The names of the nodes in the bond.
* </ul>
*/
public DrawGraphBond addBond(String node1, String node2) {
DrawGraphBond bond = new DrawGraphBond();
int n1 = getNodeIndex(node1);
int n2 = getNodeIndex(node2);
if(n1 >= 0 && n2 >= 0 ) {
bond = new DrawGraphBond(DefaultBondType,
(DrawGraphNode) Nodes.elementAt(n1),
(DrawGraphNode) Nodes.elementAt(n2));
Bonds.addElement(bond);
}
else {
System.out.println("Nodes not found: Node 1: '" + node1 + "' Node 2: '" + node2 + "'");
}
return bond;
}
public void treeGraphPositions(DrawGraphNode pick, int maxWidth,
int initialy, int yinc) {
Hashtable used = new Hashtable();
Hashtable usedrxns = new Hashtable();
Vector current = new Vector();
current.add(pick.getNameTag());
used.put(pick.getNameTag(),pick.getNameTag());
int ylevel = initialy;
while(current.size() > 0) {
int dist = maxWidth/(current.size()+1);
for(int cnt=0;cnt<current.size();cnt++) {
String name = (String) current.elementAt(cnt);
int n = getNode(name);
DrawGraphNode p = (DrawGraphNode) Nodes.elementAt(n);
p.setYCoordinate(ylevel,yOffSet);
p.setXCoordinate((cnt+1)*dist,xOffSet);
}
Vector next = new Vector();
for(int cnt=0;cnt<current.size();cnt++) {
String p = (String) current.elementAt(cnt);
Vector sons = getSons(p);
for(int soncnt = 0;soncnt<sons.size();soncnt++) {
String name = (String) sons.elementAt(soncnt);
if(!used.contains(name)) {
used.put(name,name);
next.add(name);
}
}
}
ylevel = ylevel + yinc;
current = next;
}
ylevel = initialy;
int xlevel = maxWidth + ylevel;
for(int n=0;n<Nodes.size();n++) {
DrawGraphNode p = (DrawGraphNode) Nodes.elementAt(n);
if(!used.contains(p.getNameTag())) {
p.setXCoordinate(xlevel,xOffSet);
p.setYCoordinate(ylevel,yOffSet);
ylevel += yinc;
}
}
}
/** index = getNodeIndex(name)
* <ul>
* <li> name: The name of the node to find
* </ul>
*/
public int getNodeIndex(String name) {
boolean notfound = true;
int found = -1;
for(int i=0;i < Nodes.size() && notfound; i++) {
if(name.equals(((DrawGraphNode) Nodes.elementAt(i)).getNameTag())) {
notfound = false;
found = i;
}
}
return found;
}
/** bond = getNode(name)
* <ul>
* <li> name: The name of the bond to find
* </ul>
*/
public int getNode(String name) {
boolean notfound = true;
int found = -1;
for(int i=0;i < Nodes.size() && notfound; i++) {
if(name.equals(((DrawGraphNode) Nodes.elementAt(i)).getNameTag())) {
notfound = false;
found = i;
}
}
return found;
}
public String getNodeNameFromIndex(int inode) {
return ((DrawGraphNode) Nodes.elementAt(inode)).getNameTag();
}
/** drawGraph(g) . . . . . draw the current positions of nodes and bonds
*/
public void drawGraph(Graphics g) {
for(int ibond=0;ibond < Bonds.size(); ibond++) {
DrawGraphBond bond = (DrawGraphBond) Bonds.elementAt(ibond);
int i1 = getNode(bond.Son);
int i2 = getNode(bond.Parent);
DrawGraphNode node1 = (DrawGraphNode) Nodes.elementAt(i1);
DrawGraphNode node2 = (DrawGraphNode) Nodes.elementAt(i2);
if(node1.drawNode && node2.drawNode) {
//System.out.println("Bond: " + node1.getNameTag() + "," + node2.getNameTag());
bond.drawBond(g);
}
}
for(int inode=0;inode < Nodes.size(); inode++) {
DrawGraphNode node = (DrawGraphNode) Nodes.elementAt(inode);
node.drawNode(g);
}
}
public void normalNodePositions() {
double xhigh = -100000;
double xlow = 100000;
double yhigh = -100000;
double ylow = 100000;
for(int inode=0;inode < Nodes.size(); inode++) {
DrawGraphNode node = (DrawGraphNode) Nodes.elementAt(inode);
double x = node.getXCoordinate();
double y = node.getYCoordinate();
if(x > xhigh) xhigh = x;
if(y > yhigh) yhigh = y;
if(x < xlow) xlow = x;
if(y < ylow) ylow = y;
}
double factor = 250.0;
double xoffset = (xlow + xhigh)/2.0;
double yoffset = (ylow + yhigh)/2.0;
double xfactor = factor;
double yfactor = factor;
if(Math.abs(xhigh-xlow) >.001)
xfactor = factor/(2.0*(xhigh - xlow));
if(Math.abs(yhigh-ylow) >.001)
yfactor = factor/(2.0*(yhigh - ylow));
for(int inode=0;inode < Nodes.size(); inode++) {
DrawGraphNode node = (DrawGraphNode) Nodes.elementAt(inode);
double x = node.getXCoordinate();
double y = node.getYCoordinate();
Double xx = new Double((x-xoffset)*xfactor + 100.0);
Double yy = new Double((y-yoffset)*yfactor + 100.0);
node.setXCoordinate(xx.intValue(),xOffSet);
node.setYCoordinate(yy.intValue(),yOffSet);
}
}
/** drawGraphCoordinates()
*
* public void drawGraphCoordinates()
* {
*
* for(int inode=0;inode < Nodes.size(); inode++)
* {
* DrawGraphNode n = (DrawGraphNode) Nodes.elementAt(inode);
* }
* }
*/
public synchronized void relax() {
Dimension d = getPreferredSize();
for(int i=0;i<50;i++) {
if(EdgeAdjust)
adjustEdges();
checkNodeDistances();
moveNodes(d);
}
repaint();
}
double randomChange(double base) {
return 2.0*Math.random()*base - base;
}
public void centerXFactor(double xCenter) {
double accum = 0.0;
for(int i = 0; i< Nodes.size();i++) {
DrawGraphNode n1 = (DrawGraphNode) Nodes.elementAt(i);
accum += n1.XCoordinate;
}
double nd = (double) Nodes.size();
accum /= nd;
double diff = xCenter - accum;
for(int i = 0; i< Nodes.size();i++) {
DrawGraphNode n1 = (DrawGraphNode) Nodes.elementAt(i);
n1.dx += diff;
}
}
public void centerYFactor(double yCenter) {
double accum = 0.0;
for(int i = 0; i< Nodes.size();i++) {
DrawGraphNode n1 = (DrawGraphNode) Nodes.elementAt(i);
accum += n1.YCoordinate;
}
double nd = (double) Nodes.size();
accum /= nd;
double diff = yCenter - accum;
for(int i = 0; i< Nodes.size();i++) {
DrawGraphNode n1 = (DrawGraphNode) Nodes.elementAt(i);
n1.dy += diff;
}
}
public void checkNodeDistances() {
for (int i = 0 ; i < Nodes.size() ; i++) {
DrawGraphNode n1 = (DrawGraphNode) Nodes.elementAt(i);
double dx = 0;
double dy = 0;
for (int j = 0 ; j < i ; j++) {
if(j != i) {
DrawGraphNode n2 = (DrawGraphNode) Nodes.elementAt(j);
double vx = n1.XCoordinate - n2.XCoordinate;
double vy = n1.YCoordinate - n2.YCoordinate;
double len = vx * vx + vy * vy;
double slen = Math.sqrt(len);
if(slen < edgeLength*0.8) {
double fx = ((vx / slen))*baseMove;
double fy = ((vy / slen))*baseMove;
if(slen < edgeLength*.1) {
fx = randomChange(baseMove);
fy = randomChange(baseMove);
}
dx += fx;
dy += fy;
}
}
}
double dlen = dx * dx + dy * dy;
if (dlen > 0) {
//dlen = Math.sqrt(dlen);
dlen = 1.0;
n1.dx += dx / dlen;
n1.dy += dy / dlen;
}
}
}
public void moveNodes(Dimension d) {
//jiggleRandomNode();
for (int i = 0 ; i < Nodes.size() ; i++) {
DrawGraphNode n = (DrawGraphNode) Nodes.elementAt(i);
if (!n.fixed) {
n.XCoordinate += Math.max(-40, Math.min(40, n.dx));
if(!treeGraph)
n.YCoordinate += Math.max(-30, Math.min(30, n.dy));
if (n.XCoordinate < 30) {
n.XCoordinate = 30;
}
else if (n.XCoordinate > d.width-30) {
n.XCoordinate = d.width-30;
}
if (n.YCoordinate < 30) {
n.YCoordinate = 30;
}
else if (n.YCoordinate > d.height-30) {
n.YCoordinate = d.height-30;
}
}
n.dx /= 2;
n.dy /= 2;
}
centerXFactor(d.width/2.0);
if(!treeGraph)
centerYFactor(d.height/2.0);
}
public void adjustEdges() {
for (int i = 0 ; i < Bonds.size() ; i++) {
DrawGraphBond e = (DrawGraphBond) Bonds.elementAt(i);
DrawGraphNode n1 = (DrawGraphNode) Nodes.elementAt(getNode(e.getParent()));
DrawGraphNode n2 = (DrawGraphNode) Nodes.elementAt(getNode(e.getSon()));
double vx = n1.XCoordinate - n2.XCoordinate;
double vy = n1.YCoordinate - n2.YCoordinate;
double len = Math.sqrt(vx * vx + vy * vy);
if(len > edgeLength*1.5) {
n1.XCoordinate -= vx/10.0;
n2.XCoordinate += vx/10.0;
if(!treeGraph) {
n1.YCoordinate -= vy/10.0;
n2.YCoordinate += vy/10.0;
}
}
}
}
public double bondLength(DrawGraphBond e) {
DrawGraphNode n1 = (DrawGraphNode) Nodes.elementAt(getNode(e.getParent()));
DrawGraphNode n2 = (DrawGraphNode) Nodes.elementAt(getNode(e.getSon()));
double vx = n1.XCoordinate - n2.XCoordinate;
double vy = n1.YCoordinate - n2.YCoordinate;
double len = Math.sqrt(vx * vx + vy * vy);
return len;
}
public boolean MoveEdge(int ia) {
boolean inter = false;
double di = Math.random() * Bonds.size();
int i = (int) di;
DrawGraphBond b = (DrawGraphBond) Bonds.elementAt(i);
DrawGraphBond a = (DrawGraphBond) Bonds.elementAt(ia);
if(i == ia)
inter = false;
else
inter = Intersect(a,b);
return inter;
}
public boolean Intersect(DrawGraphBond a, DrawGraphBond b) {
DrawGraphNode a1 = (DrawGraphNode) Nodes.elementAt(getNode(a.getParent()));
DrawGraphNode a2 = (DrawGraphNode) Nodes.elementAt(getNode(a.getSon()));
DrawGraphNode b1 = (DrawGraphNode) Nodes.elementAt(getNode(b.getParent()));
DrawGraphNode b2 = (DrawGraphNode) Nodes.elementAt(getNode(b.getSon()));
return Intersect(a1,a2,b1,b2);
}
public boolean Intersect(DrawGraphNode a1, DrawGraphNode a2, DrawGraphNode b1, DrawGraphNode b2) {
boolean inter;
double dxa = a2.XCoordinate - a1.XCoordinate;
double dya = a2.YCoordinate - a1.YCoordinate;
double dxb = b2.XCoordinate - b1.XCoordinate;
double dyb = b2.YCoordinate - b1.YCoordinate;
double xdiff = a1.XCoordinate - b1.XCoordinate;
double ydiff = a1.YCoordinate - b1.YCoordinate;
double det = dxa*dyb - dxb*dya;
double pb = -dya*xdiff + dxa*ydiff;
double pa = -dyb*xdiff + dxb*ydiff;
if(det != 0.0) {
pa = pa/det;
pb = pb /det;
}
if(pa > 0.01 && pa < 0.99 && pb > 0.01 && pb < .99) {
inter = true;
a1.dx = dxa*(0.1);
a1.dy = dya*(0.1);
countMove++;
if(countMove > 100) {
Dimension d = new Dimension(100,100);
shakeNodes(d);
countMove = 0;
}
}
else {
inter = false;
}
return inter;
}
public void shakeNodes(Dimension d) {
for (int i = 0 ; i < Nodes.size() ; i++) {
DrawGraphNode n = (DrawGraphNode) Nodes.elementAt(i);
if (!n.fixed) {
n.XCoordinate += 80*Math.random() - 40;
if(!treeGraph)
n.YCoordinate += 80*Math.random() - 40;
}
}
}
/** recomputeConnectionCoords() given the nodes, recompute bond postions
*/
public void recomputeConnectionCoords() {
for(int ibond=0;ibond < Bonds.size(); ibond++) {
DrawGraphBond bond = (DrawGraphBond) Bonds.elementAt(ibond);
int par = getNode(bond.getParent());
int son = getNode(bond.getSon());
((DrawGraphBond) Bonds.elementAt(ibond)).calculateBondCoordinate((DrawGraphNode) Nodes.elementAt(par),
(DrawGraphNode) Nodes.elementAt(son));
}
}
/** names = getSons(parent) . . . . . . . . . . . . . . . . . . get sons
* <ul>
* <li> parent: The name of the parent node
* <li> names: The names of the sons of the parent
* </ul>
*/
public Vector getSons(String parent) {
Vector sons = new Vector();
for(int b = 0; b < Bonds.size() ; b++) {
DrawGraphBond bond = (DrawGraphBond) Bonds.elementAt(b);
if(bond.getParent().equals(parent)) {
sons.addElement(bond.getSon());
}
}
return sons;
}
public void paint(Graphics g) {
DefaultNodeFont = g.getFontMetrics();
computeReports();
setSize(xMax,yMax);
recomputeConnectionCoords();
drawGraph(g);
Color bg = getBackground();
//Draw a fancy frame around the applet.
g.setColor(bg);
g.draw3DRect(0, 0, xMax - 1, yMax - 1, true);
g.draw3DRect(3, 3, xMax - 7, yMax - 7, false);
}
/**
* Determines the value of the parameters for drawing.
*/
private void computeReports() {
XRelative = 100;
if(Nodes.size() == 0)
YRelative = 100;
else
YRelative = (yMax - 2*yOffSet)/ Nodes.size();
}
/**
* Process the click on the graph surface.
* <P>
* <P> Computes the coordinates of the click.
* <P> Computes the portions of the command string
* <P> that will be returned after a click.
*/
public void getCmdCoord(MouseEvent evnt) {
int xClick = evnt.getX();
int yClick = evnt.getY();
int bestbond = getBondFromCoordinates(xClick,yClick);
int bestnode = getNodeFromCoordinates(xClick,yClick);
DrawGraphNode node = (DrawGraphNode) Nodes.elementAt(bestnode);
DrawGraphBond bond = (DrawGraphBond) Bonds.elementAt(bestbond);
BestChosenNode = node.getNameTag();
BestChosenParent = bond.getParent();
BestChosenSon = bond.getSon();
if(getDistanceToBond(bestbond,xClick,yClick) > getDistanceToNode(bestnode,xClick,yClick) ) {
GraphCommand = " " + BestChosenNode;
}
else {
GraphCommand = " " + BestChosenParent + " " + BestChosenSon;
}
}
public int getDistanceToBond(int ibond, int xClick, int yClick) {
DrawGraphBond bond = (DrawGraphBond) Bonds.elementAt(ibond);
return bond.distSquaredToCoordinate(xClick,yClick);
}
public int getDistanceToNode(int inode, int xClick, int yClick) {
DrawGraphNode node = (DrawGraphNode) Nodes.elementAt(inode);
return node.distSquaredToCoordinate(xClick,yClick);
}
public int getBondFromCoordinates(int xClick, int yClick) {
int bestbond = 0;
int mindistbond = xMax*xMax+yMax*yMax;
for(int ibond=0;ibond < Bonds.size(); ibond++) {
DrawGraphBond bond = (DrawGraphBond) Bonds.elementAt(ibond);
if(mindistbond > bond.distSquaredToCoordinate(xClick,yClick)) {
bestbond = ibond;
mindistbond = bond.distSquaredToCoordinate(xClick,yClick);
}
}
return bestbond;
}
public int getNodeFromCoordinates(int xClick, int yClick) {
String bnode = new String();
int mindistnode = xMax*xMax+yMax*yMax;
int bestnode = 0;
for(int inode=0;inode < Nodes.size(); inode++) {
DrawGraphNode node = (DrawGraphNode) Nodes.elementAt(inode);
if(mindistnode > node.distSquaredToCoordinate(xClick,yClick)) {
bnode = node.getNameTag();
bestnode = inode;
mindistnode = node.distSquaredToCoordinate(xClick,yClick);
}
}
return bestnode;
}
public String getGraphCommand() {
return GraphCommand;
}
public String getBestChosenNode() {
return BestChosenNode;
}
public String getBestChosenParent() {
return BestChosenParent;
}
public String getBestChosenSon() {
return BestChosenSon;
}
// finalize: final cleanup
protected void finalize() throws Throwable {
super.finalize();
}
/** setXRelative(rel)
* <ul>
* <li> rel: The coordinate rel
* </ul>
*/
public void setXRelative(int rel) {
XRelative = rel;
}
/** rel = getXRelative()
* <ul>
* <li> rel: The coordinate rel
* </ul>
*/
public int getXRelative() {
return XRelative;
}
/** setYRelative(rel)
* <ul>
* <li> rel: The coordinate rel
* </ul>
*/
public void setYRelative(int rel) {
YRelative = rel;
}
/** rel = getYRelative()
* <ul>
* <li> rel: The coordinate rel
* </ul>
*/
public int getYRelative() {
return YRelative;
}
/** num = getNumberOfNodes()
* <ul>
* <li> num: The number of nodes in the graph
* </ul>
*/
public int getNumberOfNodes() {
return Nodes.size();
}
public Dimension getPreferredSize() {
return new Dimension(xMax,yMax);
}
/**
* mousePressed, mouseClicked, mouseEntered, mouseExited, mouseReleased -
* methods that define reactions for the mouse operations.
*/
public void mousePressed(MouseEvent evnt) {
int x = evnt.getX();
int y = evnt.getY();
int nindex = getNodeFromCoordinates(x,y);
pick = (DrawGraphNode) Nodes.elementAt(nindex);
pickfixed = pick.fixed;
pick.fixed = true;
pick.XCoordinate = x;
pick.YCoordinate = y;
repaint();
}
public void mouseDragged(MouseEvent evnt) {
if(pick == null)
mousePressed(evnt);
int x = evnt.getX();
int y = evnt.getY();
pick.XCoordinate = x;
pick.YCoordinate = y;
repaint();
}
public void mouseClicked(MouseEvent evnt) {getCmdCoord(evnt);}
public void mouseEntered(MouseEvent evnt){}
public void mouseExited(MouseEvent evnt){}
public void mouseReleased(MouseEvent evnt){}
}
| true
|
cd70ff756c45b016471e8d97a8fc24b2269e52f5
|
Java
|
Vino007/LectureSystem
|
/src/main/java/com/vino/scaffold/shiro/service/UserServiceImpl.java
|
GB18030
| 8,398
| 2.171875
| 2
|
[] |
no_license
|
package com.vino.scaffold.shiro.service;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.logging.SimpleFormatter;
import javax.annotation.Resource;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.vino.scaffold.entity.Constants;
import com.vino.scaffold.service.base.AbstractBaseServiceImpl;
import com.vino.scaffold.shiro.entity.Role;
import com.vino.scaffold.shiro.entity.User;
import com.vino.scaffold.shiro.exception.UserDuplicateException;
import com.vino.scaffold.shiro.repository.RoleRepository;
import com.vino.scaffold.shiro.repository.UserRepository;
@Transactional
@Service("userService")
public class UserServiceImpl extends AbstractBaseServiceImpl<User, Long> implements UserService{
@Autowired
private UserRepository userRepository;
@Autowired
private RoleRepository roleRepository;
@Autowired
private PasswordHelper passwordHelper;
/**
* ̬ѯ.
*/
private Specification<User> buildSpecification(final Map<String,Object> searchParams) {
Specification<User> spec = new Specification<User>(){
@Override
public Predicate toPredicate(Root<User> root,
CriteriaQuery<?> cq, CriteriaBuilder cb) {
Predicate allCondition = null;
String username=(String) searchParams.get("username");
String userAlias=(String) searchParams.get("userAlias");
String createTimeRange=(String) searchParams.get("createTimeRange");
if(username!=null&&!"".equals(username)){
Predicate condition=cb.like(root.get("username").as(String.class),"%"+searchParams.get("username")+"%");
if(null==allCondition)
allCondition=cb.and(condition);//˴ʼallCondition,cb.and(allCondition,condition)дᵼ¿ָ
else
allCondition=cb.and(allCondition,condition);
}
if(userAlias!=null&&!"".equals(userAlias)){
Predicate condition=cb.like(root.get("userAlias").as(String.class),"%"+searchParams.get("userAlias")+"%");
if(null==allCondition)
allCondition=cb.and(condition);//˴ʼallCondition,cb.and(allCondition,condition)дᵼ¿ָ
else
allCondition=cb.and(allCondition,condition);
}
if(createTimeRange!=null&&!"".equals(createTimeRange)){
String createTimeStartStr=createTimeRange.split(" - ")[0]+":00:00:00";
String createTimeEndStr=createTimeRange.split(" - ")[1]+":23:59:59";
SimpleDateFormat format=new SimpleDateFormat("MM/dd/yyyy:hh:mm:ss");
System.out.println(createTimeStartStr);
try {
Date createTimeStart = format.parse(createTimeStartStr);
Date createTimeEnd=format.parse(createTimeEndStr);
Predicate condition=cb.between(root.get("createTime").as(Date.class),createTimeStart, createTimeEnd);
if(null==allCondition)
allCondition=cb.and(condition);//˴ʼallCondition,cb.and(allCondition,condition)дᵼ¿ָ
else
allCondition=cb.and(allCondition,condition);
} catch (ParseException e) {
e.printStackTrace();
Logger log =LoggerFactory.getLogger(this.getClass());
log.error("createTime תʱ");
}
}
return allCondition;
}
};
return spec;
}
@Override
public Page<User> findUserByCondition(Map<String,Object> searchParams, Pageable pageable) {
return userRepository.findAll(buildSpecification(searchParams), pageable);
}
public UserRepository getUserRepository() {
return userRepository;
}
public void setUserRepository(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Override
public User findByUsername(String username) {
// TODO Auto-generated method stub
return userRepository.findByUsername(username);
}
@Override
public Set<String> findAllRoleNamesByUsername(String username) {
User user=userRepository.findByUsername(username);
Set<Role> roles=user.getRoles();
Set<String> roleNames=new HashSet<String>();
if(!roles.isEmpty()){
for(Role r : roles){
roleNames.add(r.getName());
}
}
return roleNames;
}
@Override
public Set<String> findAllPermissionsByUsername(String username) {
User user=userRepository.findByUsername(username);
Set<Role> roles=user.getRoles();
Set<String> permissions=new HashSet<String>();
for(Role r:roles){
Set<com.vino.scaffold.shiro.entity.Resource> resources=r.getResources();
for(com.vino.scaffold.shiro.entity.Resource res:resources){
permissions.add(res.getPermission());
}
}
return permissions;
}
/**
* û
* @param user
* @throws UserDuplicateException
*/
public void saveWithCheckDuplicate(User user) throws UserDuplicateException{
//УǷûظ
if(userRepository.findByUsername(user.getUsername())!=null)
throw new UserDuplicateException();
//
passwordHelper.encryptPassword(user);
user.setCreateTime(new Date());
if(getCurrentUser()!=null)
user.setCreatorName(getCurrentUser().getUsername());
userRepository.save(user);
}
@Override
public void update(User user){
User user2=userRepository.findOne(user.getId());
if(user.getUserAlias()!=null){
user2.setUserAlias(user.getUserAlias());
}
if(user.getLocked()!=null){
user2.setLocked(user.getLocked());
}
if(user.getLastLoginTime()!=null){
user2.setLastLoginTime(user.getLastLoginTime());
}
if(user.getPassword()!=null){
user2.setPassword(user.getPassword());
}
if(user.getLoginTime()!=null){
user2.setLoginTime(user.getLoginTime());
}
}
/**
*
* @param userId
* @param newPassword
*/
@Override
public void changePassword(Long userId, String newPassword) {
User user =userRepository.findOne(userId);
user.setPassword(newPassword);
passwordHelper.encryptPassword(user);//м,ĺȴflushͻ־ûݿ
}
@Override
public void connectUserAndRole(Long userId, Long... roleId) {
User user=userRepository.findOne(userId);
Set<Role> roles=user.getRoles();
for(Long id:roleId){
roles.add(roleRepository.findOne(id));
}
}
@Override
public void disconnectUserAndRole(Long userId, Long... roleIds) {
for(Long id:roleIds){
userRepository.findOne(userId).getRoles().remove(roleRepository.findOne(id));
}
}
public RoleRepository getRoleRepository() {
return roleRepository;
}
public void setRoleRepository(RoleRepository roleRepository) {
this.roleRepository = roleRepository;
}
public PasswordHelper getPasswordHelper() {
return passwordHelper;
}
public void setPasswordHelper(PasswordHelper passwordHelper) {
this.passwordHelper = passwordHelper;
}
@Override
public void clearAllUserAndRoleConnection(Long userId) {
User user=userRepository.findOne(userId);
user.getRoles().clear();
}
@Override
public void saveWithCheckDuplicate(List<User> users)
throws UserDuplicateException {
if(null==users||0==users.size())
return;
//УǷûظ
for(User user:users){
if(userRepository.findByUsername(user.getUsername())!=null)
throw new UserDuplicateException();
if(user.getPassword()==null){
user.setPassword(Constants.DEFAULT_PASSWORD);
}
//
passwordHelper.encryptPassword(user);
user.setCreateTime(new Date());
user.setCreatorName(getCurrentUser().getUsername());
userRepository.save(user);
}
}
}
| true
|
cf666e18ec61f62a0239afb44b119c1b907b75dc
|
Java
|
shashanksriva/javapractice
|
/src/com/equinix/bitset/BitSetImplementation.java
|
UTF-8
| 1,177
| 3.46875
| 3
|
[] |
no_license
|
package com.equinix.bitset;
import java.util.BitSet;
public class BitSetImplementation {
private BitSet bitset;
/**
* Creates BitSet with default size of 24 bits
*/
public BitSetImplementation() {
bitset = new BitSet(24);
}
/**
* Creates BitSet with given size
* @param size
*/
public BitSetImplementation(int size) {
bitset = new BitSet(size);
}
/**
* Sets interface to be set, implies that interface id is not available
* @param bitIndex
*/
void setInterfaceInUse(int bitIndex) {
//System.out.println("Setting Interface::" + bitIndex);
bitset.set(bitIndex);
}
/**
* Clears set flag for an interface, making it available for configuration
* @param bitIndex
*/
void clearInterface(int bitIndex) {
bitset.clear(bitIndex);
}
/**
* Returns next available interface
* @return
*/
int getNextAvailableInterface() {
return bitset.nextClearBit(1);
}
boolean getStatusOfInterface(int index) {
System.out.println(bitset.toString());
return bitset.get(index);
}
}
| true
|
957ee3f06144927804c8f337bcbff898cfb81629
|
Java
|
HWenTing/leetcode
|
/T_701_800/T704.java
|
UTF-8
| 669
| 3.671875
| 4
|
[] |
no_license
|
package T_701_800;
public class T704 {
// 给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。
// 二分查找 注意细节
public int search(int[] nums, int target) {
int left=0;
int right=nums.length-1;
int mid;
while(left<=right){
mid=left+(right-left)/2;
if(nums[mid]==target)
return mid;
else if(nums[mid]<target){
left=mid+1;
}else{
right=mid-1;
}
}
return -1;
}
}
| true
|
517435df8d75614068e0093a8528550e12d0709b
|
Java
|
rfranco84/MVCDatabase
|
/src/main/java/com/cg/MVCThymeDB/MVCDatabase/services/UserServices.java
|
UTF-8
| 990
| 2.625
| 3
|
[] |
no_license
|
package com.cg.MVCThymeDB.MVCDatabase.services;
import com.cg.MVCThymeDB.MVCDatabase.dao.UserDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.cg.MVCThymeDB.MVCDatabase.pojo.User;
import java.util.List;
// Service annotation marks class as a service.
@Service
public class UserServices {
// Dependency injection of the dao
@Autowired
UserDAO userDAO;
// Add new user
public User addUser(User user){
return userDAO.save(user);
}
// TODO: Update user
// TODO: Remove user by id
// Get user
public User retrieve(int _id){
if(userDAO.existsById(_id))
return userDAO.findById(_id).get();
// Should be corrected in the future. This returns null if the user foesn't exist.
return null;
}
// Get all users
public List<User> retrieveAllUsers(){
return userDAO.findAll();
}
}
| true
|
ca613e4067d3d0f351ba04e1603a6d1d20a56a47
|
Java
|
fabienwarniez/jtwig
|
/jtwig-core/src/test/java/org/jtwig/acceptance/config/JsonConfigurationTest.java
|
UTF-8
| 1,224
| 2.25
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.jtwig.acceptance.config;
import com.google.common.base.Function;
import org.jtwig.JtwigModelMap;
import org.jtwig.JtwigTemplate;
import org.jtwig.functions.config.JsonConfiguration;
import org.junit.Test;
import javax.annotation.Nullable;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.IsEqual.equalTo;
import static org.jtwig.configuration.JtwigConfigurationBuilder.newConfiguration;
public class JsonConfigurationTest {
@Test
public void changeJsonMapperConfigurationShouldAffectTheJsonEncodeFunction() throws Exception {
JtwigModelMap model = new JtwigModelMap();
String result = JtwigTemplate
.inlineTemplate("{{ json_encode 'three' }}", newConfiguration()
.withJsonConfiguration(new JsonConfiguration().jsonMapper(new Function<Object, String>() {
@Nullable
@Override
public String apply(@Nullable Object input) {
return "ohoh";
}
}))
.build())
.render(model);
assertThat(result, is(equalTo("ohoh")));
}
}
| true
|
e6f71ca4657f38d65ee5ca10dd3ebb39cde5c9c1
|
Java
|
mindvv0rk/Fasten
|
/app/src/main/java/ai/testtask/fasten/weather/model/response/autocomplete/AutocompleteResponse.java
|
UTF-8
| 363
| 1.914063
| 2
|
[] |
no_license
|
package ai.testtask.fasten.weather.model.response.autocomplete;
import com.google.gson.annotations.SerializedName;
import java.util.List;
import ai.testtask.fasten.weather.model.City;
public final class AutocompleteResponse {
@SerializedName("RESULTS")
private List<City> mCities;
public List<City> getCities() {
return mCities;
}
}
| true
|
d41464ab1de6c1d283addb255a8cadfee4a19bcb
|
Java
|
jckd1122/Tinder
|
/Tinder V1.0/code/Tinder/src/cn/tinder/das/exception/message/ArrangeExceptionMsg.java
|
UTF-8
| 655
| 1.828125
| 2
|
[] |
no_license
|
package cn.tinder.das.exception.message;
public class ArrangeExceptionMsg {
public static final String INDEX_ERR = "INDEX读取错误";
public static final String SALEINFO_ERR ="SALEINFO读取错误";
public static final String ARRINFO_ERR = "排班信息错误";
public static final String BASICARRANGE_ARRMODE_ERR = "读取排班用基础信息错误";
public static final String BASIC_HOLIDAY_ERR = "读取假日信息错误";
public static final String BASIC_JOB_ERR = "读取岗位信息错误";
public static final String USER_ERR = "读取User错误";
public static final String REST_DAY_WRONG = "员工休息天数不能少于4天";
}
| true
|
4ee4a9b682bcfc90f362bf811c5418c087ef3997
|
Java
|
benjaminscridon/Assignment4-SD
|
/Assignment4 SD/Java SOAP Services Project/assignment4/src/ro/utcluj/sd/assignment4/service/TestMain.java
|
UTF-8
| 797
| 2.328125
| 2
|
[] |
no_license
|
package ro.utcluj.sd.assignment4.service;
import ro.utcluj.sd.assignment4.dto.PackageDTO;
import ro.utcluj.sd.assignment4.dto.UserDTO;
public class TestMain {
public static void main(String[] args){
PackageServiceBean p = new PackageServiceBean();
UserDTO sender = new UserDTO();
sender.setEmail("russ");
sender.setFirstName("dasd");
sender.setLastName("dasd");
sender.setPassword("123456");
UserDTO receiver = new UserDTO();
receiver.setEmail("dasddddddaaad");
receiver.setPassword("123456");
PackageDTO pack = new PackageDTO();
pack.setDescription("pppp");
pack.setDestinationCity("pppp");
pack.setName("pppp");
pack.setReceiver(receiver);
pack.setTacking(false);
pack.setSenderCity("pppp");
pack.setSender(sender);
p.addPackage(pack);
}
}
| true
|
ad796fa5c7e2b73b9b05abec76ba4de61ad2c752
|
Java
|
Leefirm/GX_NC5.X
|
/lcsw_sw/src/public/nc/vo/lcsw/sw07/.svn/text-base/SW07GetCheckClass.java.svn-base
|
GB18030
| 808
| 1.953125
| 2
|
[] |
no_license
|
package nc.vo.lcsw.sw07;
import java.io.Serializable;
import nc.vo.trade.pub.IBDGetCheckClass2;
/**
* <b>װݻУ·</b>
* @version 1.0
* @since 1.0
* @author չ
* @time 2014-09-03 17:20:11
*/
public class SW07GetCheckClass implements Serializable,IBDGetCheckClass2{
private static final long serialVersionUID = 1L;
public SW07GetCheckClass() {
}
/*
* ǰ̨Уȫ·
* @see nc.vo.trade.pub.IBDGetCheckClass2#getUICheckClass()
*/
public String getUICheckClass() {
return "nc.ui.lcsw.sw07.SW07CardCheck";
}
/*
* ų́Уȫ·
* @see nc.vo.trade.pub.IBDGetCheckClass#getCheckClass()
*/
public String getCheckClass() {
return "nc.bs.lcsw.sw07.SW07BusiCheck";
}
}
| true
|
89eda756f9677bec9a8bc49e9a627e0335ba7271
|
Java
|
QuattroViper/TeamspeakAdminAndroid
|
/app/src/main/java/com/example/marno/teamspeakapp/JTS3ServerQueryExample.java
|
UTF-8
| 9,142
| 2.65625
| 3
|
[] |
no_license
|
package com.example.marno.teamspeakapp;
import java.io.PrintStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Vector;
import com.example.marno.teamspeakapp.JTS3ServerQuery;
import com.example.marno.teamspeakapp.TS3ServerQueryException;
import com.example.marno.teamspeakapp.TeamspeakActionListener;
public class JTS3ServerQueryExample implements TeamspeakActionListener
{
JTS3ServerQuery query;
boolean debug = false; // Set to true if you want to see all key / values
public static void main(String[] args)
throws Exception
{
JTS3ServerQueryExample jts3 = new JTS3ServerQueryExample();
jts3.runServerMod();
}
/*
* Just output all key / value pairs
*/
void outputHashMap(HashMap<String, String> hm, PrintStream stream)
{
if (hm == null)
{
return;
}
Collection<String> cValue = hm.values();
Collection<String> cKey = hm.keySet();
Iterator<String> itrValue = cValue.iterator();
Iterator<String> itrKey = cKey.iterator();
while (itrValue.hasNext() && itrKey.hasNext())
{
stream.println(itrKey.next() + ": " + itrValue.next());
}
}
public void teamspeakActionPerformed(String eventType, HashMap<String, String> eventInfo)
{
if (debug) System.out.println(eventType + " received");
if (debug) outputHashMap(eventInfo, System.out);
if (eventType.equals("notifytextmessage"))
{
if (eventInfo.get("msg").equalsIgnoreCase("!quitbot")) // Quit this program
{
try
{
query.sendTextMessage(Integer.parseInt(eventInfo.get("invokerid")), JTS3ServerQuery.TEXTMESSAGE_TARGET_CLIENT, "Bye Bye, my master!");
query.removeTeamspeakActionListener();
query.closeTS3Connection();
}
catch (Exception e)
{
e.printStackTrace();
try
{
query.sendTextMessage(Integer.parseInt(eventInfo.get("invokerid")), JTS3ServerQuery.TEXTMESSAGE_TARGET_CLIENT, "An error occurred: " + e.toString());
}
catch (Exception e2) { /* do nothing */ }
}
System.exit(0);
}
else if (eventInfo.get("msg").equalsIgnoreCase("!clientlist")) // Client List
{
try
{
Vector<HashMap<String, String>> dataClientList = query.getList(JTS3ServerQuery.LISTMODE_CLIENTLIST, "-info,-times");
StringBuffer sb = new StringBuffer();
for (HashMap<String, String> hashMap : dataClientList)
{
if (debug) outputHashMap(hashMap, System.out);
if (sb.length() > 0)
{
sb.append(", ");
}
sb.append(hashMap.get("client_nickname"));
}
query.sendTextMessage(Integer.parseInt(eventInfo.get("invokerid")), JTS3ServerQuery.TEXTMESSAGE_TARGET_CLIENT, "Client List (only client names displayed): " + sb.toString());
}
catch (Exception e)
{
e.printStackTrace();
try
{
query.sendTextMessage(Integer.parseInt(eventInfo.get("invokerid")), JTS3ServerQuery.TEXTMESSAGE_TARGET_CLIENT, "An error occurred: " + e.toString());
}
catch (Exception e2) { /* do nothing */ }
}
}
else if (eventInfo.get("msg").equalsIgnoreCase("!channellist")) // Channel List
{
try
{
Vector<HashMap<String, String>> dataChannelList = query.getList(JTS3ServerQuery.LISTMODE_CHANNELLIST);
StringBuffer sb = new StringBuffer();
for (HashMap<String, String> hashMap : dataChannelList)
{
if (debug) outputHashMap(hashMap, System.out);
if (sb.length() > 0)
{
sb.append(", ");
}
sb.append(hashMap.get("channel_name"));
}
query.sendTextMessage(Integer.parseInt(eventInfo.get("invokerid")), JTS3ServerQuery.TEXTMESSAGE_TARGET_CLIENT, "Channel List (only channel names displayed): " + sb.toString());
}
catch (Exception e)
{
e.printStackTrace();
try
{
query.sendTextMessage(Integer.parseInt(eventInfo.get("invokerid")), JTS3ServerQuery.TEXTMESSAGE_TARGET_CLIENT, "An error occurred: " + e.toString());
}
catch (Exception e2) { /* do nothing */ }
}
}
else if (eventInfo.get("msg").equalsIgnoreCase("!logview")) // Channel List
{
try
{
Vector<HashMap<String, String>> dataLogList = query.getLogEntries(4, false, false, 0);
StringBuffer sb = new StringBuffer();
for (HashMap<String, String> hashMap : dataLogList)
{
if (debug) outputHashMap(hashMap, System.out);
if (sb.length() > 0)
{
sb.append("\n");
}
sb.append(hashMap.get("l"));
}
query.sendTextMessage(Integer.parseInt(eventInfo.get("invokerid")), JTS3ServerQuery.TEXTMESSAGE_TARGET_CLIENT, "Log entries (last 4 lines):\n" + sb.toString());
}
catch (Exception e)
{
e.printStackTrace();
try
{
query.sendTextMessage(Integer.parseInt(eventInfo.get("invokerid")), JTS3ServerQuery.TEXTMESSAGE_TARGET_CLIENT, "An error occurred: " + e.toString());
}
catch (Exception e2) { /* do nothing */ }
}
}
else if (eventInfo.get("msg").equalsIgnoreCase("!serverinfo")) // Server Info
{
try
{
HashMap<String, String> dataServerInfo = query.getInfo(JTS3ServerQuery.INFOMODE_SERVERINFO, 0);
if (debug) outputHashMap(dataServerInfo, System.out);
query.sendTextMessage(Integer.parseInt(eventInfo.get("invokerid")), JTS3ServerQuery.TEXTMESSAGE_TARGET_CLIENT, "Server Info (only server name displayed): " + dataServerInfo.get("virtualserver_name"));
}
catch (Exception e)
{
e.printStackTrace();
try
{
query.sendTextMessage(Integer.parseInt(eventInfo.get("invokerid")), JTS3ServerQuery.TEXTMESSAGE_TARGET_CLIENT, "An error occurred: " + e.toString());
}
catch (Exception e2) { /* do nothing */ }
}
}
else if (eventInfo.get("msg").equalsIgnoreCase("!myservergroups")) // Server Groups of own client
{
try
{
int clientDBID = query.getClientDBIDFromUID(eventInfo.get("invokeruid"));
Vector<HashMap<String, String>> dataClientServerGroups = query.getList(JTS3ServerQuery.LISTMODE_SERVERGROUPSBYCLIENTID, "cldbid="+Integer.toString(clientDBID));
StringBuffer sb = new StringBuffer();
for (HashMap<String, String> hashMap : dataClientServerGroups)
{
if (debug) outputHashMap(hashMap, System.out);
if (sb.length() > 0)
{
sb.append(", ");
}
sb.append(hashMap.get("sgid"));
}
query.sendTextMessage(Integer.parseInt(eventInfo.get("invokerid")), JTS3ServerQuery.TEXTMESSAGE_TARGET_CLIENT, "You are member of the following Server Group IDs: " + sb.toString());
}
catch (Exception e)
{
e.printStackTrace();
try
{
query.sendTextMessage(Integer.parseInt(eventInfo.get("invokerid")), JTS3ServerQuery.TEXTMESSAGE_TARGET_CLIENT, "An error occurred: " + e.toString());
}
catch (Exception e2) { /* do nothing */ }
}
}
}
}
void runServerMod()
throws Exception
{
query = new JTS3ServerQuery();
try
{
// Connect to TS3 Server, set your server data here
query.connectTS3Query("localhost", 10011);
// Login with an server query account. If needed, uncomment next line!
//query.loginTS3("serveradmin", "password");
// Set our class for receiving events
query.setTeamspeakActionListener(this);
// Select virtual Server
query.selectVirtualServer(1);
// Register some events
query.addEventNotify(JTS3ServerQuery.EVENT_MODE_TEXTSERVER, 0); // Server Chat event
query.addEventNotify(JTS3ServerQuery.EVENT_MODE_TEXTCHANNEL, 0); // Channel Chat event
query.addEventNotify(JTS3ServerQuery.EVENT_MODE_TEXTPRIVATE, 0); // Private Chat event
}
catch (TS3ServerQueryException sqe)
{
System.err.println("An error occurred while connecting to the TS3 server, stopping now! More details below.");
if (sqe.getFailedPermissionID() >= 0)
{
HashMap<String, String> permInfo = null;
try
{
// This needs the permission b_serverinstance_permission_list
permInfo = query.getPermissionInfo(sqe.getFailedPermissionID());
System.err.println("Missing permission:");
outputHashMap(permInfo, System.err);
}
catch (Exception e)
{
// Ignore this exception to make sure, that a missing b_serverinstance_permission_list don't quit this program.
}
}
throw sqe;
}
catch (Exception e)
{
System.err.println("An error occurred while connecting to the TS3 server, stopping now! More details below.");
throw e;
}
System.out.println("You can now chat with this program, using server chat,");
System.out.println("channel chat (in default channel) or by private messaging the query connection!");
System.out.println("Commands are (some might need serveradmin permissions):");
System.out.println("!channellist");
System.out.println("!clientlist");
System.out.println("!logview");
System.out.println("!myservergroups");
System.out.println("!serverinfo");
System.out.println("!quitbot");
System.out.println();
while(true)
{
try
{
/*
* Make sure that the Java VM don't quit this program.
*/
Thread.sleep(100);
}
catch (Exception e)
{
}
}
}
}
| true
|
fcaa2aa97af2b4f3a02d0d589fc00061423da006
|
Java
|
jmstart/SpringBoot_HighLevel
|
/SpringBoot_Security_05/src/main/java/com/jiaming/config/mySecurityConfig.java
|
UTF-8
| 2,596
| 2.453125
| 2
|
[] |
no_license
|
package com.jiaming.config;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
/**
* @author jmstart
* @create 2020-05-28 18:51
*/
@EnableWebSecurity //开启注解支持
public class mySecurityConfig extends WebSecurityConfigurerAdapter {
//定义授权规则
@Override
protected void configure(HttpSecurity http) throws Exception {
//定制请求的授权规则
http.authorizeRequests().antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("VIP1")
.antMatchers("/level2/**").hasRole("VIP2")
.antMatchers("/level3/**").hasRole("VIP3");
/**
* formLogin(): 开启自动配置登录功能,如果没有登录权限会自动跳转到登录页面
* 1. 访问/login请求 来到登录页
* 2. 访问/login?error 登录失败重定向到登录错误页面
* loginPage("/userlogin"): 自定义登录页
*/
http.formLogin()/*.loginPage("/userlogin")*/;
/**
* logout(): 开启自动配置注销功能
* 1. 访问/logout 表示用户注销, 清空session
* 2. 默认注销成功会返回到 /login?logout页面
* logoutSuccessUrl("/"): 自己定义注销成功后返回首页
*/
http.logout().logoutSuccessUrl("/");
/**
* 开启记住我功能
* 登录成功后,将Cookie发送给浏览器保存,以后登录就带这个Cookie,检查通过免登录
* 点击注销,会删除这个Cookie
* .rememberMeParameter("remeber"): 自定义记住我
*/
http.rememberMe()/*.rememberMeParameter("remeber")*/;
}
//定义认证规则
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//从内存里查用户密码
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("admin").password(new BCryptPasswordEncoder().encode("root")).roles("VIP1", "VIP2")
.and()
.withUser("xiaoming").password(new BCryptPasswordEncoder().encode("root")).roles("VIP1","VIP2", "VIP3");
}
}
| true
|
db590ff2cdaf542f40fd98bfa56f659489d9edc4
|
Java
|
jtarlecki/vfd
|
/services/RebatePrograms/src/com/rebateprograms/data/output/GetNewequipmentByTechnologyRtnType.java
|
UTF-8
| 646
| 1.835938
| 2
|
[] |
no_license
|
package com.rebateprograms.data.output;
/**
* Generated for query "getNewequipmentByTechnology" on 07/31/2013 10:22:32
*
*/
public class GetNewequipmentByTechnologyRtnType {
private Integer newequipmentid;
private String newquipmentname;
public Integer getNewequipmentid() {
return newequipmentid;
}
public void setNewequipmentid(Integer newequipmentid) {
this.newequipmentid = newequipmentid;
}
public String getNewquipmentname() {
return newquipmentname;
}
public void setNewquipmentname(String newquipmentname) {
this.newquipmentname = newquipmentname;
}
}
| true
|
35394758a2d14875666047c8c2034a6c6a6e4071
|
Java
|
popadorin/oop-labs3
|
/src/com/oop/lab1/Lab1Task1.java
|
UTF-8
| 324
| 2.390625
| 2
|
[] |
no_license
|
package com.oop.lab1;
public class Lab1Task1 {
public static void main(String[] args) {
int a = 5;
Monitor monitor1 = new Monitor();
monitor1.color = "red";
System.out.println(monitor1.color);
Monitor monitor2 = new Monitor();
System.out.println(monitor2.color);
}
}
| true
|
ff06e944d2ef0b5447143aa2626b9505cc0d44b7
|
Java
|
robin-hood-debug/burndown-chart
|
/src/main/java/de/paluch/burndown/SprintDaysGenerator.java
|
UTF-8
| 1,437
| 3.328125
| 3
|
[] |
no_license
|
package de.paluch.burndown;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.List;
/**
* Sprint Days Calculator. Omits SATURDAY and SUNDAY. <br>
* <br>
* Project: burdnown-chart <br>
* Autor: mark <br>
* Created: 19.03.2012 <br>
* <br>
*/
public class SprintDaysGenerator {
private final boolean regularFreeDays[] = new boolean[Calendar.SATURDAY + 1];
public SprintDaysGenerator() {
regularFreeDays[Calendar.SUNDAY] = true;
regularFreeDays[Calendar.SATURDAY] = true;
}
/**
* @param count
* @param firstDay
* @return List<Date>
*/
public List<Date> generateSprintDays(int count, Date firstDay) {
int maxIterations = count * 14;
int iteration = 0;
Calendar cal = Calendar.getInstance();
cal.setTime(firstDay);
List<Date> result = new ArrayList<Date>();
while (result.size() < count) {
if (iteration++ > maxIterations) {
throw new IllegalStateException("Cannot find requested amount of days, toFind: " + count + ", found: "
+ result.size());
}
if (!regularFreeDays[cal.get(Calendar.DAY_OF_WEEK)]) {
result.add(cal.getTime());
}
cal.add(Calendar.DATE, 1);
}
return Collections.unmodifiableList(result);
}
}
| true
|
7c76d78f6fc4bbea7a7246f8e42530140c2cedaa
|
Java
|
show4268time/algorithm
|
/src/main/java/leetcode/code50/Code6ZigzagConversion.java
|
UTF-8
| 1,185
| 3.65625
| 4
|
[] |
no_license
|
package leetcode.code50;
/**
* @author: PhilipFry
* @create: 2022-05-06 10:29
* @Description: The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this:
* (you may want to display this pattern in a fixed font for better legibility)
*/
public class Code6ZigzagConversion {
public String convert(String s, int numRows) {
if (numRows == 1) {
return s;
}
char[] chars = s.toCharArray();
char[][] matrix = new char[numRows][chars.length];
int[] cursors = new int[numRows];
boolean goesUp = false; // 控制掉头,0=down, 1=up
for (int i = 0, row = 0; i < chars.length; i++) {
matrix[row][cursors[row]++] = chars[i];
// 掉头
if (row == 0) {
goesUp = false;
}
if (row == numRows - 1) {
goesUp = true;
}
// 跑
row = (goesUp) ? row - 1 : row + 1;
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < numRows; i++) {
sb.append(matrix[i], 0, cursors[i]);
}
return sb.toString();
}
}
| true
|
e0e35e043d20536c0c2e27e28a343e51cb045632
|
Java
|
boringcc/SF
|
/src/leetCode/esay_27.java
|
UTF-8
| 887
| 3.765625
| 4
|
[] |
no_license
|
package leetCode;
/**
* 移除元素
* 给定 nums = [0,1,2,2,3,0,4,2], val = 2,
函数应该返回新的长度 5, 并且 nums 中的前五个元素为 0, 1, 3, 0, 4。
注意这五个元素可为任意顺序。
你不需要考虑数组中超出新长度后面的元素。
*/
public class esay_27 {
public int removeElement(int[] nums, int val) {
int n=nums.length;
int i=0;
while(i<n){
if(nums[i]==val){
n--;
nums[i]=nums[n];
} else{
i++;
}
}
return n;
}
//最快解法
public int removeElement2(int[] nums, int val) {
int i = -1,j=0;
int len = nums.length;
while(j<len){
if(nums[j] != val) {
nums[++i] = nums[j];
}
j++;
}
return i+1;
}
}
| true
|
2e2cd73432a21fab5497fd47b49fa9a22db92b5c
|
Java
|
rcgonzalezf/codility-lessons
|
/Codility/StacksAndQueues/StoneWall.java
|
UTF-8
| 1,573
| 3.21875
| 3
|
[
"Unlicense"
] |
permissive
|
import java.util.ArrayList;
import java.util.List;
// https://codility.com/demo/results/demoX7Z9X3-HSB/ 100%
public class StoneWall {
public int solution(int[] H) {
int len = H.length;
Stack<Integer> stack = new Stack<>(len);
int blockCounter = 0;
for (int i = 0; i < len; ++i) {
int element = H[i];
if (stack.isEmpty()) {
stack.push(element);
++blockCounter;
} else {
while (!stack.isEmpty() && stack.peek() > element) {
stack.pop();
}
if (!stack.isEmpty() && stack.peek() == element) {
continue;
} else {
stack.push(element);
++blockCounter;
}
}
}
return blockCounter;
}
public static class Stack<T> {
public List<T> stack;
public Stack(int capacity) {
stack = new ArrayList<>(capacity);
}
public void push(T item) {
stack.add(item);
}
public T pop() {
T item = peek();
stack.remove(stack.size() - 1);
return item;
}
public T peek() {
int position = stack.size();
T item = stack.get(position - 1);
return item;
}
public boolean isEmpty() {
return stack.isEmpty();
}
}
}
| true
|
a6c2f7d18ccbcdbaf4028c7aef48c82870646ad5
|
Java
|
belemirkara/Portakalcucumber2
|
/src/test/java/Pages/ContactInfoControlofmandatoryFieldsPage.java
|
UTF-8
| 2,439
| 1.835938
| 2
|
[] |
no_license
|
package Pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.support.PageFactory;
public class ContactInfoControlofmandatoryFieldsPage {
public ContactInfoControlofmandatoryFieldsPage(WebDriver driver) {
PageFactory.initElements(driver, this);
}
@FindBy(how = How.ID, using = "ownerName")
public WebElement fieldrestaurantownername2;
@FindBy(how = How.ID, using = "ownerLastName")
public WebElement fieldrestaurantownersurname2;
@FindBy(how = How.ID, using = "restaurant-owner-phone")
public WebElement fieldrestaurantownerno2;
@FindBy(how = How.ID, using = "restaurant-phone")
public WebElement fieldrestaurantno2;
@FindBy(how = How.ID, using = "restaurant-owner-email")
public WebElement fieldrestaurantmail2;
@FindBy(how = How.ID, using = "2")
public WebElement failpopup;
@FindBy(how = How.ID, using = "managerName")
public WebElement fieldmanagername2;
@FindBy(how = How.ID, using = "managerLastName")
public WebElement fieldmanagersurname2;
@FindBy(how = How.ID, using = "restaurant-po-number")
public WebElement fieldmanagerno2;
@FindBy(how = How.CLASS_NAME, using = ("alert-warning"))
public WebElement txtcontactmandatory;
@FindBy(how = How.ID, using = ("btnSave"))
public WebElement BUTTONSave;
@FindBy(how = How.ID, using = ("btnSaveAndContinue"))
public WebElement BUTTONSaveandcontinue;
public void ContactInfoMandatory1() {
fieldrestaurantownername2.clear();
}
public void ContactInfoMandatory2() {
fieldrestaurantownersurname2.clear();
}
public void ContactInfoMandatory3() {
fieldrestaurantownerno2.clear();
}
public void ContactInfoMandatory4() {
fieldrestaurantno2.clear();
}
public void ContactInfoMandatory5() {
fieldrestaurantmail2.clear();
}
public void ContactInfoMandatory6() {
failpopup.click();
}
public void ContactInfoMandatory7() {
fieldmanagername2.clear();
}
public void ContactInfoMandatory8() {
fieldmanagersurname2.clear();
}
public void ContactInfoMandatory9() {
fieldmanagerno2.clear();
}
public void ContactInfoMandatory10() {
failpopup.click();
}
}
| true
|
51d4ea94bc837da44fcb67db693af1565a02fb8b
|
Java
|
sharon-lee-fumi/CarFactory
|
/app/src/main/java/pointclickcare/lish/carfactory/Wheel1Factory.java
|
UTF-8
| 217
| 2.71875
| 3
|
[] |
no_license
|
package pointclickcare.lish.carfactory;
public class Wheel1Factory implements WheelAbstractFactory{
@Override
public Wheel createWheel() {
Wheel1 wheel1 = new Wheel1();
return wheel1;
}
}
| true
|
2f14d046046db1ec048e99921437aaf97b4d5606
|
Java
|
HSETeam/mosCTapp
|
/app/src/main/java/com/hackaton/mosctapp/CommonClasses/Route.java
|
UTF-8
| 820
| 2.828125
| 3
|
[] |
no_license
|
package com.hackaton.mosctapp.CommonClasses;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
/**
* Created by diesersamat on 25/04/15.
*/
public class Route {
boolean direct;
ArrayList<Step> route;
String name;
public Route(boolean direct, ArrayList<Step> route) {
this.route = route;
this.direct = direct;
}
public boolean getDirection(boolean dir) {
return dir ^ this.direct;
}
public ArrayList<Step> getWay(boolean dir) {
boolean currentDir = getDirection(dir);
Step way;
if(currentDir) {
way = new Step("Left", "lalal");
} else {
way = new Step("Right", ";a;a");
}
route.add(0, way);
return route;
}
}
| true
|