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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
1047e4ceb316e1e1bf44be7f607d9a14d9ccbf4f | Java | kkzfl22/demo | /src/main/java/com/liujun/pattern/dynamicproxy/jdk/InvocationHandler.java | UTF-8 | 356 | 2.546875 | 3 | [] | no_license | package com.liujun.pattern.dynamicproxy.jdk;
import java.lang.reflect.Method;
/**
* 动态代理的接口
* @author liujun
*
* @date 2015年5月4日
* @vsersion 0.0.1
*/
public interface InvocationHandler {
/**
* 代理类的核心接口
* @param o 代理的对象
* @param m 方法信息
*/
public void invoke(Object o, Method m);
}
| true |
1c838934c3e97a62b43e8d654b7a69c733176817 | Java | jankichauhan/GridImageSearch | /src/main/java/com/janki/gridimagesearch/activities/ImageDisplayActivity.java | UTF-8 | 4,819 | 1.96875 | 2 | [] | no_license | package com.janki.gridimagesearch.activities;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.ShareActionProvider;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import com.janki.gridimagesearch.R;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import uk.co.senab.photoview.PhotoViewAttacher;
public class ImageDisplayActivity extends ActionBarActivity {
private ShareActionProvider miShareAction;
private ImageView ivImageResult;
private ProgressBar pbImageLoad;
private PhotoViewAttacher mAttacher;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_display);
}
public void setupShareIntent() {
// Fetch Bitmap Uri locally
ImageView ivImage = (ImageView) findViewById(R.id.ivFullImage);
Uri bmpUri = getLocalBitmapUri(ivImage); // see previous remote images section
// Create share intent as described above
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
shareIntent.setType("image/*");
// Attach share event to the menu item provider
miShareAction.setShareIntent(shareIntent);
}
// Returns the URI path to the Bitmap displayed in specified ImageView
public Uri getLocalBitmapUri(ImageView imageView) {
// Extract Bitmap from ImageView drawable
Drawable drawable = imageView.getDrawable();
Bitmap bmp = null;
if (drawable instanceof BitmapDrawable) {
bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
} else {
return null;
}
// Store image to default external storage directory
Uri bmpUri = null;
try {
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS), "share_image_" + System.currentTimeMillis() + ".png");
file.getParentFile().mkdirs();
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = Uri.fromFile(file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
@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_image_display, menu);
MenuItem item = menu.findItem(R.id.image_share);
miShareAction = (ShareActionProvider) MenuItemCompat.getActionProvider(item);
String url = getIntent().getStringExtra("url");
String website = getIntent().getStringExtra("website");
// Find the image view
ivImageResult = (ImageView) findViewById(R.id.ivFullImage);
pbImageLoad = (ProgressBar) findViewById(R.id.pbImageLoad);
pbImageLoad.setVisibility(View.VISIBLE);
// Load the image in the image view
Picasso.with(this)
.load(url)
.into(ivImageResult, new Callback() {
@Override
public void onSuccess() {
pbImageLoad.setVisibility(View.GONE);
setupShareIntent();
if (mAttacher != null) {
mAttacher.update();
} else {
mAttacher = new PhotoViewAttacher(ivImageResult);
}
}
@Override
public void onError() {
}
});
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.image_share) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| true |
4816020d4355d35dc56a1a285d0199056a918b9a | Java | zyb2013/Warriors | /src/com/yayo/warriors/module/pack/rule/BackpackRule.java | UTF-8 | 1,146 | 2.578125 | 3 | [] | no_license | package com.yayo.warriors.module.pack.rule;
import com.yayo.warriors.module.pack.type.BackpackType;
import com.yayo.warriors.module.user.type.Job;
public class BackpackRule {
/**
* 获得默认的背包位置信息
*
* @param job 角色的职业
* @param backpack 背包号
* @return
*/
public static byte[] getDefaultPosition(Job job, int backpack) {
if(backpack != BackpackType.USER_PANEL_BACKPACK) {
return null;
}
switch (job) {
case XINGXIU: return new byte[]{ 0, 23, 48, 95, 50, 95, 49, 48, 48, 54, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124 };
case XIAOYAO: return new byte[]{ 0, 23, 48, 95, 50, 95, 49, 48, 48, 52, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124 };
case TIANLONG: return new byte[]{ 0, 23, 48, 95, 50, 95, 49, 48, 48, 48, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124 };
case TIANSHAN: return new byte[]{ 0, 23, 48, 95, 50, 95, 49, 48, 48, 53, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124, 124 };
}
return null;
//默认的背包位置. 物理攻击命令
}
}
| true |
57554d4b233adbbda565e91bcfbc6e98a6447567 | Java | smartcommunitylab/smartcampus.vas.roveretoexplorer.android | /RoveretoExplorer/src/eu/iescities/pilot/rovereto/roveretoexplorer/custom/SearchHelper.java | UTF-8 | 2,805 | 1.960938 | 2 | [] | no_license | /*******************************************************************************
* Copyright 2012-2013 Trento RISE
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package eu.iescities.pilot.rovereto.roveretoexplorer.custom;
import java.util.Arrays;
import java.util.List;
import android.content.Context;
import eu.iescities.pilot.rovereto.roveretoexplorer.R;
import eu.iescities.pilot.rovereto.roveretoexplorer.fragments.search.WhenForSearch;
import eu.iescities.pilot.rovereto.roveretoexplorer.fragments.search.WhereForSearch;
public class SearchHelper {
private static long oneDay = 1 * 24 * 60 * 60 * 1000;
private static WhenForSearch[] WHEN_CATEGORIES = null;
private static WhereForSearch[] WHERE_CATEGORIES =null;
public interface OnSearchListener {
void onSearch(String query);
}
public static void initSpinners(Context context) {
WHEN_CATEGORIES = new WhenForSearch[] {
new WhenForSearch(context.getString(R.string.search_anytime),0,0),
new WhenForSearch(context.getString(R.string.search_today),0,oneDay),
new WhenForSearch(context.getString(R.string.search_tomorrow),oneDay,oneDay),
new WhenForSearch(context.getString(R.string.search_thisweek),0,7*oneDay),
new WhenForSearch(context.getString(R.string.search_intwoweeks),0,14 * oneDay),
new WhenForSearch(context.getString(R.string.search_inonemonth),0,30 * oneDay)};
WHERE_CATEGORIES = new WhereForSearch[] {
new WhereForSearch(context.getString(R.string.search_anywhere),0.00),
new WhereForSearch(context.getString(R.string.search_within,"100m"),0.001),
new WhereForSearch(context.getString(R.string.search_within,"200m"),0.002),
new WhereForSearch(context.getString(R.string.search_within,"500m"),0.005),
new WhereForSearch(context.getString(R.string.search_within,"1km"),0.01),
new WhereForSearch(context.getString(R.string.search_within,"10km"),0.1),
new WhereForSearch(context.getString(R.string.search_within,"50km"),0.5)};
}
public static List<WhenForSearch> getWhenList() {
return Arrays.asList(WHEN_CATEGORIES);
}
public static List<WhereForSearch> getWhereList() {
return Arrays.asList(WHERE_CATEGORIES);
}
}
| true |
fba957905e942ced7fbb0906511556b6be8817ff | Java | Youngdong/LocationServer | /src/main/java/net/flycamel/locationserver/domain/LocationDataService.java | UTF-8 | 561 | 2.046875 | 2 | [] | no_license | package net.flycamel.locationserver.domain;
import io.grpc.locationservice.LocationServiceOuterClass.LocationHistoryInfo;
import io.grpc.locationservice.LocationServiceOuterClass.SearchResultInfo;
import java.util.List;
import java.util.Optional;
public interface LocationDataService {
LocationData save(LocationData data);
Optional<LocationData> findLastLocation(String id);
List<LocationHistoryInfo> findHistory(String id, long startTime, long endTime);
List<SearchResultInfo> search(double latitude, double longitude, double radius);
}
| true |
9b502fbb38f43ce7336788637fcf4f8120c3d95c | Java | nongdancode/Hotel_java | /src/main/java/com/apartment/management/service/interfaces/parkingLot/TransportService.java | UTF-8 | 290 | 1.648438 | 2 | [] | no_license | package com.apartment.management.service.interfaces.parkingLot;
import com.apartment.management.model.parkingLot.Transport;
import com.apartment.management.service.interfaces.GeneralService;
public interface TransportService<T extends Transport> extends
GeneralService<T, Integer>
{
}
| true |
e95cba68e2ce60e748fe663bfb78f23bb341f71c | Java | o1711/somecode | /fsa/fs-uicommons/src/api/java/com/fs/uicommons/api/gwt/client/facebook/LoginResponseJSO.java | UTF-8 | 706 | 1.78125 | 2 | [] | no_license | /**
* All right is from Author of the file,to be explained in comming days.
* Mar 26, 2013
*/
package com.fs.uicommons.api.gwt.client.facebook;
import com.google.gwt.core.client.JavaScriptObject;
/**
* @author wu <code>
{
status: 'connected',
authResponse: {
accessToken: '...',
expiresIn:'...',
signedRequest:'...',
userID:'...'
}
}
</code> ref:
* https://developers.facebook.com/docs/howtos/login/getting-started/
*/
public final class LoginResponseJSO extends JavaScriptObject {
protected LoginResponseJSO() {
}
public native AuthResponseJSO getAuthResponse()
/*-{
return this.authResponse;
}-*/;
}
| true |
a01124c5e099f445b50eeef0ff0903c7da5f8a1a | Java | uestcwangci/many_module | /leetcode/src/tx_jingxuan/Easy5.java | UTF-8 | 372 | 2.453125 | 2 | [] | no_license | package tx_jingxuan;
public class Easy5 {
public int removeDuplicates(int[] nums) {
int before = 0;
int after = 0;
for (; before < nums.length - 1; before++) {
if (nums[before] != nums[before + 1]) {
after++;
nums[after] = nums[before + 1];
}
}
return after + 1;
}
}
| true |
71c3d4a6e952b23171a99e01b8105606d35593a6 | Java | DanieleGiorgi94/Progetto_ISPW | /fersa_laptop/src/Boundary/Annuncio_ospite.java | UTF-8 | 3,914 | 2.1875 | 2 | [] | no_license | package Boundary;
import Controller.MainController;
import application.Main;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.layout.AnchorPane;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import java.io.IOException;
import static Boundary.Annuncio_locatario.annuncioBean;
public class Annuncio_ospite {
@FXML
private Main main;
@FXML
protected static Stage stage;
@FXML
protected Text textCity;
@FXML
protected Text textPrice;
@FXML
protected Text textDescription;
@FXML
protected Text textUser;
@FXML
protected Text textAnnounceName;
@FXML
public void accedi(ActionEvent event){
try {
AnchorPane root = (AnchorPane) FXMLLoader.load(getClass().getResource("/Boundary/Login.fxml"));
Scene scene = new Scene(root);
Stage stage = new Stage();
stage.setScene(scene);
stage.setTitle("Login");
stage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
@FXML
public void registra(ActionEvent event) {
try {
AnchorPane root = (AnchorPane) FXMLLoader.load(getClass().getResource("/Boundary/Registrazione.fxml"));
Scene scene = new Scene(root);
Stage stage = new Stage();
stage.setScene(scene);
stage.setTitle("Registrazione");
stage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
public void displayRenterShowcase(ActionEvent event) {
try {
AnchorPane root = (AnchorPane) FXMLLoader.load(getClass().getResource("/Boundary/HomepageOspite_annunciLocatori.fxml"));
Scene scene = new Scene(root);
stage = main.getStage();
stage.setScene(scene);
stage.setTitle("Homepage");
this.stage.close();
stage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
@FXML
public void displayTenantShowcase(ActionEvent event) {
try {
AnchorPane root = (AnchorPane) FXMLLoader.load(getClass().getResource("/Boundary/HomepageOspite_annunciLocatari.fxml"));
Scene scene = new Scene(root);
stage = main.getStage(); // mi prendo il primary stage definito nell'initRootLayout
stage.setScene(scene); //ci setto la nuova scene da visualizzare senza aprire una nuova finestra
stage.setTitle("Homepage");
this.stage.close();//chiudo la finestra precedente
stage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
@FXML
public void signal(ActionEvent event){
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Attenzione!");
alert.setHeaderText("Registrazione necessaria");
alert.setContentText("Devi effettuare il login per segnalare questo annuncio");
alert.showAndWait();
alert.close();
}
@FXML
public void insertFavorites(ActionEvent event){
}
@FXML
public void cercaSuMappa(ActionEvent event){
}
@FXML
public void cercaPerNome(ActionEvent event){
}
@FXML
public void contattaLocatario(ActionEvent event) {
MainController.increase_counter_renting(annuncioBean);
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Grazie!");
alert.setHeaderText("Locatario contattato");
alert.setContentText("Controllo della sua prenotazione passata in gestione a Renting");
alert.showAndWait();
alert.close();
System.out.println("Controllo della prenotazione passato a Renting");
}
}
| true |
d3a9ab343d9d0d598128016ad58fb83eefee52fd | Java | limamarcelo/student_manager | /src/main/java/model/entity/subject/Subject.java | UTF-8 | 1,119 | 2.65625 | 3 | [] | no_license | package model.entity.subject;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "subject")
public class Subject {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_subject")
private Long id;
@Column(name = "name_subject", length = 40, nullable = false, unique = false)
private String name;
@Column(name = "teacher_subject")
private Long teacher;
public Subject() {}
public Subject(Long id, String name, Long teacher) {
setId(id);
setName(name);
setTeacher(teacher);
}
public Subject(String name, Long teacher) {
setName(name);
setTeacher(teacher);
}
public void setId(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setTeacher(Long teacher) {
this.teacher = teacher;
}
public Long getTeacher() {
return teacher;
}
} | true |
2d60041aca561eca5758d238d0983ef7ac056d0b | Java | zdco/onvif-java-lib | /src/org/onvif/ver10/device/wsdl/SetDynamicDNS.java | GB18030 | 3,494 | 1.921875 | 2 | [
"Apache-2.0"
] | permissive | //
// ļ JavaTM Architecture for XML Binding (JAXB) ʵ v2.2.11 ɵ
// <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// ±Դģʽʱ, ԴļĶʧ
// ʱ: 2015.12.11 ʱ 09:30:43 PM CST
//
package org.onvif.ver10.device.wsdl;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import javax.xml.datatype.Duration;
import org.onvif.ver10.schema.DynamicDNSType;
/**
* <p>anonymous complex type Java ࡣ
*
* <p>ģʽƬָڴеԤݡ
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="Type" type="{http://www.onvif.org/ver10/schema}DynamicDNSType"/>
* <element name="Name" type="{http://www.onvif.org/ver10/schema}DNSName" minOccurs="0"/>
* <element name="TTL" type="{http://www.w3.org/2001/XMLSchema}duration" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"type",
"name",
"ttl"
})
@XmlRootElement(name = "SetDynamicDNS")
public class SetDynamicDNS {
@XmlElement(name = "Type", required = true)
@XmlSchemaType(name = "string")
protected DynamicDNSType type;
@XmlElement(name = "Name")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlSchemaType(name = "token")
protected String name;
@XmlElement(name = "TTL")
protected Duration ttl;
/**
* ȡtypeԵֵ
*
* @return
* possible object is
* {@link DynamicDNSType }
*
*/
public DynamicDNSType getType() {
return type;
}
/**
* typeԵֵ
*
* @param value
* allowed object is
* {@link DynamicDNSType }
*
*/
public void setType(DynamicDNSType value) {
this.type = value;
}
/**
* ȡnameԵֵ
*
* @return
* possible object is
* {@link String }
*
*/
public String getName() {
return name;
}
/**
* nameԵֵ
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* ȡttlԵֵ
*
* @return
* possible object is
* {@link Duration }
*
*/
public Duration getTTL() {
return ttl;
}
/**
* ttlԵֵ
*
* @param value
* allowed object is
* {@link Duration }
*
*/
public void setTTL(Duration value) {
this.ttl = value;
}
}
| true |
3d7d23a754caf7c2e7163cb6945e78e87a228dac | Java | cmu-mtlab/grex | /tst/ruleLearnerTest/MockExtractedRule.java | UTF-8 | 1,354 | 2.75 | 3 | [] | no_license | package ruleLearnerTest;
import ruleLearnerNew.ExtractedRule;
public class MockExtractedRule
{
public MockExtractedRule(String type, String srcLhs, String tgtLhs, String srcRhs,
String tgtRhs, String alignIndices, String alignTypes)
{
this.type = type;
this.srcLhs = srcLhs;
this.tgtLhs = tgtLhs;
this.srcRhs = srcRhs;
this.tgtRhs = tgtRhs;
this.alignIndices = alignIndices;
this.alignTypes = alignTypes;
}
public boolean equivalentRule(ExtractedRule rule)
{
String[] ruleParts = rule.toString().split("\\|\\|\\|");
String newLhs = "[" + this.srcLhs + "::" + this.tgtLhs + "]";
return this.type.equals(ruleParts[0].trim())
&& newLhs.equals(ruleParts[1].trim())
&& this.srcRhs.equals(ruleParts[2].trim())
&& this.tgtRhs.equals(ruleParts[3].trim())
&& this.alignIndices.equals(ruleParts[4].trim())
&& this.alignTypes.equals(ruleParts[5].trim());
}
public String toString()
{
return type + "||| [" + srcLhs + ":" + tgtLhs + "|||" + srcRhs + "|||"
+ tgtRhs + "|||" + alignIndices + "|||" + alignTypes;
}
private String type;
private String srcLhs;
private String tgtLhs;
private String srcRhs;
private String tgtRhs;
private String alignIndices;
private String alignTypes;
}
| true |
b3be940a35df04d834f24b7d870622bfdb644291 | Java | adgo/qmate | /MATE/org.tud.inf.st.mbt.automation.selenium/src/org/tud/inf/st/mbt/automation/selenium/SeleniumSimulationAutomation.java | UTF-8 | 4,732 | 2.15625 | 2 | [
"Apache-2.0"
] | permissive | package org.tud.inf.st.mbt.automation.selenium;
import java.util.HashMap;
import java.util.Map;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.tud.inf.st.mbt.actions.PostGenerationAction;
import org.tud.inf.st.mbt.actions.TermAction;
import org.tud.inf.st.mbt.automation.basic.ManualAutomation;
import org.tud.inf.st.mbt.automation.execute.ISimulationResponder;
import org.tud.inf.st.mbt.terms.FloatTerm;
import org.tud.inf.st.mbt.terms.FunctorTerm;
import org.tud.inf.st.mbt.terms.IntegerTerm;
import org.tud.inf.st.mbt.terms.LongTerm;
import org.tud.inf.st.mbt.terms.StringTerm;
import org.tud.inf.st.mbt.terms.Term;
import org.tud.inf.st.mbt.emf.util.ModelUtil;
public class SeleniumSimulationAutomation extends ManualAutomation {
private String connection;
private WebDriver driver;
private Class<? extends WebDriver> driverClass;
private Map<Integer, WebElement> elements = new HashMap<>();
public SeleniumSimulationAutomation(String connection, Class<? extends WebDriver> driverClass) {
this.connection = connection;
this.driverClass = driverClass;
reset();
}
public String getConnection() {
return connection;
}
@Override
public boolean automate(PostGenerationAction action,
ISimulationResponder responder) {
try {
Boolean b = automateLocal(action, responder);
if (b == null)
return super.automate(action, responder);
if(b == true)
return true;
if (b == false)
return false;
} catch (Exception e) {
e.printStackTrace();
return false;
}
return false;
}
public Boolean automateLocal(PostGenerationAction action,
ISimulationResponder responder) {
System.out.println(action);
if (action instanceof TermAction) {
Term term = ((TermAction) action).getTerm();
if (term instanceof FunctorTerm) {
FunctorTerm fterm = (FunctorTerm) term;
String functor = fterm.getFunctor();
if (functor.equals("open") && fterm.getArguments().size() == 1
&& fterm.getArguments().get(0) instanceof StringTerm) {
if(driver !=null)driver.quit();
try {
this.driver = driverClass.newInstance();
} catch (Exception e) {
e.printStackTrace();
}
driver.get(((StringTerm) fterm.getArguments().get(0))
.getValue());
return true;
}
else if (functor.equals("findByName")
&& fterm.getArguments().size() == 2) {
WebElement e = driver.findElement(By
.name(((StringTerm) fterm.getArguments().get(1))
.getValue()));
elements.put(
ModelUtil.hashCode(fterm.getArguments().get(0)), e);
return true;
}
else if (functor.equals("findById")
&& fterm.getArguments().size() == 2) {
WebElement e = driver.findElement(By.id(((StringTerm) fterm
.getArguments().get(1)).getValue()));
elements.put(
ModelUtil.hashCode(fterm.getArguments().get(0)), e);
return true;
}
else if (functor.equals("findByXPath")
&& fterm.getArguments().size() == 2) {
WebElement e = driver.findElement(By
.xpath(((StringTerm) fterm.getArguments().get(1))
.getValue()));
elements.put(
ModelUtil.hashCode(fterm.getArguments().get(0)), e);
return true;
}
else if (functor.equals("submit")
&& fterm.getArguments().size() == 1) {
elements.get(
ModelUtil.hashCode(fterm.getArguments().get(0)))
.submit();
return true;
}
else if (functor.equals("sendKeys")
&& fterm.getArguments().size() == 2) {
elements.get(
ModelUtil.hashCode(fterm.getArguments().get(0)))
.sendKeys(
((StringTerm) fterm.getArguments().get(1))
.getValue());
return true;
}
else if (functor.equals("click")
&& fterm.getArguments().size() == 1) {
elements.get(
ModelUtil.hashCode(fterm.getArguments().get(0)))
.click();
return true;
}
else if (functor.equals("quit")
&& fterm.getArguments().size() == 0)
driver.quit();
return true;
}
}
return null;
}
private static int getIntValue(Term t) {
if (t instanceof IntegerTerm)
return ((IntegerTerm) t).getValue();
else if (t instanceof FloatTerm)
return (int) ((FloatTerm) t).getValue();
else if (t instanceof LongTerm)
return (int) ((LongTerm) t).getValue();
else
return -1;
}
@Override
public void reset() {
elements.clear();
super.reset();
}
}
| true |
bb9e7c6a8c164011ee01bd5950db1c1f1a8c1540 | Java | rtyley/gh4a | /src/com/gh4a/adapter/FeedAdapter.java | UTF-8 | 19,730 | 1.882813 | 2 | [] | no_license | /*
* Copyright 2011 Azwan Adli Abdullah
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gh4a.adapter;
import java.util.List;
import android.content.Context;
import android.content.res.Resources;
import android.text.SpannableString;
import android.text.style.ClickableSpan;
import android.text.style.TextAppearanceSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.gh4a.Gh4Application;
import com.gh4a.R;
import com.gh4a.utils.ImageDownloader;
import com.gh4a.utils.StringUtils;
import com.github.api.v2.schema.ObjectPayloadPullRequest;
import com.github.api.v2.schema.Payload;
import com.github.api.v2.schema.PayloadPullRequest;
import com.github.api.v2.schema.PayloadTarget;
import com.github.api.v2.schema.Repository;
import com.github.api.v2.schema.UserFeed;
/**
* The Feed adapter.
*/
public class FeedAdapter extends RootAdapter<UserFeed> {
/**
* Instantiates a new feed adapter.
*
* @param context the context
* @param objects the objects
*/
public FeedAdapter(Context context, List<UserFeed> objects) {
super(context, objects);
}
/*
* (non-Javadoc)
* @see com.gh4a.adapter.RootAdapter#doGetView(int, android.view.View,
* android.view.ViewGroup)
*/
@Override
public View doGetView(int position, View convertView, ViewGroup parent) {
View v = convertView;
ViewHolder viewHolder = null;
if (v == null) {
LayoutInflater vi = (LayoutInflater) LayoutInflater.from(mContext);
v = vi.inflate(R.layout.feed_row, null);
viewHolder = new ViewHolder();
viewHolder.ivGravatar = (ImageView) v.findViewById(R.id.iv_gravatar);
viewHolder.tvTitle = (TextView) v.findViewById(R.id.tv_title);
viewHolder.tvDesc = (TextView) v.findViewById(R.id.tv_desc);
viewHolder.tvCreatedAt = (TextView) v.findViewById(R.id.tv_created_at);
v.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder) v.getTag();
}
final UserFeed feed = mObjects.get(position);
if (feed != null) {
ImageDownloader.getInstance().download(feed.getActorAttributes().getGravatarId(),
viewHolder.ivGravatar);
viewHolder.ivGravatar.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
/** Open user activity */
Gh4Application context = (Gh4Application) v.getContext()
.getApplicationContext();
context.openUserInfoActivity(v.getContext(), feed.getActorAttributes()
.getLogin(), feed.getActorAttributes().getName());
}
});
viewHolder.tvTitle.setText(formatTitle(feed));
String content = formatDescription(feed, viewHolder, (RelativeLayout) v);
if (content != null) {
viewHolder.tvDesc.setVisibility(View.VISIBLE);
viewHolder.tvDesc.setText(content);
}
else if (View.VISIBLE == viewHolder.tvDesc.getVisibility()) {
viewHolder.tvDesc.setText(null);
viewHolder.tvDesc.setVisibility(View.GONE);
}
else {
viewHolder.tvDesc.setText(null);
viewHolder.tvDesc.setVisibility(View.GONE);
}
viewHolder.tvCreatedAt.setText(pt.format(feed.getCreatedAt()));
}
return v;
}
/**
* Format description.
*
* @param feed the feed
* @param viewHolder the view holder
* @param baseView the base view
* @return the string
*/
private String formatDescription(UserFeed feed, ViewHolder viewHolder,
final RelativeLayout baseView) {
Payload payload = feed.getPayload();
Resources res = mContext.getResources();
LinearLayout ll = (LinearLayout) baseView.findViewById(R.id.ll_push_desc);
ll.removeAllViews();
TextView generalDesc = (TextView) baseView.findViewById(R.id.tv_desc);
ll.setVisibility(View.GONE);
generalDesc.setVisibility(View.VISIBLE);
/** PushEvent */
if (UserFeed.Type.PUSH_EVENT.equals(feed.getType())) {
generalDesc.setVisibility(View.GONE);
ll.setVisibility(View.VISIBLE);
List<String[]> shas = payload.getShas();
Repository repository = feed.getRepository();
boolean isRepoExists = repository != null;
for (int i = 0; i < shas.size(); i++) {
String[] sha = shas.get(i);
SpannableString spannableSha = new SpannableString(sha[0].substring(0, 7));
if (isRepoExists) {
spannableSha.setSpan(new TextAppearanceSpan(baseView.getContext(),
R.style.default_text_medium_url), 0, spannableSha.length(), 0);
}
else {
spannableSha = new SpannableString("(deleted)");
}
TextView tvCommitMsg = new TextView(baseView.getContext());
tvCommitMsg.setText(spannableSha);
tvCommitMsg.append(" " + sha[2]);
tvCommitMsg.setSingleLine(true);
tvCommitMsg.setTextAppearance(baseView.getContext(), R.style.default_text_medium);
ll.addView(tvCommitMsg);
if (i == 2 && shas.size() > 3) {// show limit 3 lines
TextView tvMoreMsg = new TextView(baseView.getContext());
String text = res.getString(R.string.event_push_desc, shas.size() - 3);
tvMoreMsg.setText(text);
ll.addView(tvMoreMsg);
break;
}
}
return null;
}
/** CommitCommentEvent */
else if (UserFeed.Type.COMMIT_COMMENT_EVENT.equals(feed.getType())) {
SpannableString spannableSha = new SpannableString(payload.getCommit().substring(0, 7));
spannableSha.setSpan(new TextAppearanceSpan(baseView.getContext(),
R.style.default_text_medium_url), 0, spannableSha.length(), 0);
generalDesc.setText(R.string.event_commit_comment_desc);
generalDesc.append(spannableSha);
return null;
}
/** PullRequestEvent */
else if (UserFeed.Type.PULL_REQUEST_EVENT.equals(feed.getType())) {
PayloadPullRequest pullRequest = payload.getPullRequest();
if (!StringUtils.isBlank(pullRequest.getTitle())) {
String text = String.format(res.getString(R.string.event_pull_request_desc),
pullRequest.getTitle(),
pullRequest.getCommits(),
pullRequest.getAdditions(),
pullRequest.getDeletions());
return text;
}
return null;
}
/** FollowEvent */
else if (UserFeed.Type.FOLLOW_EVENT.equals(feed.getType())) {
PayloadTarget target = payload.getTarget();
if (target != null) {
String text = String.format(res.getString(R.string.event_follow_desc),
target.getLogin(),
target.getRepos(),
target.getFollowers());
return text;
}
return null;
}
/** WatchEvent */
else if (UserFeed.Type.WATCH_EVENT.equals(feed.getType())) {
Repository repository = feed.getRepository();
StringBuilder sb = new StringBuilder();
if (repository != null) {
sb.append(StringUtils.doTeaser(repository.getDescription()));
}
return sb.toString();
}
/** ForkEvent */
else if (UserFeed.Type.FORK_EVENT.equals(feed.getType())) {
String text = String.format(res.getString(R.string.event_fork_desc),
formatToRepoName(feed));
return text;
}
/** CreateEvent */
else if (UserFeed.Type.CREATE_EVENT.equals(feed.getType())) {
if ("repository".equals(payload.getObject())) {
String text = String.format(res.getString(R.string.event_create_repo_desc),
feed.getActor(),
feed.getPayload().getName());
return text;
}
else if ("branch".equals(payload.getObject()) || "tag".equals(payload.getObject())) {
String text = String.format(res.getString(R.string.event_create_branch_desc),
payload.getObject(),
feed.getActor(),
feed.getPayload().getName(),
feed.getPayload().getObjectName());
return text;
}
generalDesc.setVisibility(View.GONE);
return null;
}
/** DownloadEvent */
else if (UserFeed.Type.DOWNLOAD_EVENT.equals(feed.getType())) {
String filename = payload.getUrl();
int index = filename.lastIndexOf("/");
if (index != -1) {
filename = filename.substring(index + 1, filename.length());
}
return filename;
}
/** GollumEvent */
else if (UserFeed.Type.GOLLUM_EVENT.equals(feed.getType())) {
String text = String.format(res.getString(R.string.event_gollum_desc),
payload.getTitle());
return text;
}
/** PublicEvent */
else if (UserFeed.Type.PUBLIC_EVENT.equals(feed.getType())) {
Repository repository = feed.getRepository();
if (repository != null) {
return StringUtils.doTeaser(repository.getDescription());
}
else {
return payload.getRepo();
}
}
else {
generalDesc.setVisibility(View.GONE);
return null;
}
}
/**
* Format title.
*
* @param feed the feed
* @return the string
*/
private String formatTitle(UserFeed feed) {
Payload payload = feed.getPayload();
Resources res = mContext.getResources();
/** PushEvent */
if (UserFeed.Type.PUSH_EVENT.equals(feed.getType())) {
String text = String.format(res.getString(R.string.event_push_title),
feed.getActor(),
payload.getRef().split("/")[2],
formatFromRepoName(feed));
return text;
}
/** IssuesEvent */
else if (UserFeed.Type.ISSUES_EVENT.equals(feed.getType())) {
String text = String.format(res.getString(R.string.event_issues_title),
feed.getActor(),
payload.getAction(),
payload.getNumber(),
formatFromRepoName(feed));
return text;
}
/** CommitCommentEvent */
else if (UserFeed.Type.COMMIT_COMMENT_EVENT.equals(feed.getType())) {
String text = String.format(res.getString(R.string.event_commit_comment_title),
feed.getActor(),
formatFromRepoName(feed));
return text;
}
/** PullRequestEvent */
else if (UserFeed.Type.PULL_REQUEST_EVENT.equals(feed.getType())) {
int pullRequestNumber = payload.getNumber();
if (payload.getPullRequest() instanceof ObjectPayloadPullRequest) {
pullRequestNumber = ((ObjectPayloadPullRequest) payload.getPullRequest()).getNumber();
}
String text = String.format(res.getString(R.string.event_pull_request_title),
feed.getActor(),
"closed".equals(payload.getAction()) ? "merged" : payload.getAction(),
pullRequestNumber,
formatFromRepoName(feed));
return text;
}
/** WatchEvent */
else if (UserFeed.Type.WATCH_EVENT.equals(feed.getType())) {
String text = String.format(res.getString(R.string.event_watch_title),
feed.getActor(), payload.getAction(),
formatFromRepoName(feed));
return text;
}
/** GistEvent */
else if (UserFeed.Type.GIST_EVENT.equals(feed.getType())) {
String text = String.format(res.getString(R.string.event_gist_title),
feed.getActor(),
payload.getAction(), payload.getName());
return text;
}
/** ForkEvent */
else if (UserFeed.Type.FORK_EVENT.equals(feed.getType())) {
String text = String.format(res.getString(R.string.event_fork_title),
feed.getActor(),
formatFromRepoName(feed));
return text;
}
/** ForkApplyEvent */
else if (UserFeed.Type.FORK_APPLY_EVENT.equals(feed.getType())) {
String text = String.format(res.getString(R.string.event_fork_apply_title),
feed.getActor(),
formatFromRepoName(feed));
return text;
}
/** FollowEvent */
else if (UserFeed.Type.FOLLOW_EVENT.equals(feed.getType())) {
String text = String.format(res.getString(R.string.event_follow_title),
feed.getActor(),
payload.getTarget() != null ? payload.getTarget().getLogin() : payload
.getTargetId());
return text;
}
/** CreateEvent */
else if (UserFeed.Type.CREATE_EVENT.equals(feed.getType())) {
if ("repository".equals(payload.getRefType())) {
String text = String.format(res.getString(R.string.event_create_repo_title),
feed.getActor(), formatFromRepoName(feed));
return text;
}
else if ("branch".equals(payload.getRefType()) || "tag".equals(payload.getRefType())) {
String text = String.format(res.getString(R.string.event_create_branch_title),
feed.getActor(), payload.getRefType(), payload.getRef(),
formatFromRepoName(feed));
return text;
}
else {
return feed.getActor();
}
}
/** DeleteEvent */
else if (UserFeed.Type.DELETE_EVENT.equals(feed.getType())) {
if ("repository".equals(payload.getObject())) {
String text = String.format(res.getString(R.string.event_delete_repo_title),
feed.getActor(), payload.getName());
return text;
}
else {
String text = String.format(res.getString(R.string.event_delete_branch_title),
feed.getActor(), payload.getRefType(), payload.getRef(),
formatFromRepoName(feed));
return text;
}
}
/** WikiEvent */
else if (UserFeed.Type.WIKI_EVENT.equals(feed.getType())) {
String text = String.format(res.getString(R.string.event_wiki_title),
feed.getActor(),
payload.getAction(),
formatFromRepoName(feed));
return text;
}
/** MemberEvent */
else if (UserFeed.Type.MEMBER_EVENT.equals(feed.getType())) {
String text = String.format(res.getString(R.string.event_member_title),
feed.getActor(), payload.getMember().getLogin(),
formatFromRepoName(feed));
return text;
}
/** DownloadEvent */
else if (UserFeed.Type.DOWNLOAD_EVENT.equals(feed.getType())) {
String text = String.format(res.getString(R.string.event_download_title),
feed.getActor(),
formatFromRepoName(feed));
return text;
}
/** GollumEvent */
else if (UserFeed.Type.GOLLUM_EVENT.equals(feed.getType())) {
String text = String.format(res.getString(R.string.event_gollum_title),
feed.getActor(), payload.getAction(), payload.getTitle(),
formatFromRepoName(feed));
return text;
}
/** PublicEvent */
else if (UserFeed.Type.PUBLIC_EVENT.equals(feed.getType())) {
String text = String.format(res.getString(R.string.event_public_title),
feed.getActor(), formatFromRepoName(feed));
return text;
}
/** IssueCommentEvent */
else if (UserFeed.Type.ISSUE_COMMENT_EVENT.equals(feed.getType())) {
String text = String.format(res.getString(R.string.event_issue_comment),
feed.getActor(), formatFromRepoName(feed));
return text;
}
else {
return "";
}
}
/**
* The Class InternalURLSpan.
*/
static class InternalURLSpan extends ClickableSpan {
/** The listener. */
OnClickListener mListener;
/**
* Instantiates a new internal url span.
*
* @param listener the listener
*/
public InternalURLSpan(OnClickListener listener) {
mListener = listener;
}
/*
* (non-Javadoc)
* @see android.text.style.ClickableSpan#onClick(android.view.View)
*/
@Override
public void onClick(View widget) {
mListener.onClick(widget);
}
}
private static String formatFromRepoName(UserFeed userFeed) {
Repository repository = userFeed.getRepository();
if (repository != null) {
return repository.getOwner() + "/" + repository.getName();
}
return "(deleted)";
}
private static String formatToRepoName(UserFeed userFeed) {
String url = userFeed.getUrl();
if (!StringUtils.isBlank(url)) {
String[] urlParts = url.split("/");
if (urlParts.length > 3) {
return urlParts[3] + "/" + urlParts[4];
}
else {
return "(deleted)";
}
}
return "(deleted)";
}
/**
* The Class ViewHolder.
*/
private static class ViewHolder {
/** The iv gravatar. */
public ImageView ivGravatar;
/** The tv title. */
public TextView tvTitle;
/** The tv desc. */
public TextView tvDesc;
/** The tv created at. */
public TextView tvCreatedAt;
}
} | true |
b97575eaff5819f0a84ad04ca09c284edab28ca3 | Java | manisha123-sha/FlyAway | /src/com/dao/FlightDaoImpl.java | UTF-8 | 3,314 | 2.515625 | 3 | [] | no_license | package com.dao;
import java.util.List;
import javax.persistence.TypedQuery;
import javax.transaction.Transactional;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import com.dto.Flight;
public class FlightDaoImpl implements FlightDAO {
private SessionFactory factory;
public FlightDaoImpl() {
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();
factory = meta.getSessionFactoryBuilder().build();
}
@Override
public Integer addFlight(Flight flight) {
Integer Id=null;
Session session=factory.openSession();
Transaction txn=session.beginTransaction();
Id=(Integer) session.save(flight);
txn.commit();
session.close();
return Id;
}
@Override
public List<Flight> listFlights() {
List <Flight> flights=null;
Session session=factory.openSession();
Transaction txn=session.getTransaction();
String hql="FROM Flight";
TypedQuery<Flight> query=session.createQuery(hql);
flights=query.getResultList();
session.close();
return flights;
}
@Override
@Transactional
public void updateFLight(Integer ID, Flight flight) {
Session session=factory.openSession();
Transaction txn=session.beginTransaction();
//1.Fatching Flight Row from db and get it into object
Flight flight1=session.get(Flight.class, ID);
//2.Modify the object attribute with new value
flight1.setAirline(flight.getAirline());
flight1.setArr_datetime(flight.getArr_datetime());
flight1.setDep_datetime(flight.getDep_datetime());
flight1.setActual_datetime(flight.getActual_datetime());
flight1.setPrice(flight.getPrice());
flight1.setStatus(flight.getStatus());
flight1.setCapacity(flight.getCapacity());
flight1.setFrom_airport(flight.getFrom_airport());
flight1.setTo_airport(flight.getTo_airport());
flight1.setFlightId(flight.getFlightId());
//3.Save back the object into database
session.update(flight1);
txn.commit();
session.close();
}
@Override
public void deleteFlight(Integer ID) {
Session session=factory.openSession();
Transaction txn=session.beginTransaction();
//1.Fatching Employee Row from db and get it into object
Flight flight1=session.get(Flight.class, ID);
//2.Delete the record
session.delete(flight1);
txn.commit();
session.close();
}
@Override
@Transactional
public Flight searchFlightById(Integer ID) {
Session session=factory.openSession();
Transaction txn=session.beginTransaction();
//1.Fatching Employee Row from db and get it into object
Flight flight1=session.get(Flight.class, ID);
session.close();
return flight1;
}
@Override
public List<Flight> searchFlights(String hql) {
List <Flight> flights=null;
Session session=factory.openSession();
Transaction txn=session.getTransaction();
TypedQuery<Flight> query=session.createQuery(hql);
flights=query.getResultList();
session.close();
return flights;
}
}
| true |
579d7e78d8698a7371d80f07b3bc781e91fd9c20 | Java | hecc1231/custom-java-compiler | /custom-java-compiler/src/lexicalscanner/statemachine/CharStateMachine.java | GB18030 | 4,873 | 3.328125 | 3 | [] | no_license | package lexicalscanner.statemachine;
import lexicalscanner.LexicalScanner;
/**
* ַ״̬
* @author Hersch
*
*/
public class CharStateMachine {
public CharStateMachine() {
initEndState();
}
//ʼֹ״̬ıǺЧ״̬ĶӦ
/**
* ֵַ,ַֹ״̬ж鸳ֵ
*/
public void initEndState(){
for(int i=60;i<=66;i++){
LexicalScanner.endAttributeArray[i]="0x106";
LexicalScanner.endStateArray[i] = 1;
}
LexicalScanner.endAttributeArray[68] = "0x106";
LexicalScanner.endAttributeArray[71] = "0x106";
LexicalScanner.endAttributeArray[73] = "0x106";
LexicalScanner.endAttributeArray[76] = "0x106";
LexicalScanner.endStateArray[68] = 1;
LexicalScanner.endStateArray[71] = 1;
LexicalScanner.endStateArray[73] = 1;
LexicalScanner.endStateArray[76] = 1;
}
/**
* ַ״̬״̬ı
* @param c
*/
public void changeState(char c){
switch (LexicalScanner.currentState) {
case LexicalScanner.START_STATE:
if(c=='\''){
LexicalScanner.currentState = 49;//'
}
else{
LexicalScanner.currentState = LexicalScanner.START_STATE;
}
break;
case 49:
if(c=='\\'){
LexicalScanner.currentState = 50;//'\
}
else{
LexicalScanner.currentState = 51;//ַ
}
break;
case 50://'\
if(c=='\''){
LexicalScanner.currentState = 52;//'\\
}
else if(c=='r'){
LexicalScanner.currentState = 53;//'\r
}
else if(c=='n'){
LexicalScanner.currentState = 54;//'\n
}
else if(c=='f'){
LexicalScanner.currentState = 55;//'\f
}
else if(c=='t'){
LexicalScanner.currentState = 56;//'\t
}
else if(c=='b'){
LexicalScanner.currentState = 57;//'\b
}
else if(LexicalScanner.isOctalNum(c)&&c<'4'){
LexicalScanner.currentState = 58;//'\˽
}
else if(c=='u'){
LexicalScanner.currentState = 59;// '/u
}
else{
LexicalScanner.currentState = LexicalScanner.ERROR_STATE;
}
break;
case 51://'x
if(c=='\''){
LexicalScanner.currentState = 60;//'x' end
}
else{
LexicalScanner.currentState = LexicalScanner.ERROR_STATE;
}
break;
case 52:
if(c=='\''){
LexicalScanner.currentState = 61;// end
}
else{
LexicalScanner.currentState = LexicalScanner.ERROR_STATE;
}
break;
case 53://'\r
if(c=='\''){
LexicalScanner.currentState = 62;//end
}
else{
LexicalScanner.currentState = LexicalScanner.ERROR_STATE;
}
break;
case 54://'\n
if(c=='\''){
LexicalScanner.currentState = 63;//end
}
else{
LexicalScanner.currentState = LexicalScanner.ERROR_STATE;
}
break;
case 55://'\f
if(c=='\''){
LexicalScanner.currentState = 64;//end
}
else{
LexicalScanner.currentState = LexicalScanner.ERROR_STATE;
}
break;
case 56://'\t
if(c=='\''){
LexicalScanner.currentState = 65;//end
}
else{
LexicalScanner.currentState = LexicalScanner.ERROR_STATE;
}
break;
case 57://'\b
if(c=='\''){
LexicalScanner.currentState = 66;//end
}
else{
LexicalScanner.currentState = LexicalScanner.ERROR_STATE;
}
break;
case 58://'\d
if(LexicalScanner.isOctalNum(c)){
LexicalScanner.currentState = 67;//'\dd
}
else if(c=='\''){
LexicalScanner.currentState = 68;//'\d' end
}
else{
LexicalScanner.currentState = LexicalScanner.ERROR_STATE;
}
break;
case 59:// '/u
if(LexicalScanner.isHexNum(c)){
LexicalScanner.currentState = 69;// '/ux
}
else{
LexicalScanner.currentState = LexicalScanner.ERROR_STATE;
}
break;
case 67:
if(LexicalScanner.isOctalNum(c)){
LexicalScanner.currentState = 70;//'\ddd
}
else if(c=='\''){
LexicalScanner.currentState = 71;//'\dd' end
}
else{
LexicalScanner.currentState = LexicalScanner.ERROR_STATE;
}
break;
case 69:
if(LexicalScanner.isHexNum(c)){
LexicalScanner.currentState = 72;//'/uxx
}
else{
LexicalScanner.currentState = LexicalScanner.ERROR_STATE;
}
break;
case 70:
if(c=='\''){
LexicalScanner.currentState = 73;//'\ddd' end
}
else{
LexicalScanner.currentState = LexicalScanner.ERROR_STATE;
}
break;
case 72:
if(LexicalScanner.isHexNum(c)){
LexicalScanner.currentState = 74;//'uxxx
}
else{
LexicalScanner.currentState = LexicalScanner.ERROR_STATE;
}
break;
case 74:
if(LexicalScanner.isHexNum(c)){
LexicalScanner.currentState = 75;//'uxxxx
}
else{
LexicalScanner.currentState = LexicalScanner.ERROR_STATE;
}
break;
case 75:
if(c=='\''){
LexicalScanner.currentState = 76;//'uxxxx' end
}
else{
LexicalScanner.currentState = LexicalScanner.ERROR_STATE;
}
break;
}
}
}
| true |
fc979b9d16f134bd24c4512351a48dc995e648c8 | Java | magicianx/single-bridge | /src/main/java/com/gaea/single/bridge/controller/user/UserController.java | UTF-8 | 23,629 | 1.742188 | 2 | [] | no_license | package com.gaea.single.bridge.controller.user;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gaea.single.bridge.config.DictionaryProperties;
import com.gaea.single.bridge.constant.CommonHeaderConst;
import com.gaea.single.bridge.constant.DefaultSettingConstant;
import com.gaea.single.bridge.constant.LoboPathConst;
import com.gaea.single.bridge.controller.BaseController;
import com.gaea.single.bridge.converter.UserConverter;
import com.gaea.single.bridge.core.error.BusinessException;
import com.gaea.single.bridge.core.error.ErrorCode;
import com.gaea.single.bridge.core.lobo.LoboClient;
import com.gaea.single.bridge.core.lobo.LoboCode;
import com.gaea.single.bridge.dto.PageReq;
import com.gaea.single.bridge.dto.PageRes;
import com.gaea.single.bridge.dto.Result;
import com.gaea.single.bridge.dto.user.*;
import com.gaea.single.bridge.enums.AuditStatus;
import com.gaea.single.bridge.enums.LoginType;
import com.gaea.single.bridge.enums.UserType;
import com.gaea.single.bridge.service.*;
import com.gaea.single.bridge.util.DateUtil;
import com.gaea.single.bridge.util.JsonUtils;
import com.gaea.single.bridge.util.LoboUtil;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import springfox.documentation.annotations.ApiIgnore;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;
@RestController
@RequestMapping(value = "/user", produces = MediaType.APPLICATION_JSON_VALUE)
@Api(tags = "用户服务")
@Validated
@Slf4j
public class UserController extends BaseController {
@Autowired private LoboClient loboClient;
@Autowired private MessageService yxMessageService;
@Autowired private UserSocialInfoService userRegInfoService;
@Autowired private UserService userService;
@Autowired private UserGreetService userGreetService;
@Autowired private GratuityService gratuityService;
@GetMapping(value = "/v1/columns.net")
@ApiOperation(value = "获取用户栏目列表")
public Mono<Result<List<UserColumnRes>>> getUserColumns(@ApiIgnore ServerWebExchange exchange) {
Map<String, Object> data = new HashMap<>();
data.put("appId", getAppId());
data.put("userId", getUserId(exchange));
return loboClient.postForm(
exchange, LoboPathConst.USER_COLUMN_LIST, data, UserConverter.toUserColumnResList);
}
@GetMapping(value = "/v1/list.net")
@ApiOperation(value = "获取用户列表")
public Mono<Result<PageRes<UserItemRes>>> getUserList(
@ApiParam(value = "栏目id", required = true) @NotNull @RequestParam Long columnId,
@Valid PageReq pageReq,
@ApiIgnore ServerWebExchange exchange) {
Map<String, Object> data = getPageData(pageReq);
data.put("appId", getAppId());
data.put("menuId", columnId);
return loboClient
.postFormForPage(exchange, LoboPathConst.USER_LIST, data, null, UserConverter.toUserItemRes)
.flatMap(
res -> {
if (!res.isSuccess()) {
return Mono.just(res);
}
Mono[] setCityMonos =
res.getData().getRecords().stream()
.map(
user ->
userService
.isEnablePosition(user.getUserId())
.map(
enable -> {
if (!enable) {
user.setCity(DefaultSettingConstant.UNKNOWN_POSITION);
}
return user;
}))
.toArray(Mono[]::new);
return Mono.when(setCityMonos).thenReturn(res);
});
}
@GetMapping(value = "/v1/profile.net")
@ApiOperation(value = "获取用户资料")
public Mono<Result<UserProfileRes>> getUserProfile(
@ApiParam(value = "用户id", required = true) @NotNull @RequestParam Long userId,
@ApiIgnore ServerWebExchange exchange) {
Map<String, Object> data = new HashMap<>();
data.put("appId", getAppId());
data.put("profileId", userId);
Mono<Result<UserProfileRes>> profileMono =
loboClient
.postForm(exchange, LoboPathConst.USER_PROFILE, data, UserConverter.toUserProfileRes)
.flatMap(
result -> {
if (result.isSuccess()) {
return gratuityService
.getRecentGifts(userId)
.map(
giftIcons -> {
result.getData().setGiftIcons(giftIcons);
return result;
})
.flatMap(
r ->
userService
.isEnablePosition(result.getData().getUserId())
.map(
enable -> {
if (!enable) {
result
.getData()
.setCity(DefaultSettingConstant.UNKNOWN_POSITION);
}
return r;
}));
}
return Mono.just(result);
});
Mono<Result<List<AlbumItemRes>>> albumMono =
loboClient.postFormForList(
exchange, LoboPathConst.USER_ALBUM, data, UserConverter.toAlbumItemRes);
return Mono.zip(
profileMono,
albumMono,
(res1, res2) -> {
if (LoboCode.isErrorCode(res1.getCode())) {
throw new BusinessException(
res1.getCode(), LoboCode.getErrorMessage(res1.getCode()));
}
if (res1.getCode() == ErrorCode.INNER_ERROR.getCode()) {
throw ErrorCode.INNER_ERROR.newBusinessException();
}
if (LoboCode.isErrorCode(res2.getCode())) {
throw new BusinessException(
res1.getCode(), LoboCode.getErrorMessage(res1.getCode()));
}
if (res2.getCode() == ErrorCode.INNER_ERROR.getCode()) {
throw ErrorCode.INNER_ERROR.newBusinessException();
}
res2.getData().forEach(album -> res1.getData().getPhotos().add(album.getImgUrl()));
return res1;
})
.onErrorResume(
ex -> {
if (ex instanceof BusinessException) {
return Mono.just(Result.error(((BusinessException) ex).getCode(), ex.getMessage()));
}
return Mono.just(
Result.error(
ErrorCode.INNER_ERROR.getCode(), ErrorCode.INNER_ERROR.getMessage()));
});
}
@GetMapping(value = "/v1/info.do")
@ApiOperation(value = "获取当前登录用户信息")
public Mono<Result<UserInfoRes>> getUserInfo(@ApiIgnore ServerWebExchange exchange) {
return loboClient
.postForm(exchange, LoboPathConst.USER_INFO, null, UserConverter.toUserRes)
.flatMap(
res -> {
if (ErrorCode.isSuccess(res.getCode())) {
return yxMessageService
.getMessageCount(res.getData().getId())
.flatMap(
count -> {
res.getData().setMessageCount(count);
if (res.getData().getUserType() == UserType.ANCHOR) {
return userGreetService
.removeGreetUser(res.getData().getId())
.thenReturn(res);
}
return Mono.just(res);
});
}
return Mono.just(res);
});
}
@GetMapping(value = "/v1/blacks.do")
@ApiOperation(value = "获取黑名单列表")
public Mono<Result<PageRes<BlackUserRes>>> getBlackList(
@ApiIgnore ServerWebExchange exchange, @Valid PageReq pageReq) {
return loboClient.getForPage(
exchange,
LoboPathConst.BLACK_LIST,
getPageData(pageReq),
null,
(obj) -> {
JSONObject result = (JSONObject) obj;
return new BlackUserRes(
result.getLong("userId"),
result.getString("nickName"),
result.getString("portrait"),
result.getString("yunxinId"));
});
}
@DeleteMapping(value = "/v1/black.do")
@ApiOperation(value = "移除黑名单用户")
public Mono<Result<PageRes<BlackUserRes>>> removeBlackUser(
@ApiIgnore ServerWebExchange exchange,
@ApiParam(value = "用户id", required = true) @RequestParam("userId") @NotNull Long userId) {
Map<String, Object> data = new HashMap<>();
data.put("blackId", userId);
data.put("type", "2");
return loboClient.postForm(exchange, LoboPathConst.REMOVE_BLACK_USER, data, null);
}
@PostMapping(value = "/v1/login.net", consumes = MediaType.APPLICATION_JSON_VALUE)
@ApiOperation(value = "用户登录")
public Mono<Result<LoginRes>> login(
@ApiIgnore ServerWebExchange exchange, @Valid @RequestBody LoginReq req) {
Mono<Result<LoginRes>> mono;
if (req.getType() == LoginType.PHONE_DIRECT) {
Map<String, Object> data = new HashMap<>();
data.put("os", getOsType(exchange).getCode());
data.put("appId", getAppId());
data.put("channel", getChannelId(exchange));
data.put("deviceNo", getDeviceNo(exchange));
data.put("token", req.getAccessToken());
mono = loboClient.postForm(exchange, LoboPathConst.ONE_LOGIN, data, UserConverter.toLoginRes);
} else {
replaceToPasswordLoginForAudit(req);
Map<String, Object> data = new HashMap<>();
data.put("type", req.getType().getCode());
data.put("os", getOsType(exchange).getCode());
data.put("openId", req.getOpenId());
data.put("imageUrl", req.getPortraitUrl());
data.put("appId", getAppId());
data.put("channel", getChannelId(exchange));
data.put("deviceNo", getDeviceNo(exchange));
data.put("accessToken", req.getAccessToken());
data.put("userName", req.getNickName());
data.put("version", getAppVersion(exchange));
data.put("userMobile", req.getPhoneNum());
data.put("password", req.getPassword());
data.put("smsCode", req.getSmsCode());
mono =
loboClient.postForm(exchange, LoboPathConst.USER_LOGIN, data, UserConverter.toLoginRes);
}
if (StringUtils.isNotBlank(req.getInviteCode())) {
Map<String, Object> data = new HashMap<>();
data.put("inviteCode", req.getInviteCode());
data.put("key", "key");
mono =
mono.flatMap(
(result) -> {
if (ErrorCode.isSuccess(result.getCode())) {
log.info("登录成功,用户{}即将绑定邀请码: {}", result.getData().getId(), req.getInviteCode());
exchange
.getAttributes()
.put(CommonHeaderConst.USER_ID, result.getData().getId().toString());
exchange
.getAttributes()
.put(CommonHeaderConst.SESSION, result.getData().getSession());
return loboClient
.postForm(exchange, LoboPathConst.BIND_INVITE_CODE, data, null)
.map((r) -> result)
.onErrorResume((ex) -> Mono.just(result));
}
return Mono.just(result);
});
}
return mono.flatMap(
result -> {
LoginRes res = result.getData();
if (ErrorCode.isSuccess(result.getCode())) {
return userGreetService
.initGreetConfig(res.getId())
.then(
Mono.defer(
() -> userGreetService.addGreetUser(res.getId(), res.getIsRegister())))
.thenReturn(result);
}
return Mono.just(result);
});
}
@PostMapping(value = "/v1/cancel.do")
@ApiOperation(value = "用户注销")
public Mono<Result<Object>> cancel() {
return Mono.just(Result.success());
}
@PostMapping(value = "/v1/logout.do")
@ApiOperation(value = "用户退出登录")
public Mono<Result<LoginRes>> logout() {
return Mono.just(Result.success());
}
@GetMapping(value = "/v1/album.do")
@ApiOperation(value = "获取用户相册列表")
public Mono<Result<List<AlbumItemRes>>> getUserAlbum(@ApiIgnore ServerWebExchange exchange) {
Map<String, Object> data = new HashMap<>();
data.put("profileId", getUserId(exchange));
return loboClient.postFormForList(
exchange, LoboPathConst.USER_ALBUM, data, UserConverter.toAlbumItemRes);
}
@PostMapping(value = "/v1/album.do", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@ApiImplicitParams(
@ApiImplicitParam(
name = "img",
value = "图片",
paramType = "form",
dataType = "__file",
required = true))
@ApiOperation(value = "上传相册图片")
public Mono<Result<List<AlbumItemRes>>> uploadAlbumImg(
@Valid UploadAlbumReq req, @ApiIgnore ServerWebExchange exchange) {
Map<String, Object> data = new HashMap<>();
data.put("file", req.getImg());
return loboClient.postForm(
exchange,
LoboPathConst.UPLOAD_ALBUM_IMG,
data,
(obj) -> {
JSONObject result = (JSONObject) obj;
JSONArray albumItems = result.getJSONArray("album");
return albumItems.stream()
.map(
i -> {
JSONObject item = (JSONObject) i;
return new AlbumItemRes(
item.getString("url"),
AuditStatus.ofCode(item.getInteger("status")),
false);
})
.collect(Collectors.toList());
});
}
@DeleteMapping(value = "/v1/album.do")
@ApiOperation(value = "删除相册图片")
public Mono<Result<Object>> removeAlbumImg(
@ApiIgnore ServerWebExchange exchange, @Valid DeleteAlbumReq req) {
Map<String, Object> url = new HashMap<>();
url.put("url", req.getImgUrl());
url.put("status", req.getStatus().getCode());
String urls = JsonUtils.toJsonString(Collections.singletonList(url));
Map<String, Object> data = new HashMap<>();
data.put("urls", urls);
return loboClient.postForm(exchange, LoboPathConst.DELETE_ALBUM_IMG, data, null);
}
@PostMapping(value = "/v1/info.do", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@ApiImplicitParams(
@ApiImplicitParam(name = "portrait", value = "头像", paramType = "form", dataType = "__file"))
@ApiOperation(value = "编辑用户资料", notes = "只传值发生变化的字段,普通用户需要上传头像, 性别和生日不可重复修改,昵称和个人简介修改后需要进行审核")
public Mono<Result<Object>> modifyUserInfo(
@Valid UpdateUserReq req, @ApiIgnore ServerWebExchange exchange) {
if (req.getBirthday() != null) {
long year =
ChronoUnit.YEARS.between(DateUtil.toLocalDate(req.getBirthday()), LocalDate.now());
if (year < 18) {
return Mono.error(ErrorCode.AGE_LESS_THAN_LIMIT.newBusinessException());
}
}
Integer appVersion = getAppIntVersion(exchange);
List<Integer> loboErrorCodes = Collections.singletonList(1005);
if (req.getNickName() != null) {
return callUpdateUserInfo(
exchange, appVersion, 1, "nickName", req.getNickName(), loboErrorCodes)
.flatMap(
result -> {
boolean auditing = false;
if (LoboCode.isErrorCode(result.getCode())) {
return Mono.error(
new BusinessException(
result.getCode(), LoboCode.getErrorMessage(result.getCode())));
}
if (result.getCode() == ErrorCode.INNER_ERROR.getCode()) {
return Mono.error(ErrorCode.INNER_ERROR.newBusinessException());
}
if (result.getCode() == 1005) {
auditing = true;
}
List<Mono<Result<Object>>> monos =
getUpdateOtherInfoMonos(exchange, appVersion, req, loboErrorCodes);
if (monos.isEmpty() && auditing) {
return Mono.error(ErrorCode.USER_INFO_AUDITING.newBusinessException());
}
return modifyUserOtherInfo(auditing, monos);
});
}
return modifyUserOtherInfo(
false, getUpdateOtherInfoMonos(exchange, appVersion, req, loboErrorCodes));
}
@GetMapping(value = "/v1/portrait.do")
@ApiOperation(value = "获取用户头像")
public Mono<Result<AlbumItemRes>> getUserPortrait(@ApiIgnore ServerWebExchange exchange) {
return loboClient.get(
exchange,
LoboPathConst.GET_USER_PORTRAIT,
null,
(obj) -> {
JSONObject result = (JSONObject) obj;
return new AlbumItemRes(
result.getString("url"), AuditStatus.ofCode(result.getInteger("status")), true);
});
}
@PostMapping(value = "/v1/address.do", consumes = MediaType.APPLICATION_JSON_VALUE)
@ApiOperation(value = "上报用户位置")
public Mono<Result<Void>> uploadUserAddress(
@ApiIgnore ServerWebExchange exchange, @Valid @RequestBody UploadUserAddressReq req) {
Map<String, Object> data = new HashMap<>();
data.put("province", req.getProvince());
data.put("city", req.getCity());
data.put("latitude", req.getLatitude());
data.put("longitude", req.getLongitude());
data.put("key", getAppId());
return loboClient.postForm(exchange, LoboPathConst.UPLOAD_USER_ADDRESS, data, null);
}
@GetMapping(value = "/v1/search.net")
@ApiOperation(value = "搜索用户", notes = "可以搜索用户及主播")
public Mono<Result<PageRes<SearchUserItemRes>>> searchUser(
@ApiParam(value = "搜索关键字", required = true) @NotBlank @RequestParam String keyword,
@Valid PageReq pageReq,
@ApiIgnore ServerWebExchange exchange) {
return userRegInfoService
.findByShowId(getUserId(exchange), keyword)
.map(
u -> {
List<SearchUserItemRes> users =
Collections.singletonList(
new SearchUserItemRes(
u.getUserId(), LoboUtil.getImageUrl(u.getPortrait()), u.getNickName()));
PageRes<SearchUserItemRes> pageRes = PageRes.of(1, 1, 1, users);
return Result.success(pageRes);
})
.defaultIfEmpty(Result.success(PageRes.empty()));
}
private List<Mono<Result<Object>>> getUpdateOtherInfoMonos(
ServerWebExchange exchange,
Integer appVersion,
UpdateUserReq req,
List<Integer> loboErrorCodes) {
List<Mono<Result<Object>>> monos = new ArrayList<>();
if (req.getIntro() != null) {
monos.add(
callUpdateUserInfo(exchange, appVersion, 2, "intro", req.getIntro(), loboErrorCodes));
}
if (req.getGender() != null) {
monos.add(
callUpdateUserInfo(exchange, appVersion, 3, "sex", req.getGender().getCode(), null));
}
if (req.getBirthday() != null) {
monos.add(
callUpdateUserInfo(
exchange, appVersion, 4, "birthday", DateUtil.toLoboDate(req.getBirthday()), null));
}
if (req.getPortrait() != null) {
monos.add(callUploadUserPortrait(exchange, req.getPortrait()));
}
return monos;
}
private Mono<Result<Object>> modifyUserOtherInfo(
boolean nickNameAuditing, List<Mono<Result<Object>>> monos) {
if (!monos.isEmpty()) {
return Mono.zip(
monos,
(objs) -> {
boolean auditing = nickNameAuditing;
for (Object obj : objs) {
Result<Object> result = (Result<Object>) obj;
if (LoboCode.isErrorCode(result.getCode())) {
throw new BusinessException(
result.getCode(), LoboCode.getErrorMessage(result.getCode()));
}
if (result.getCode() == ErrorCode.INNER_ERROR.getCode()) {
throw ErrorCode.INNER_ERROR.newBusinessException();
}
if (!auditing && result.getCode() == 1005) {
auditing = true;
}
}
if (auditing) {
throw ErrorCode.USER_INFO_AUDITING.newBusinessException();
}
return new Object();
})
.map(Result::success)
.onErrorResume(
ex -> {
if (ex instanceof BusinessException) {
return Mono.just(
Result.error(((BusinessException) ex).getCode(), ex.getMessage()));
}
return Mono.just(
Result.error(
ErrorCode.INNER_ERROR.getCode(), ErrorCode.INNER_ERROR.getMessage()));
});
}
return Mono.just(Result.success());
}
private Mono<Result<Object>> callUpdateUserInfo(
ServerWebExchange exchange,
Integer appVersion,
int type,
String name,
Object value,
List<Integer> loboErrorCodes) {
Map<String, Object> data = new HashMap<>();
data.put(name, value);
data.put("type", type);
data.put("key", type); // key和type的值相同
data.put("appVersion", appVersion); // key和type的值相同
return loboClient.postForm(exchange, LoboPathConst.EDIT_USER_INFO, data, null, loboErrorCodes);
}
private Mono<Result<Object>> callUploadUserPortrait(
ServerWebExchange exchange, FilePart portrait) {
Map<String, Object> data = new HashMap<>();
data.put("file", portrait); // key和type的值相同
return loboClient.postForm(exchange, LoboPathConst.UPLOAD_USER_PORTRAIT, data, url -> url);
}
/**
* 如果是使用app store审核账号使用验证码登录, 替换为密码登录
*
* @param req {@link LoginReq}
*/
private void replaceToPasswordLoginForAudit(LoginReq req) {
DictionaryProperties.AppStoreAudit auditConfig = DictionaryProperties.get().getAppStoreAudit();
if (req.getType() == LoginType.PHONE_SMS_CODE
&& auditConfig.getPhones().contains(req.getPhoneNum())) {
log.info("使用应用审核手机号 {} 进行验证码登录,转换为密码登录", req.getPhoneNum());
req.setType(LoginType.PHONE_PASSWORD);
req.setPassword(auditConfig.getPassword());
}
}
}
| true |
aca24f47dc2b1f3b3fc6d23fd4068276ddbfc93a | Java | avemphract/fourth-homework-avemphract | /src/main/java/dev/patika/fourthhomeworkavemphract/exception/StudentNumberForOneCourseExceededException.java | UTF-8 | 479 | 2.921875 | 3 | [
"MIT"
] | permissive | package dev.patika.fourthhomeworkavemphract.exception;
import dev.patika.fourthhomeworkavemphract.model.Course;
import dev.patika.fourthhomeworkavemphract.model.Student;
public class StudentNumberForOneCourseExceededException extends RuntimeException{
public StudentNumberForOneCourseExceededException(Student student, Course course) {
super("Student number exceeded in course.\n Given student: "+student.toString()+"\nStudent course: "+course.toString());
}
}
| true |
b007c174dc1ac2bf54ef72189f9e21ecdf5beae3 | Java | hradynarski/dynamic-java-compiler | /src/test/java/com/raulgomis/djc/CompilationTest.java | UTF-8 | 1,135 | 2.46875 | 2 | [
"MIT"
] | permissive | package com.raulgomis.djc;
import com.raulgomis.djc.utils.CompilerExecutor;
import org.junit.Assert;
import org.junit.Test;
public class CompilationTest {
@Test
public void test01() {
CompilerExecutor compilerExecutor = new CompilerExecutor();
try {
Class<Runnable> clazz = compilerExecutor.compile("Test01.java");
final Runnable r;
try {
r = clazz.newInstance();
r.run();
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
Assert.assertNotNull(clazz);
} catch (DynamicCompilerException e) {
e.printStackTrace();
Assert.fail();
}
}
@Test
public void test02() {
CompilerExecutor compilerExecutor = new CompilerExecutor();
try {
compilerExecutor.compile("Test02.java");
Assert.fail();
} catch (DynamicCompilerException e) {
Assert.assertEquals("Error on line 3: ';' expected\n",
e.getDiagnosticsError());
}
}
}
| true |
81771e3019a5449c404f2299f46fe42ed8e16ecc | Java | doter/matrix | /matrix/src/main/java/com/matrix/sys/model/Test.java | UTF-8 | 252 | 1.609375 | 2 | [] | no_license | package com.matrix.sys.model;
import java.io.Serializable;
public class Test {
}
class M<PK extends Serializable>{
}
class M1 extends M<String>{
}
interface IS<T extends M,ID>{
}
class S<T extends M,ID> implements IS<T,ID>{}; | true |
933766676387070ad7196ba39aaaf04fa4234a83 | Java | kenza-bouzid/P2i-FlexiFile | /TestArduino-2018/JavaArduino/src/main/java/fr/insalyon/p2i2/javaarduino/Mesure.java | UTF-8 | 1,144 | 2.921875 | 3 | [] | no_license | package fr.insalyon.p2i2.javaarduino;
import java.sql.*;
/*
* 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.
*/
/**
*
* @author bouzi
*/
public class Mesure {
//attributs de la classe
private int idMesure;
private int idCapteur;
private Date dateMesure ;
private double valeur ;
//constructeur de la classe Mesure
public Mesure(int idM, int idC, Date d, double val){
idMesure = idM;
idCapteur = idC;
dateMesure = d;
valeur = val;
}
// ------ getters -------
public int getIdMesure (){
return idMesure;
}
public int getIdCapteur(){
return idCapteur;
}
public Date getDateMesure (){
return dateMesure;
}
public double getValeur (){
return valeur;
}
// ------ setters -------
public void setValeur(int v){
valeur = v;
}
}
| true |
cd1e39f1e1006dce5678a11111feb494f4da0b46 | Java | NaoumM/MorganStanley | /MorganStanleyTicTacToe/src/main/java/com/morganstanley/business/RoundRobin.java | UTF-8 | 585 | 2.84375 | 3 | [] | no_license | /*
* @author Ninus Khamis (MSc)
* @version 1.3
* @since 2015-06-30
*/
package com.morganstanley.business;
import java.util.List;
import java.util.Iterator;
import com.morganstanley.domain.user.IUser;
/**
* The following class implements a simple round robing iteration
* mechanism.
*/
public class RoundRobin {
private Iterator<IUser> it;
private List<IUser> list;
public RoundRobin(List<IUser> list) {
this.list = list;
it = list.iterator();
}
public IUser next() {
if (!it.hasNext())
it = list.iterator();
IUser user = it.next();
return user;
}
}
| true |
fe5924c8b68d5682556f34aaef3b3cff5f42edc4 | Java | NigelWu95/wechat | /src/main/java/com/wechat/central/AccessTokenProxy.java | UTF-8 | 2,653 | 2.4375 | 2 | [
"MIT"
] | permissive | /**
* Project Name: wechat
* File Name: AccessTokenProxy.java
* Package Name: wechat: com.wechat.central
* Copyright (c) 2017, wubingheng All Rights Reserved.
*/
package com.wechat.central;
import org.apache.commons.lang.StringUtils;
import com.wechat.exceptions.AccesssTokenException;
import com.wechat.exceptions.ConfigException;
import com.wechat.exceptions.HttpRequestException;
import com.wechat.service.IAccessTokenService;
/**
* ClassName: AccessTokenProxy Description: TODO Date Time: 2017年8月2日 上午9:30:15
*
* @author Nigel Wu wubinghengajw@outlook.com
* @version V1.0
* @since V1.0
* @jdk 1.7
* @see /**
* Get the valid access token by the access token server.
*
* @return String(access token string)
* @throws AccesssTokenException
* @throws ConfigException
* @throws HttpRequestException
/**
* Load the custom access token server by reflection.
*
* @return IAccessTokenService
* @throws ConfigException
*/
public class AccessTokenProxy {
private String appId;
private String appSecret;
private int requestTimes;
private String customerServerClass;
public AccessTokenProxy() throws ConfigException {
this.customerServerClass = Config.getInstance().getAccessTokenServer();
this.appId = Config.getInstance().getAppId();
this.appSecret = Config.getInstance().getAppSecret();
this.requestTimes = Integer.valueOf(Config.getInstance().getRequestTimes());
}
*/
public String getAccessToken() throws AccesssTokenException, ConfigException, HttpRequestException {
IAccessTokenService accessTokenServer = null;
/*
* If there is a custom server, using it to get access token. Else using default
* server.
*/
if (!StringUtils.isBlank(customerServerClass)) {
accessTokenServer = customerServer();
} else {
accessTokenServer = AccessTokenDefaultServer.getInstance();
}
return accessTokenServer.getAccessToken(appId, appSecret, requestTimes);
}
*/
private IAccessTokenService customerServer() throws ConfigException {
String className = customerServerClass;
IAccessTokenService customerServer = null;
try {
Class<?> clazz = Class.forName(className);
customerServer = (IAccessTokenService) clazz.newInstance();
} catch (Exception e) {
ConfigException configException = new ConfigException();
configException.setNoCustomServerError(e.getMessage());
throw configException;
}
return customerServer;
}
} | true |
a9c9360d3efc82055898855c6d493062e3d1f0b5 | Java | juzername/memory | /test/nhf/TableTest.java | ISO-8859-2 | 4,121 | 2.796875 | 3 | [] | no_license | package nhf;
import static org.junit.Assert.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
/**
* TableTest osztly a Table osztly metdusainak tesztelshez.
* @author Lenovo
*
*/
@RunWith(Parameterized.class)
public class TableTest {
Table table;
GameMode gamemode;
Habitat hab;
public TableTest(GameMode gamemode, Habitat hab) {
this.gamemode = gamemode;
this.hab = hab;
}
/**
* j tbla ltrehozsa
*/
@Before
public void setUp() {
table = new Table();
}
/**
* a Table osztly initCardsByGameMode metdusnak tesztelse. A krtyatpusokat vizsglja a jtkmdok alapjn.
*/
@Test
public void testInitCardsByGameMode() {
table.initCardsByGameMode(gamemode);
if(gamemode.equals(GameMode.MEMORYGAME)) {
for(int i = 0; i < table.getCardDeck().size(); i++)
assertEquals(CardType.MEMORYCARD, table.getCardDeck().get(i).getCardType());
}
else {
for(int i = 0; i < 6; i++)
assertEquals(CardType.IMAGECARD, table.getCardDeck().get(1).getCardType());
for(int i = 6; i < 12; i++)
assertEquals(CardType.TEXTCARD, table.getCardDeck().get(7).getCardType());
}
}
/**
* a Table osztly initCardsByHabitats() metdusnak tesztelse.
*/
@Test
public void testInintCardsByHabitats() {
table.initCardsByHabitats(hab);
for(int i = 0; i < table.getCardDeck().size(); i++) {
assertEquals(hab, table.getCardDeck().get(i).getHabitat());
}
}
/**
* a Table osztly initCards() metdusnak tesztelse.
*/
@Test
public void testInitCards() throws IOException {
table.initCardsByGameMode(gamemode);
table.initCardsByHabitats(hab);
BufferedImage bim = null;
if(gamemode.equals(GameMode.MEMORYGAME)) {
table.initCards(CardType.MEMORYCARD, CardType.MEMORYCARD, hab);
Card c8 = table.getCardDeck().get(8);
assertEquals(hab, c8.getHabitat());
assertEquals(2, c8.getId());
bim = new BufferedImage(178, 250, ImageIO.read(new File("MEMORYCARD"+"-"+hab.toString()+"-2.png")).getType());
assertEquals(bim.getWidth(), c8.getImage().getWidth());
assertEquals(bim.getHeight(), c8.getImage().getHeight());
Assert.assertArrayEquals(bim.getPropertyNames(), c8.getImage().getPropertyNames());
}
else {
table.initCards(CardType.IMAGECARD, CardType.TEXTCARD, hab);
Card c1 = table.getCardDeck().get(1);
assertEquals(CardType.IMAGECARD, c1.getCardType());
assertEquals(hab, c1.getHabitat());
assertEquals(1, c1.getId());
bim = new BufferedImage(178, 250, ImageIO.read(new File("IMAGECARD"+"-"+hab.toString()+"-1.png")).getType());
assertEquals(bim.getWidth(), c1.getImage().getWidth());
assertEquals(bim.getHeight(), c1.getImage().getHeight());
assertEquals(bim.getClass(), c1.getImage().getClass());
Card c8 = table.getCardDeck().get(8);
assertEquals(hab, c8.getHabitat());
assertEquals(2, c8.getId());
bim = new BufferedImage(178, 250, ImageIO.read(new File("TEXTCARD"+"-"+hab.toString()+"-2.png")).getType());
assertEquals(bim.getWidth(), c8.getImage().getWidth());
assertEquals(bim.getHeight(), c8.getImage().getHeight());
assertEquals(bim.getClass(), c8.getImage().getClass());
}
}
/**
* Paramterlista a tesztesetekhez.
* @return paramterlista
*/
@Parameters
public static List<Object[]> parameters(){
List<Object[]> params = new ArrayList<>();
params.add(new Object[] {GameMode.MEMORYGAME, Habitat.FARM});
params.add(new Object[] {GameMode.WORDCARDSGAME, Habitat.JUNGLE});
params.add(new Object[] {GameMode.MEMORYGAME, Habitat.PET});
params.add(new Object[] {GameMode.WORDCARDSGAME, Habitat.RIVER});
params.add(new Object[] {GameMode.MEMORYGAME, Habitat.SAFARI});
return params;
}
}
| true |
2aaa32c72ac3f50d481e78fb481a8beb09e966d3 | Java | xiezhirui/mjp | /src/test/java/com/cdhrtx/mjp/oop/interfaces/service/UserServiceTest.java | UTF-8 | 311 | 1.929688 | 2 | [] | no_license | package com.cdhrtx.mjp.oop.interfaces.service;
/**
* 用户服务接口测试用例
*
* @author xzr
*
*/
public class UserServiceTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("当前的网站名称是:" + UserService.WEB_SITE_NAME);
}
}
| true |
7c99f7108c6fe8ae55c0991eafb9432573dd9b97 | Java | ProjectsHTinc/HSTAndroid12 | /app/src/main/java/com/hst/osa_koodaiapp/adapter/NotificationListAdapter.java | UTF-8 | 3,437 | 2.21875 | 2 | [] | no_license | package com.hst.osa_koodaiapp.adapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.hst.osa_koodaiapp.R;
import com.hst.osa_koodaiapp.bean.support.ProductOffer;
import com.hst.osa_koodaiapp.utils.OSAValidator;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class NotificationListAdapter extends RecyclerView.Adapter<NotificationListAdapter.MyViewHolder> {
private ArrayList<ProductOffer> productOfferArrayList;
private OnItemClickListener onItemClickListener;
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private LinearLayout notificationLayout;
private ImageView offerImage;
private TextView productName;
private TextView productDescription;
private TextView productOffer;
public MyViewHolder(View itemView) {
super(itemView);
notificationLayout = (LinearLayout)itemView.findViewById(R.id.offerLayout);
notificationLayout.setOnClickListener(this);
offerImage = (ImageView)itemView.findViewById(R.id.offerImage);
productName = (TextView)itemView.findViewById(R.id.prd_name );
productDescription = (TextView)itemView.findViewById(R.id.prod_desc);
productOffer = (TextView)itemView.findViewById(R.id.offer);
}
@Override
public void onClick(View v) {
if (onItemClickListener != null) {
onItemClickListener.onItemClickNotification(v, getAdapterPosition());
}
// else {
// onItemClickListener.onItemClickAddress(Selecttick);
// }
}
}
public NotificationListAdapter(ArrayList<ProductOffer> productOfferArrayList, OnItemClickListener onItemClickListener) {
this.productOfferArrayList = productOfferArrayList;
this.onItemClickListener = onItemClickListener;
}
public interface OnItemClickListener {
public void onItemClickNotification(View view, int position);
}
@NonNull
@Override
public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_notification_items, parent, false);
return new MyViewHolder(itemView);
}
@Override
public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
ProductOffer productOffer = productOfferArrayList.get(position);
holder.productName.setText(productOffer.getProduct_name());
holder.productDescription.setText(productOffer.getProduct_description());
if (productOffer.getOffer_status().equalsIgnoreCase("0")) {
holder.productOffer.setVisibility(View.GONE);
} else {
holder.productOffer.setText(productOffer.getOffer_percentage() + " % Off");
}
if (OSAValidator.checkNullString(productOffer.getProduct_cover_img())){
Picasso.get().load(productOffer.getProduct_cover_img()).into(holder.offerImage);
}
}
@Override
public int getItemCount() {
return productOfferArrayList.size();
}
}
| true |
6b5632564e9630c529099037f1211f647913ff6c | Java | FarrowDShonne/Balance | /core/src/com/balance/balancegame/Handler/ContactHandler.java | UTF-8 | 608 | 2.359375 | 2 | [] | no_license | package com.balance.balancegame.Handler;
import com.balance.balancegame.Constants;
import com.badlogic.gdx.physics.box2d.Fixture;
/**
* Created by Registered User on 7/20/2016.
*/
public class ContactHandler {
//public final static short SCALE = 2, CLICKBOX = 4, GCIRCLE = 8, GBOX = 16;
public ContactHandler(){
}
public static void handleContacts(Fixture a, Fixture b){
if(a.getFilterData().categoryBits == Constants.SCALE && b.getFilterData().categoryBits != Constants.SCALE){
// System.out.println("You have hit the ground");
}
}
}
| true |
97b2e066c7b03a553696246676f8aba20c944a0e | Java | bioclipse/bioclipse.medea | /plugins/net.bioclipse.reaction/src/net/bioclipse/reaction/editparts/RDirectEditManager.java | UTF-8 | 1,645 | 2.03125 | 2 | [] | no_license | /*******************************************************************************
* Copyright (c) 2007-2009 Miguel Rojas <miguelrojasch@users.sf.net>,
* Stefan Kuhn <shk3@users.sf.net>
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* www.eclipse.org—epl-v10.html <http://www.eclipse.org/legal/epl-v10.html>
*
* Contact: http://www.bioclipse.net/
******************************************************************************/
package net.bioclipse.reaction.editparts;
import net.bioclipse.reaction.model.AbstractObjectModel;
import org.eclipse.gef.GraphicalEditPart;
import org.eclipse.gef.tools.CellEditorLocator;
import org.eclipse.gef.tools.DirectEditManager;
import org.eclipse.swt.widgets.Text;
/**
*
* @author Miguel Rojas
*/
public class RDirectEditManager extends DirectEditManager{
private AbstractObjectModel reactionModel;
/**
* Constructor of the MyDirectEditManager object
*
* @param source The GraphicalEditPart
* @param editorType The Class
* @param locator The CellEditorLocator
*/
public RDirectEditManager(GraphicalEditPart source, Class editorType, CellEditorLocator locator) {
super(source, editorType, locator);
reactionModel = (AbstractObjectModel)source.getModel();
}
/*
* (non-Javadoc)
* @see org.eclipse.gef.tools.DirectEditManager#initCellEditor()
*/
protected void initCellEditor() {
getCellEditor().setValue(reactionModel.getText());
Text text = (Text)getCellEditor().getControl();
text.selectAll();
}
}
| true |
89a9f412bd104e08915992851f5bc1688f4c7d41 | Java | MaryManzhos/TestRail | /src/test/java/models/Project.java | UTF-8 | 254 | 1.796875 | 2 | [] | no_license | package models;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
@Data
@AllArgsConstructor
@Builder
public class Project {
String nameOfProject;
String announcement;
boolean showAnnouncement;
String radio;
}
| true |
b9367fa1621c8620e230b7a9ceb2269780ccf9d1 | Java | mforsmar/Inda-Project | /Inda-Project/src/Water.java | UTF-8 | 167 | 2.3125 | 2 | [] | no_license | /**
* @author jenna
* @version 2015-05-12
*/
public class Water extends Beverage {
double alcohol = - 2.0;
public Water(){
super(alcohol);
}
}
| true |
391069dbaca02c20c00b034ac38f2af29b6bba1d | Java | gaurigshankar/RestWebServicePG | /src/main/java/com/gauri/rest/poc/data/Person.java | UTF-8 | 417 | 2.09375 | 2 | [] | no_license | package com.gauri.rest.poc.data;
public class Person {
private String customerType;
private AccountInfo[] accounts;
public String getCustomerType() {
return customerType;
}
public void setCustomerType(String customerType) {
this.customerType = customerType;
}
public AccountInfo[] getAccounts() {
return accounts;
}
public void setAccounts(AccountInfo[] accounts) {
this.accounts = accounts;
}
}
| true |
2059e17c5bc48ca496e00ffbb9b62c30ef68f8fb | Java | Azure/azure-sdk-for-java | /sdk/resourcemanagerhybrid/azure-resourcemanager-storage/src/main/java/com/azure/resourcemanager/storage/fluent/FileSharesClient.java | UTF-8 | 35,041 | 1.570313 | 2 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-2.1-or-later",
"CC0-1.0",
"BSD-3-Clause",
"UPL-1.0",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-generic-cla"
] | permissive | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.storage.fluent;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.http.rest.PagedFlux;
import com.azure.core.http.rest.PagedIterable;
import com.azure.core.http.rest.Response;
import com.azure.core.util.Context;
import com.azure.resourcemanager.storage.fluent.models.FileShareInner;
import com.azure.resourcemanager.storage.fluent.models.FileShareItemInner;
import com.azure.resourcemanager.storage.models.DeletedShare;
import com.azure.resourcemanager.storage.models.GetShareExpand;
import com.azure.resourcemanager.storage.models.ListSharesExpand;
import reactor.core.publisher.Mono;
/** An instance of this class provides access to all the operations defined in FileSharesClient. */
public interface FileSharesClient {
/**
* Lists all shares.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param maxpagesize Optional. Specified maximum number of shares that can be included in the list.
* @param filter Optional. When specified, only share names starting with the filter will be listed.
* @param expand Optional, used to expand the properties within share's properties.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return response schema.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedFlux<FileShareItemInner> listAsync(
String resourceGroupName, String accountName, String maxpagesize, String filter, ListSharesExpand expand);
/**
* Lists all shares.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return response schema.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedFlux<FileShareItemInner> listAsync(String resourceGroupName, String accountName);
/**
* Lists all shares.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return response schema.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<FileShareItemInner> list(String resourceGroupName, String accountName);
/**
* Lists all shares.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param maxpagesize Optional. Specified maximum number of shares that can be included in the list.
* @param filter Optional. When specified, only share names starting with the filter will be listed.
* @param expand Optional, used to expand the properties within share's properties.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return response schema.
*/
@ServiceMethod(returns = ReturnType.COLLECTION)
PagedIterable<FileShareItemInner> list(
String resourceGroupName,
String accountName,
String maxpagesize,
String filter,
ListSharesExpand expand,
Context context);
/**
* Creates a new share under the specified account as described by request body. The share resource includes
* metadata and properties for that share. It does not include a list of the files contained by the share.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param shareName The name of the file share within the specified storage account. File share names must be
* between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-)
* character must be immediately preceded and followed by a letter or number.
* @param fileShare Properties of the file share to create.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return properties of the file share, including Id, resource name, resource type, Etag.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<FileShareInner>> createWithResponseAsync(
String resourceGroupName, String accountName, String shareName, FileShareInner fileShare);
/**
* Creates a new share under the specified account as described by request body. The share resource includes
* metadata and properties for that share. It does not include a list of the files contained by the share.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param shareName The name of the file share within the specified storage account. File share names must be
* between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-)
* character must be immediately preceded and followed by a letter or number.
* @param fileShare Properties of the file share to create.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return properties of the file share, including Id, resource name, resource type, Etag.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<FileShareInner> createAsync(
String resourceGroupName, String accountName, String shareName, FileShareInner fileShare);
/**
* Creates a new share under the specified account as described by request body. The share resource includes
* metadata and properties for that share. It does not include a list of the files contained by the share.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param shareName The name of the file share within the specified storage account. File share names must be
* between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-)
* character must be immediately preceded and followed by a letter or number.
* @param fileShare Properties of the file share to create.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return properties of the file share, including Id, resource name, resource type, Etag.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
FileShareInner create(String resourceGroupName, String accountName, String shareName, FileShareInner fileShare);
/**
* Creates a new share under the specified account as described by request body. The share resource includes
* metadata and properties for that share. It does not include a list of the files contained by the share.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param shareName The name of the file share within the specified storage account. File share names must be
* between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-)
* character must be immediately preceded and followed by a letter or number.
* @param fileShare Properties of the file share to create.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return properties of the file share, including Id, resource name, resource type, Etag.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<FileShareInner> createWithResponse(
String resourceGroupName, String accountName, String shareName, FileShareInner fileShare, Context context);
/**
* Updates share properties as specified in request body. Properties not mentioned in the request will not be
* changed. Update fails if the specified share does not already exist.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param shareName The name of the file share within the specified storage account. File share names must be
* between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-)
* character must be immediately preceded and followed by a letter or number.
* @param fileShare Properties to update for the file share.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return properties of the file share, including Id, resource name, resource type, Etag.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<FileShareInner>> updateWithResponseAsync(
String resourceGroupName, String accountName, String shareName, FileShareInner fileShare);
/**
* Updates share properties as specified in request body. Properties not mentioned in the request will not be
* changed. Update fails if the specified share does not already exist.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param shareName The name of the file share within the specified storage account. File share names must be
* between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-)
* character must be immediately preceded and followed by a letter or number.
* @param fileShare Properties to update for the file share.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return properties of the file share, including Id, resource name, resource type, Etag.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<FileShareInner> updateAsync(
String resourceGroupName, String accountName, String shareName, FileShareInner fileShare);
/**
* Updates share properties as specified in request body. Properties not mentioned in the request will not be
* changed. Update fails if the specified share does not already exist.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param shareName The name of the file share within the specified storage account. File share names must be
* between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-)
* character must be immediately preceded and followed by a letter or number.
* @param fileShare Properties to update for the file share.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return properties of the file share, including Id, resource name, resource type, Etag.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
FileShareInner update(String resourceGroupName, String accountName, String shareName, FileShareInner fileShare);
/**
* Updates share properties as specified in request body. Properties not mentioned in the request will not be
* changed. Update fails if the specified share does not already exist.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param shareName The name of the file share within the specified storage account. File share names must be
* between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-)
* character must be immediately preceded and followed by a letter or number.
* @param fileShare Properties to update for the file share.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return properties of the file share, including Id, resource name, resource type, Etag.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<FileShareInner> updateWithResponse(
String resourceGroupName, String accountName, String shareName, FileShareInner fileShare, Context context);
/**
* Gets properties of a specified share.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param shareName The name of the file share within the specified storage account. File share names must be
* between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-)
* character must be immediately preceded and followed by a letter or number.
* @param expand Optional, used to expand the properties within share's properties.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return properties of a specified share.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<FileShareInner>> getWithResponseAsync(
String resourceGroupName, String accountName, String shareName, GetShareExpand expand);
/**
* Gets properties of a specified share.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param shareName The name of the file share within the specified storage account. File share names must be
* between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-)
* character must be immediately preceded and followed by a letter or number.
* @param expand Optional, used to expand the properties within share's properties.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return properties of a specified share.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<FileShareInner> getAsync(
String resourceGroupName, String accountName, String shareName, GetShareExpand expand);
/**
* Gets properties of a specified share.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param shareName The name of the file share within the specified storage account. File share names must be
* between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-)
* character must be immediately preceded and followed by a letter or number.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return properties of a specified share.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<FileShareInner> getAsync(String resourceGroupName, String accountName, String shareName);
/**
* Gets properties of a specified share.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param shareName The name of the file share within the specified storage account. File share names must be
* between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-)
* character must be immediately preceded and followed by a letter or number.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return properties of a specified share.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
FileShareInner get(String resourceGroupName, String accountName, String shareName);
/**
* Gets properties of a specified share.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param shareName The name of the file share within the specified storage account. File share names must be
* between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-)
* character must be immediately preceded and followed by a letter or number.
* @param expand Optional, used to expand the properties within share's properties.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return properties of a specified share.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<FileShareInner> getWithResponse(
String resourceGroupName, String accountName, String shareName, GetShareExpand expand, Context context);
/**
* Deletes specified share under its account.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param shareName The name of the file share within the specified storage account. File share names must be
* between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-)
* character must be immediately preceded and followed by a letter or number.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<Void>> deleteWithResponseAsync(String resourceGroupName, String accountName, String shareName);
/**
* Deletes specified share under its account.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param shareName The name of the file share within the specified storage account. File share names must be
* between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-)
* character must be immediately preceded and followed by a letter or number.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Void> deleteAsync(String resourceGroupName, String accountName, String shareName);
/**
* Deletes specified share under its account.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param shareName The name of the file share within the specified storage account. File share names must be
* between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-)
* character must be immediately preceded and followed by a letter or number.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
void delete(String resourceGroupName, String accountName, String shareName);
/**
* Deletes specified share under its account.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param shareName The name of the file share within the specified storage account. File share names must be
* between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-)
* character must be immediately preceded and followed by a letter or number.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the response.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<Void> deleteWithResponse(String resourceGroupName, String accountName, String shareName, Context context);
/**
* Restore a file share within a valid retention days if share soft delete is enabled.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param shareName The name of the file share within the specified storage account. File share names must be
* between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-)
* character must be immediately preceded and followed by a letter or number.
* @param deletedShare The deleted share to be restored.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Response<Void>> restoreWithResponseAsync(
String resourceGroupName, String accountName, String shareName, DeletedShare deletedShare);
/**
* Restore a file share within a valid retention days if share soft delete is enabled.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param shareName The name of the file share within the specified storage account. File share names must be
* between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-)
* character must be immediately preceded and followed by a letter or number.
* @param deletedShare The deleted share to be restored.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the completion.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Mono<Void> restoreAsync(String resourceGroupName, String accountName, String shareName, DeletedShare deletedShare);
/**
* Restore a file share within a valid retention days if share soft delete is enabled.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param shareName The name of the file share within the specified storage account. File share names must be
* between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-)
* character must be immediately preceded and followed by a letter or number.
* @param deletedShare The deleted share to be restored.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
void restore(String resourceGroupName, String accountName, String shareName, DeletedShare deletedShare);
/**
* Restore a file share within a valid retention days if share soft delete is enabled.
*
* @param resourceGroupName The name of the resource group within the user's subscription. The name is case
* insensitive.
* @param accountName The name of the storage account within the specified resource group. Storage account names
* must be between 3 and 24 characters in length and use numbers and lower-case letters only.
* @param shareName The name of the file share within the specified storage account. File share names must be
* between 3 and 63 characters in length and use numbers, lower-case letters and dash (-) only. Every dash (-)
* character must be immediately preceded and followed by a letter or number.
* @param deletedShare The deleted share to be restored.
* @param context The context to associate with this operation.
* @throws IllegalArgumentException thrown if parameters fail the validation.
* @throws com.azure.core.management.exception.ManagementException thrown if the request is rejected by server.
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent.
* @return the response.
*/
@ServiceMethod(returns = ReturnType.SINGLE)
Response<Void> restoreWithResponse(
String resourceGroupName, String accountName, String shareName, DeletedShare deletedShare, Context context);
}
| true |
51c75e35451ba84c850850e6cb40441586a66be5 | Java | ayar/camel-jdbc-dcn | /ayar-jpa-tool/src/main/java/com/ayar/tools/jpa/dcn/NotificationConsumer.java | UTF-8 | 1,355 | 2.21875 | 2 | [] | no_license | package com.ayar.tools.jpa.dcn;
import java.util.Observable;
import java.util.Observer;
import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.api.management.ManagedResource;
import org.apache.camel.impl.DefaultConsumer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@ManagedResource(description = "Managed DataBase Notification Consumer")
public class NotificationConsumer extends DefaultConsumer implements Observer {
private static Logger LOG = LoggerFactory
.getLogger(NotificationConsumer.class);
public NotificationConsumer(final NotificationEndpoint endpoint,
final Processor processor) {
super(endpoint, processor);
// TODO Auto-generated constructor stub
}
@Override
public NotificationEndpoint getEndpoint() {
return (NotificationEndpoint) super.getEndpoint();
}
@Override
public void start() throws Exception {
getEndpoint().connect(this);
super.start();
}
@Override
public void stop() throws Exception {
getEndpoint().disconnect(this);
super.stop();
}
@Override
public void update(Observable o, Object event) {
final Exchange exchange = getEndpoint().createExchange();
exchange.getIn().setBody(event, event.getClass());
try {
getProcessor().process(exchange);
} catch (final Exception e) {
LOG.warn("Cannot process exchange", e);
}
}
} | true |
fd9e3c1c110016faad842e75c29f8513efc51c72 | Java | sanakhanbano/ABP-Backend | /src/main/java/com/mazars/in/serviceimpl/EventMasterServiceImpl.java | UTF-8 | 1,148 | 1.976563 | 2 | [] | no_license | package com.mazars.in.serviceimpl;
import java.util.List;
import javax.transaction.Transactional;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.mazars.in.dao.EventMasterDaoRepository;
import com.mazars.in.model.mastermodel.EventMaster;
import com.mazars.in.service.EventMasterService;
@Service
@Transactional
public class EventMasterServiceImpl implements EventMasterService{
private static final Logger logger = LogManager.getLogger(CostCenterServiceImpl.class);
@Autowired
private EventMasterDaoRepository eventMasterDAO;
@Override
public void save(EventMaster eventMaster) {
// TODO Auto-generated method stub
}
@Override
public void update(EventMaster eventMaster) {
// TODO Auto-generated method stub
}
@Override
public List<EventMaster> eventMasterList() {
List<EventMaster> eventMasterList=eventMasterDAO.findAll();
return eventMasterList;
}
@Override
public void delete(EventMaster eventMaster) {
// TODO Auto-generated method stub
}
}
| true |
d3da8b96f273c56180776f1095c273192a24a7ff | Java | rfenters95/roomba-learning-tool | /src/main/java/core/sensor/bool/LightBumperFrontLeft.java | UTF-8 | 256 | 1.953125 | 2 | [] | no_license | package core.sensor.bool;
import controllers.ModuleController;
public class LightBumperFrontLeft extends BooleanSensor {
@Override
public String read() {
return String.valueOf(ModuleController.getRoomba().lightBumperFrontLeft());
}
}
| true |
5df708b519de4e2ab135352bceb167c30295a73e | Java | assecopl/fh | /fh-compiler/src/main/java/pl/fhframework/compiler/core/generator/AbstractNgTemplateCodeGenerator.java | UTF-8 | 1,637 | 1.921875 | 2 | [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] | permissive | package pl.fhframework.compiler.core.generator;
import lombok.Getter;
import pl.fhframework.core.generator.GenerationContext;
public abstract class AbstractNgTemplateCodeGenerator extends AbstractTypescriptCodeGenerator {
protected static final String START_TAG_TEMPLATE = "<%s";
protected static final String ATTRIBUTE_AND_VALUE_TEMPLATE = "%s=\"%s\"";
protected static final String ATTRIBUTE_AND_INTERPOLATION_TEMPLATE = "%s=\"{{%s}}\"";
protected static final String ONE_WAY_BINDING_TEMPLATE = "[%s]=\"%s\"";
protected static final String TWO_WAY_BINDING_TEMPLATE = "[(%s)]=\"%s\"";
protected static final String ACTION_AND_VALUE_TEMPLATE = "(%s)=\"%s\"";
protected static final String END_TAG_TEMPLATE_COMPLETE = "</%s>";
protected static final String EMPTY_ACTION_CONSTANT = "-";
protected static final String FORM_GROUP_CONSTANT = "[formGroup]=\"form\"";
protected static final String TAG_ENDING = ">";
protected static final String UNKNOWN_COMPONENT_WARNING_MESSAGE = "Tag for control {%s} not found. Control ommitted for typescript form template generation.";
public AbstractNgTemplateCodeGenerator(ModuleMetaModel moduleMetaModel, MetaModelService metaModelService) {
super(moduleMetaModel, metaModelService);
}
@Getter
protected GenerationContext contentsSection = new GenerationContext();
protected GenerationContext generateContext() {
generateContents();
return contentsSection;
}
public String generateTemplate() {
return generateContext().resolveCode();
}
protected abstract void generateContents();
}
| true |
8777dc30a8e577e0105327f3a6c95e1e070b5aca | Java | mobikan/KS | /app/src/main/java/com/solitary/ksapp/model/Like.java | UTF-8 | 2,109 | 2.546875 | 3 | [] | no_license | package com.solitary.ksapp.model;
import android.os.Parcel;
import android.os.Parcelable;
public class Like implements Parcelable {
public String id;
public long no_of_like;
public float rating;
public RatingData rating_data;
public RatingData getRating_data ()
{
return rating_data;
}
public void setRating_data (RatingData rating_data)
{
this.rating_data = rating_data;
}
public Like()
{
}
public Like(String id,long no_of_like,float rating)
{
this.id = id;
this.no_of_like = no_of_like;
this.rating = rating;
}
public String getId ()
{
return id;
}
public void setId (String id)
{
this.id = id;
}
public long getNo_of_like ()
{
return no_of_like;
}
public void setNo_of_like (long no_of_like)
{
this.no_of_like = no_of_like;
}
public float getRating ()
{
return rating;
}
public void setRating (float rating)
{
this.rating = rating;
}
@Override
public String toString()
{
return "ClassPojo [id = "+id+", no_of_like = "+no_of_like+", rating = "+rating+"]";
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.id);
dest.writeLong(this.no_of_like);
dest.writeFloat(this.rating);
dest.writeParcelable(this.rating_data, flags);
}
protected Like(Parcel in) {
this.id = in.readString();
this.no_of_like = in.readLong();
this.rating = in.readFloat();
this.rating_data = in.readParcelable(RatingData.class.getClassLoader());
}
public static final Parcelable.Creator<Like> CREATOR = new Parcelable.Creator<Like>() {
@Override
public Like createFromParcel(Parcel source) {
return new Like(source);
}
@Override
public Like[] newArray(int size) {
return new Like[size];
}
};
}
| true |
642c6e25123b53fe0d8243eae8f4ac60b2f360a2 | Java | mrlzy/reactjs | /src/main/java/com/mrlzy/shiro/web/mvc/demo/DemoController.java | UTF-8 | 559 | 1.726563 | 2 | [] | no_license | package com.mrlzy.shiro.web.mvc.demo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
@Controller
@RequestMapping("/demo")
public class DemoController {
@RequestMapping("/menu")
public String menu() {
return "demo/menu";
}
@RequestMapping("/role")
public String role() {
return "demo/role";
}
@RequestMapping("/menuPerm")
public String menuPerm() {
return "demo/menuPerm";
}
}
| true |
39c75e15bd6bc47a0073d6bbec38024af067d8dc | Java | jonnybl915/MessageApp | /src/com/theironyard/jdblack/Main.java | UTF-8 | 6,587 | 2.609375 | 3 | [] | no_license | package com.theironyard.jdblack;
import jodd.json.JsonParser;
import jodd.json.JsonSerializer;
import spark.ModelAndView;
import spark.Session;
import spark.Spark;
import spark.template.mustache.MustacheTemplateEngine;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Scanner;
public class Main {
static HashMap<String, User> userMap = new HashMap<>();
public static void main(String[] args) throws IOException {
Spark.staticFileLocation("/public");
HashMap<String, User> tempMap = readFileJson();
Spark.init();
Spark.get(
"/",
(request, response) -> {
Session session = request.session();
String username = session.attribute("username"); //requesting the session value
HashMap map = new HashMap();
if (username == null) {
return new ModelAndView(map, "index.html"); } //this gets it to compile
else {
User user = userMap.get(username);
int id = 1;
for (Message msg : user.messages)
msg.id = id;
id++;
map.put("messages", user.messages);
map.put("name", username);
writeFileJson();
return new ModelAndView(map, "messages.html");
}
},
new MustacheTemplateEngine() //so it knows how to parse the template. normally only on a get route
);
Spark.post(
"/create-user",
(request, response) -> {
String username = request.queryParams("username"); //"username" corresponds to the form in index.html
String password = request.queryParams("password"); //'password' " "
User user = userMap.get(username); //if they are not in the map then username will be null thus making user null
if(user == null){ //--which is ok bc we are checking for that here
user = new User(username, password);
userMap.put(username, user);
}
if(!password.equals(user.password)) {
throw new Exception("Incorrect Password");
}
Session session = request.session();
session.attribute("username", username); //as with a HashMap this is putting a key value pair into the session
writeFileJson();
response.redirect("/");
return "";
}
);
Spark.post(
"create-message",
(request, response) -> {
Session session = request.session(); //1. get session
String username = session.attribute("username"); //2. get username
User user = userMap.get(username); //3. get user object out of the HashMap
String message = request.queryParams("message");
user.messages.add(new Message(message));
writeFileJson();
response.redirect("/");
return "";
}
);
Spark.post(
"/logout",
(request, response) -> {
Session session = request.session();
session.invalidate();
writeFileJson();
response.redirect("/");
return "";
}
);
Spark.post(
"/delete-message",
(request, response) -> {
Session session = request.session();
String username = session.attribute("username");
User user = userMap.get(username);
if (username == null){
throw new Exception("Not logged in");
}
int id = Integer.valueOf(request.queryParams("id"));
if (id < 0 || id - 1 >= user.messages.size()){
throw new Exception("Invalid id");
}
user.messages.remove(id-1);
writeFileJson();
response.redirect("/");
return "";
// int i = 1;
// Message m = user.messages.get(i ++);
// user.messages.remove(m);
// response.redirect("/");
// return "";
}
);
Spark.post(
"/edit-message",
(request, response) -> {
Session session = request.session();
String username = session.attribute("username");
String editText = request.queryParams("newMessage");
User user = userMap.get(username);
if (username == null){
throw new Exception("Not logged in");
}
int id = Integer.valueOf(request.queryParams("id"));
if (id < 0 || id - 1 >= user.messages.size()){
throw new Exception("Invalid id");
}
user.messages.set(id-1, new Message(editText));
writeFileJson();
response.redirect("/");
return "";
}
);
}
public static void writeFileJson() throws IOException {
File f = new File("MessageList.json");
JsonSerializer serializer = new JsonSerializer();
String json = serializer.include("*").serialize(userMap);
FileWriter fw = new FileWriter(f);
fw.write(json);
fw.close();
}
public static HashMap<String, User> readFileJson() throws FileNotFoundException {
File f = new File("MessageList.json");
Scanner scanner = new Scanner(f);
scanner.useDelimiter("\\Z");
String contents = scanner.next();
JsonParser parser = new JsonParser();
HashMap<String, User> tempMap = parser.parse(contents, HashMap.class);
return tempMap;
}
}
| true |
63c88c562d5e7f60faeb08c9017ddb6160f1ffe3 | Java | NothingbutPro/kota29feb | /app/src/main/java/com/ics/admin/Adapter/MainMenuAdapter.java | UTF-8 | 19,149 | 1.828125 | 2 | [] | no_license | package com.ics.admin.Adapter;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.StrictMode;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import android.widget.Toolbar;
import com.ics.admin.Model.MenuPermisssion;
import com.ics.admin.Model.SubMenuPermissions;
import com.ics.admin.R;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
public class MainMenuAdapter extends RecyclerView.Adapter<MainMenuAdapter.MyViewHolder> {
public static ArrayList<String> Myproducttiles = new ArrayList<>();
public List<MenuPermisssion> menuPermisssionList;
public List<SubMenuPermissions> subMenuPermisssionsList = new ArrayList<>();
SubPermissionAdapter subPermissionAdapter;
int pos_try;
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
private Context mContext;
private MenuPermisssion menuPermisssion;
ProgressDialog progressDialog;
private RecyclerView subrec;
TextView okdismisstxt;
public MainMenuAdapter(Context context, List<MenuPermisssion> menuPermisssion) {
mContext = context;
this.menuPermisssionList = menuPermisssion;
progressDialog = new ProgressDialog(mContext);
setHasStableIds(true);
}
@Override
public MainMenuAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.menuinfogroup, parent, false);
return new MyViewHolder(view);
}
@Override
public void onBindViewHolder(final MainMenuAdapter.MyViewHolder holder, final int position) {
menuPermisssion = menuPermisssionList.get(position);
this.pos_try = position;
if(position==0)
{
holder.permissiontool.setVisibility(View.VISIBLE);
}else {
holder.permissiontool.setVisibility(View.GONE);
}
holder.namestff.setText(menuPermisssionList.get(position).getMenu_name());
// holder.namestff.setText("jhsgdjsydg");
// holder.emailstff.setText(menuPermisssion.getEmail());
// holder.stffid.setText(menuPermisssion.getDesignation());
// Glide.with(mContext).load("http://neareststore.in/uploads/staff/" + addNews141.getImage()).addListener(new RequestListener<Drawable>() {
// @Override
// public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
// Toast.makeText(mContext, "Failed to load image", Toast.LENGTH_SHORT).show();
// return false;
// }
//
// @Override
// public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
// Toast.makeText(mContext, "Image laod success", Toast.LENGTH_SHORT).show();
// return false;
// }
// }).into(holder.stffimg);
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// subMenuPermisssionsList.clear();
Dialog dialog = new Dialog(v.getContext());
dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.facultypermissiondialog);
// AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
// AlertDialog alertDialog = builder.create();
// LayoutInflater li = (LayoutInflater) v.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// LayoutInflater inflater = getLayoutInflater();
// View dialogLayout = li.inflate(R.layout.facultypermissiondialog, null);
TextView roles = dialog.findViewById(R.id.roles);
ToggleButton dialogtoggel = dialog.findViewById(R.id.dialogtoggel);
subrec = dialog.findViewById(R.id.subrec);
okdismisstxt = dialog.findViewById(R.id.okdismisstxt);
roles.setText(menuPermisssionList.get(position).getMenu_name());
// roles.setText(menuPermisssionList.get(position).getMenu_name());
if(!menuPermisssionList.get(position).getStatus().equals("null"))
{
subMenuPermisssionsList.clear();
// menuPermisssionList.clear();
dialogtoggel.setChecked(true);
subrec.setVisibility(View.VISIBLE);
new GETAllSubMEnues(menuPermisssionList.get(position).getStatus(), menuPermisssionList.get(position).getMenu_name() ,menuPermisssionList.get(position).getMenu_id(),2).execute();
}else {
subMenuPermisssionsList.clear();
Toast.makeText(mContext, "Nothing has assigned here", Toast.LENGTH_SHORT).show();
}
dialogtoggel.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked)
{
// if( subMenuPermisssionsList.size() !=0) {
subMenuPermisssionsList.clear();
subrec.setAdapter(null);
subrec.setVisibility(View.VISIBLE);
new POSt_AppPErmissions("2", menuPermisssionList.get(position).getMenu_id(), "1", position).execute();
// subPermissionAdapter.notifyDataSetChanged();
// }
}else {
// subPermissionAdapter.notifyDataSetChanged();
// if(subMenuPermisssionsList.size() !=0) {
subMenuPermisssionsList.clear();
subrec.setAdapter(null);
subrec.setVisibility(View.GONE);
new POSt_AppPErmissions("2", menuPermisssionList.get(position).getMenu_id(), "NI KRna", position).execute();
// subPermissionAdapter.notifyDataSetChanged();
// }
}
}
});
// rolesexpand.setonc
okdismisstxt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
});
// searching_manufacturers_data = menuPermisssionList.get(pos_try);
// Log.e("Position","is "+pos_try);
// document = searching_manufacturers_data.getBrandName();
StrictMode.setVmPolicy(builder.build());
}
@Override
public int getItemCount() {
return menuPermisssionList.size();
}
@Override
public long getItemId(int position) {
// return super.getItemId(position);
return position;
}
public class MyViewHolder extends RecyclerView.ViewHolder {
ImageView stffimg;
TextView namestff, emailstff, stffid;
ToggleButton maintoggel;
androidx.appcompat.widget.Toolbar permissiontool;
public MyViewHolder(View itemView) {
super(itemView);
// mname = (TextView) itemView.findViewById(R.id.mname);
// manu_img = itemView.findViewById(R.id.manu_img);
namestff = itemView.findViewById(R.id.lblListHeader);
maintoggel = itemView.findViewById(R.id.maintoggel);
permissiontool = itemView.findViewById(R.id.permissiontool);
// adddes = itemView.findViewById(R.id.adddes);
}
}
private class GETAllSubMEnues extends AsyncTask<String, Void, String> {
String menu_id;
int user_id;
String menu_name;
String mainstatus;
int position;
public GETAllSubMEnues(String status, String menu_name, String menu_id, int user_id) {
this.menu_id = menu_id;
this.menu_name = menu_name;
this.user_id = user_id;
this.mainstatus = status;
}
@Override
protected String doInBackground(String... arg0) {
try {
URL url = new URL("http://ihisaab.in/school_lms/Adminapi/getsubmenulist");
JSONObject postDataParams = new JSONObject();
postDataParams.put("user_id", user_id);
postDataParams.put("menu_id", menu_id);
postDataParams.put("teacher_id", ((Activity) mContext).getIntent().getStringExtra("teacher_id"));
Log.e("postDataParams", postDataParams.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /*milliseconds*/);
conn.setConnectTimeout(15000 /*milliseconds*/);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new
InputStreamReader(
conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
StringBuffer Ss = sb.append(line);
Log.e("Ss", Ss.toString());
sb.append(line);
break;
}
in.close();
return sb.toString();
} else {
return new String("false : " + responseCode);
}
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
@Override
protected void onPostExecute(String result) {
if (result != null) {
// dialog.dismiss();
JSONObject jsonObject = null;
Log.e("PostRegistration", result.toString());
try {
jsonObject = new JSONObject(result);
if (!jsonObject.getBoolean("responce")) {
// getotp.setVisibility(View.VISIBLE);
// Intent
} else {
int i = 0;
for (; i < jsonObject.getJSONArray("data").length(); i++) {
JSONObject jsonObject1 = jsonObject.getJSONArray("data").getJSONObject(i);
String permission_id = jsonObject1.getString("permission_id");
String submenu = jsonObject1.getString("submenu");
String status = jsonObject1.getString("status");
String sub_id = jsonObject1.getString("sub_id");
// String menu_name = jsonObject1.getString("menu_name");
Log.e("submenu name",""+submenu);
subMenuPermisssionsList.add(new SubMenuPermissions(permission_id,submenu ,status,mainstatus,sub_id));
// menuPermissionsSubList.add(position , new SubMenuPermissions(permission_id, submenu));
}
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext );
linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
subrec.setLayoutManager(linearLayoutManager);
subPermissionAdapter = new SubPermissionAdapter(mContext,subMenuPermisssionsList);
subrec.setAdapter(subPermissionAdapter);
subPermissionAdapter.notifyDataSetChanged();
//
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public String getPostDataString(JSONObject params) throws Exception {
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<String> itr = params.keys();
while (itr.hasNext()) {
String key = itr.next();
Object value = params.get(key);
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));
}
return result.toString();
}
}
private class POSt_AppPErmissions extends AsyncTask<String, Void, String> {
String menu_id;
String user_id;
String menu_name;
int position;
String status;
public POSt_AppPErmissions(String user_id, String menu_id, String status, int position) {
this.user_id = user_id;
this.menu_id = menu_id;
this.status = status;
this.position = position;
}
@Override
protected void onPreExecute() {
progressDialog.show();
progressDialog.setCancelable(false);
progressDialog.setTitle("Please wait");
super.onPreExecute();
}
@Override
protected String doInBackground(String... arg0) {
try {
URL url = new URL("http://ihisaab.in/school_lms/Adminapi/add_menupermission");
JSONObject postDataParams = new JSONObject();
postDataParams.put("user_id", ((Activity)mContext).getIntent().getStringExtra("teacher_id"));
postDataParams.put("menu_id", menu_id);
postDataParams.put("status", status);
Log.e("postDataParams", postDataParams.toString());
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /*milliseconds*/);
conn.setConnectTimeout(15000 /*milliseconds*/);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(postDataParams));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new
InputStreamReader(
conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line = "";
while ((line = in.readLine()) != null) {
StringBuffer Ss = sb.append(line);
Log.e("Ss", Ss.toString());
sb.append(line);
break;
}
in.close();
return sb.toString();
} else {
return new String("false : " + responseCode);
}
} catch (Exception e) {
return new String("Exception: " + e.getMessage());
}
}
@Override
protected void onPostExecute(String result) {
if (result != null) {
// dialog.dismiss();
JSONObject jsonObject = null;
Log.e("PostRegistration", result.toString());
try {
jsonObject = new JSONObject(result);
if (!jsonObject.getBoolean("responce")) {
// getotp.setVisibility(View.VISIBLE);
// Intent
} else {
subrec.setVisibility(View.VISIBLE);
menuPermisssionList.get(position).setStatus("xyz");
subMenuPermisssionsList.clear();
progressDialog.dismiss();
new GETAllSubMEnues(menuPermisssionList.get(this.position).getStatus(), menuPermisssionList.get(this.position).getMenu_name() ,menuPermisssionList.get(this.position).getMenu_id(),2).execute();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
public String getPostDataString(JSONObject params) throws Exception {
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<String> itr = params.keys();
while (itr.hasNext()) {
String key = itr.next();
Object value = params.get(key);
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));
}
return result.toString();
}
}
}
| true |
54685cc371c705a318bd6aefb397d861ed88a3d7 | Java | PraveenRavipati/store | /src/com/praveen/rest/Store.java | UTF-8 | 438 | 2.140625 | 2 | [] | no_license | package com.praveen.rest;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;
import som.praveen.db.StoreDBClient;
@Path("/store")
public class Store {
@GET
@Path("/healthCheck")
public String getMsg() {
return "store is up and running.....";
}
@GET
public String getItem(@QueryParam("item") String item) {
String s = new StoreDBClient().getItem(item);
return s;
}
}
| true |
bc04917f52dad915ccdf7b89fca8c4690909b3c3 | Java | TuanNguyenCPT/quanLySinhVien | /C2/src/B8/Manage.java | UTF-8 | 7,148 | 3.1875 | 3 | [] | no_license | package B8;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
/**
* Lớp thực thi các thao tác quản lý sinh viên
*
* @author tuann
*/
public class Manage {
public static void main(String[] args) {
List<Course> courseList = new ArrayList<>();
List<Student> studentList = new ArrayList<>();
List<Subject> subjectList = new ArrayList<>();
var input = new Scanner(System.in);
int choose;
do {
System.out.println("======================MENU======================");
System.out.println("Chọn chức năng bạn muốn: ");
System.out.println("1. Thêm mới môn học vào danh sách môn học");
System.out.println("2. Thêm mới sinh viên vào danh sách sinh viên");
System.out.println("3. Thêm mới lớp học vào danh sách lớp học");
System.out.println("4. Hiển thị danh sách môn học");
System.out.println("5. Hiển thị danh sách sinh viên");
System.out.println("6. Hiển thị danh sách lớp học theo mã lớp");
System.out.println("7. Tính điểm trung bình cho từng sinh viên trong lớp");
System.out.println("8. Xét học lực cho từng sinh viên trong danh sách");
System.out.println("9. Tìm sinh viên theo mã số sinh viên");
System.out.println("0. Thoát chương trình");
choose = input.nextInt();
input.nextLine(); // loại bỏ kí tự enter thừa
switch (choose) {
case 0: //
System.out.println("Cảm ơn bạn đã sử dụng chương trình");
break;
case 1:
var subject = createNewSubject(input);
subjectList.add(subject);
System.out.println(" Thêm môn học thành công ");
break;
case 2:
var student = createNewStudent(input);
studentList.add(student);
System.out.println("Đã thêm sinh viên mới thành công");
break;
case 3:
if (subjectList.size()>0) {
var course = createNewCourse(subjectList, input);
if(course!=null){
courseList.add(course);
System.out.println("Thêm khóa học thành công");
}
else
System.out.println("Thêm khóa học thất bại");
}
else {
System.out.println("Danh sách môn học trống");
}
break;
case 4:
break;
case 5:
showSubjectList(subjectList);
break;
case 6:
break;
case 7:
break;
case 8:
break;
case 9:
break;
case 10:
break;
default:
System.out.println("Chọn sai, vui lòng chọn lại");
break;
}
} while (choose != 0);
}
private static void showSubjectList(List<Subject> subjectList) {
}
/**
* Hàm tạo một lớp học mới từ danh sách môn học có sẵn, bảng điểm tạo sau
* @param subjectList danh sách các môn học
* @param input Scanner
* @return khóa học mới nếu thành công, null nếu không thành công
*/
private static Course createNewCourse(List<Subject> subjectList, Scanner input) {
// id = "";
// name = "";
// room = "";
// time = 0;
// subject = null;
// transcriptOfStudents = new ArrayList<>();
System.out.println("Mã khóa học: ");
var id = input.nextLine();
System.out.println("Tên khóa học: ");
var name = input.nextLine();
System.out.println("Phòng học: ");
var room = input.nextLine();
System.out.println("Thời gian học: ");
var time = input.nextFloat();
input.nextLine();
System.out.println("Mã môn học: ");
var subjectId = input.nextLine();
var subject = searchSubjectById(subjectList, subjectId);
if (subject == null){
System.out.println("Không tồn tại môn học có ID là: "+subjectId);
return null;
}
else {
Course course = new Course(id, name,room,time,subject);
return course;
}
}
/**
* Hàm tìm kiếm môn học theo ID
* @param subjectList danh sách các môn học
* @param subjectId id của môn học muốn tìm
* @return môn học muốn tìm hoặc null nếu không tìm thấy
*/
private static Subject searchSubjectById(List<Subject> subjectList, String subjectId) {
for (var subject : subjectList) {
if (subject.getId().compareTo(subjectId) == 0){
return subject;
}
}
return null;
}
/**
* Hàm tạo thêm một sinh viên mới
* @param input Scanner
* @return Sinh viên mới tạo
*/
private static Student createNewStudent(Scanner input) {
System.out.println("Nhập mã số sinh viên");
var id = input.nextLine();
System.out.println("Tên đầy đủ sinh viên: ");
var fullName = input.nextLine();
System.out.println("Địa chỉ sinh viên: ");
var address = input.nextLine();
System.out.println("Email: ");
var email = input.nextLine();
System.out.println("phone: ");
var phone = input.nextLine();
System.out.println("sex: ");
var sex = input.nextLine();
System.out.println("lớp: ");
var className = input.nextLine();
System.out.println("Khoa: ");
var major = input.nextLine();
Student student = new Student(id, fullName, address, email, phone, sex, className, major);
return student;
}
/**
* Hàm thêm 1 môn học
* @param input Scanner
* @return môn học mới
*/
private static Subject createNewSubject(Scanner input) {
System.out.println("Nhập mã môn học");
var id = input.nextLine();
System.out.println("Nhập tên môn học");
var name = input.nextLine();
System.out.println("Nhập số tín chỉ");
var credit = input.nextFloat();
System.out.println("Nhập số tiết học");
var numOfLesson = input.nextFloat();
System.out.println("Nhập số bài kiểm tra");
var numOfExam = input.nextInt();
Subject subject = new Subject(id, name, credit, numOfLesson, numOfExam);
return subject;
}
}
| true |
ba27341eabcf34b5ffdaaa3d6a3afafe425647a3 | Java | maobon/OKHttp-Android-Demo | /app/src/main/java/com/demo/okhttp/RequestTask.java | UTF-8 | 1,041 | 2.578125 | 3 | [] | no_license | package com.demo.okhttp;
import java.util.Map;
import java.util.Set;
public class RequestTask implements Runnable {
private String targetUrl;
private Map<String, String> params;
public RequestTask(String targetUrl, Map<String, String> params) {
this.targetUrl = targetUrl;
this.params = params;
}
@Override
public void run() {
StringBuilder sb = new StringBuilder();
Set<Map.Entry<String, String>> entries = params.entrySet();
int pos = 0;
for (Map.Entry<String, String> entry : entries) {
String key = entry.getKey();
String value = entry.getValue();
if (pos == 0) {
sb.append("?");
} else {
sb.append("&");
}
sb.append(String.format("%s=%s", key, value));
pos++;
}
try {
String s = HttpsUtil.doTlsPost(targetUrl, sb.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
| true |
7e682c5dfe69b28b64fc15a575bf361366038a43 | Java | jacklotusho/stormpath-spring-samples | /tooter/src/main/java/com/stormpath/tooter/model/dao/DefaultCustomerDao.java | UTF-8 | 2,077 | 2.1875 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2012 Stormpath, Inc. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.stormpath.tooter.model.dao;
import com.stormpath.tooter.model.User;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
/**
* @author Elder Crisostomo
*/
@Repository
public class DefaultCustomerDao extends BaseHibernateDao implements CustomerDao {
@Override
public User getCustomerByUserName(String userName) throws Exception {
Criteria criteria = getSession().createCriteria(User.class);
criteria.add(Restrictions.eq("userName", userName));
List<?> list = new ArrayList<Object>();
list.addAll(criteria.list());
User customer = null;
if (!list.isEmpty()) {
for (Object obj : list) {
if (obj != null) {
customer = (User) obj;
break;
}
}
}
return customer;
}
@Override
public User saveCustomer(User customer) throws Exception {
save(customer);
return customer;
}
@Override
public User updateCustomer(User customer) throws Exception {
update(customer);
return customer;
}
@Autowired
public void init(SessionFactory sessionFactory) {
setSessionFactory(sessionFactory);
}
}
| true |
320b483697d06afd2e55974cab19104ebcc7732e | Java | TheLastClownthelastone/designPatternStudy | /src/com/pt/singleton/Demo1.java | UTF-8 | 418 | 2.796875 | 3 | [] | no_license | package com.pt.singleton;
/**
* @author nate-pt
* @date 2021/10/14 11:19
* @Since 1.8
* @Description 单例模式
* 恶汉单例模式
*/
public class Demo1 {
private static Demo1 instance = new Demo1();
private Demo1(){
}
public static Demo1 getInstance() {
return instance;
}
public static void main(String[] args) {
System.out.println(Demo1.getInstance());
}
}
| true |
94a854b49d54331426a09695aab4148397d81718 | Java | jzheng13/fyp-securityanalysis | /counter/src/application/EditAccount.java | UTF-8 | 6,373 | 2 | 2 | [] | no_license | package application;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import com.toedter.calendar.JDateChooser;
public class EditAccount extends JPanel {
private AppFrame parent;
private Name user;
private Account account;
private Database db;
private JTextField serviceProvider;
private JTextField username;
private JCheckBox pubUser;
private JCheckBox pubEmail;
private JPasswordField password;
private JComboBox<Account> email;
private JDateChooser dateChooser;
/**
* Create the panel.
*/
public EditAccount(AppFrame parent) {
this.parent = parent;
this.user = parent.getUser();
this.account = parent.getAccount();
this.db = parent.getDatabase();
// this.setBounds(0, 0, 0, 0);
this.setBounds(100, 100, 1312, 772);
this.setBorder(new EmptyBorder(5, 5, 5, 5));
this.setLayout(null);
JLabel lblSelectField = new JLabel("Edit account " + parent.getAccount());
lblSelectField.setFont(new Font("Tahoma", Font.BOLD, 34));
lblSelectField.setBounds(26, 28, 828, 41);
this.add(lblSelectField);
JLabel instructions1 = new JLabel("Edit the required fields if necessary and press 'Edit details' to proceed or 'Confirm' to commit");
instructions1.setBounds(83, 89, 1146, 33);
add(instructions1);
JLabel instructions2 = new JLabel("changes.");
instructions2.setBounds(83, 130, 1146, 33);
add(instructions2);
JLabel lblServiceProvider = new JLabel("Service Provider");
lblServiceProvider.setBounds(85, 199, 231, 33);
this.add(lblServiceProvider);
JLabel lblUsername = new JLabel("Username");
lblUsername.setBounds(85, 260, 173, 33);
this.add(lblUsername);
JLabel lblPassword = new JLabel("Password");
lblPassword.setBounds(83, 321, 115, 33);
this.add(lblPassword);
serviceProvider = new JTextField();
List<String[]> result = db.selectValues("SELECT sp, username FROM ACCOUNTS_LOGIN_"
+ user.id() + " WHERE id='" + account.id() + "'", 2);
serviceProvider.setText(result.get(0)[0]);
serviceProvider.setEditable(false);
serviceProvider.setBounds(327, 196, 325, 39);
this.add(serviceProvider);
username = new JTextField();
username.setBounds(327, 257, 325, 39);
username.setText(result.get(0)[1]);
username.setColumns(10);
username.setEditable(false);
this.add(username);
JComboBox<Account> sso = new JComboBox<Account>();
sso.setMaximumRowCount(100);
sso.setBounds(937, 199, 272, 41);
sso.setVisible(false);
sso.setEditable(false);
this.add(sso);
JLabel lblEmail = new JLabel("Email");
lblEmail.setBounds(83, 382, 115, 33);
this.add(lblEmail);
email = new JComboBox<Account>();
email.setMaximumRowCount(100);
email.setEditable(false);
email.setBounds(327, 379, 325, 39);
this.add(email);
result = db.selectValues("SELECT id FROM ACCOUNTS_LOGIN_" + user.id(), 1);
for (String[] r : result) {
Account acc = new Account(user, r[0]);
email.addItem(acc);
}
sso.setSelectedIndex(-1);
email.setSelectedIndex(-1);
JCheckBox chckbxSSO = new JCheckBox("Single Sign-on");
chckbxSSO.setEnabled(false);
result = db.selectValues("SELECT sso FROM ACCOUNTS_LOGIN_" + user.id()
+ " WHERE sso IS NOT NULL", 1);
if (!result.isEmpty()) {
chckbxSSO.setSelected(true);
sso.setSelectedItem(result.get(0)[0]);
}
chckbxSSO.setBounds(686, 195, 221, 41);
this.add(chckbxSSO);
password = new JPasswordField();
password.setBounds(327, 318, 325, 39);
this.add(password);
JLabel lblDateModified = new JLabel("Date Modified");
lblDateModified.setBounds(696, 321, 211, 33);
add(lblDateModified);
dateChooser = new JDateChooser();
dateChooser.setBounds(937, 318, 272, 39);
add(dateChooser);
dateChooser.setDate(new Date());
pubUser = new JCheckBox("Public");
pubUser.setBounds(686, 256, 221, 41);
add(pubUser);
pubEmail = new JCheckBox("Public");
pubEmail.setBounds(686, 378, 221, 41);
add(pubEmail);
JButton btnAddDetails = new JButton("Edit Details >");
btnAddDetails.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
if (confirm() == JOptionPane.YES_OPTION) {
parent.addPanel(new EditDetails(parent));
}
}
});
btnAddDetails.setBounds(747, 587, 249, 41);
this.add(btnAddDetails);
JButton btnBack = new JButton("< Back");
btnBack.setBounds(83, 587, 171, 41);
add(btnBack);
btnBack.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
parent.setAccount(null);
parent.addPanel(new ExistAcc(parent));
}
});
JButton btnConfirm = new JButton("Confirm");
btnConfirm.setBounds(1038, 587, 171, 41);
add(btnConfirm);
btnConfirm.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (confirm() == JOptionPane.YES_OPTION) {
parent.setAccount(null);
parent.addPanel(new ExistAcc(parent));
}
}
});
}
public int confirm() {
int conf = JOptionPane.showConfirmDialog(parent, "Confirm changes?");
if (conf == JOptionPane.YES_OPTION) {
String pw = new String(password.getPassword());
db.query("UPDATE ACCOUNTS_LOGIN_" + user.id() + " SET usrpublic=" + pubUser.isSelected()
+ " WHERE id='" + account.id() + "'");
if (!pw.isEmpty()) {
SimpleDateFormat format = new SimpleDateFormat("yyyy, mm, dd");
String date = format.format(dateChooser.getDate());
db.query("UPDATE ACCOUNTS_LOGIN_" + user.id() + " SET password='" + pw
+ "', mod_date='" + date + "' WHERE id='" + account.id() + "'");
}
if (email.getSelectedIndex() >= 0) {
Account em = (Account) email.getSelectedItem();
db.query("UPDATE ACCOUNTS_INFO_" + user.id() + " SET email='" + em.id()
+ "', empublic=" + pubEmail.isSelected() + " WHERE id='" + account.id() + "'");
}
}
return conf;
}
}
| true |
9a596af0f223462493420ce0bcaa8e737724d1d1 | Java | qbj700/derivedResources | /src/main/java/com/sbs/example/derivedResources/controller/UsrImgController.java | UTF-8 | 4,415 | 2.171875 | 2 | [] | no_license | package com.sbs.example.derivedResources.controller;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.CacheControl;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.sbs.example.derivedResources.dto.DeriveRequest;
import com.sbs.example.derivedResources.dto.GenFile;
import com.sbs.example.derivedResources.service.DeriveRequestService;
import com.sbs.example.derivedResources.service.GenFileService;
import com.sbs.example.derivedResources.util.Util;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
@RestController
public class UsrImgController {
@Value("${custom.genFileDirPath}")
private String genFileDirPath;
@Value("${custom.tmpDirPath}")
private String tmpDirPath;
@Autowired
private GenFileService genFileService;
@Autowired
private DeriveRequestService deriveRequestService;
@GetMapping("/img")
public ResponseEntity<Resource> showImg(HttpServletRequest req, @RequestParam("url") String originUrl,
@RequestParam(defaultValue = "0") int width, @RequestParam(defaultValue = "0") int height,
@RequestParam(defaultValue = "0") int maxWidth) throws FileNotFoundException {
String currentUrl = Util.getUrlFromHttpServletRequest(req);
DeriveRequest deriveRequest = deriveRequestService.getDeriveRequestByUrl(currentUrl);
if (deriveRequest == null) {
int newDeriveRequestId = deriveRequestService.save(currentUrl, originUrl, width, height, maxWidth);
deriveRequest = deriveRequestService.getDeriveRequestById(newDeriveRequestId);
DeriveRequest originDeriveRequest = null;
if (deriveRequest.isOriginStatus()) {
originDeriveRequest = deriveRequest;
} else {
originDeriveRequest = deriveRequestService.getDeriveRequestByOriginUrl(originUrl);
}
GenFile derivedGenFile = null;
if (width > 0 && height > 0) {
derivedGenFile = deriveRequestService.getDerivedGenFileByWidthAndHeightOrMake(originDeriveRequest, width, height);
} else if (width > 0) {
derivedGenFile = deriveRequestService.getDerivedGenFileByWidthOrMake(originDeriveRequest, width);
} else if (maxWidth > 0) {
derivedGenFile = deriveRequestService.getDerivedGenFileByMaxWidthOrMake(originDeriveRequest, maxWidth);
} else {
derivedGenFile = deriveRequestService.getOriginGenFile(originDeriveRequest);
}
deriveRequestService.updateDerivedGenFileId(newDeriveRequestId, derivedGenFile.getId());
return getClientCachedResponseEntity(derivedGenFile, req);
}
GenFile originGenFile = genFileService.getGenFile(deriveRequest.getGenFileId());
return getClientCachedResponseEntity(originGenFile, req);
}
@ApiOperation(value = "이미지번호로 이미지 출력", notes = "입력받은 id에 해당하는 genFile을 출력합니다.")
@ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "genFileId", required = true) })
@GetMapping("/imgById")
public ResponseEntity<Resource> downloadFile(int id, HttpServletRequest req) throws IOException {
GenFile genFile = genFileService.getGenFile(id);
return getClientCachedResponseEntity(genFile, req);
}
private ResponseEntity<Resource> getClientCachedResponseEntity(GenFile genFile, HttpServletRequest req) throws FileNotFoundException {
String filePath = genFile.getFilePath();
Resource resource = new InputStreamResource(new FileInputStream(filePath));
// Try to determine file's content type
String contentType = req.getServletContext().getMimeType(new File(filePath).getAbsolutePath());
if (contentType == null) {
contentType = "application/octet-stream";
}
return ResponseEntity.ok().cacheControl(CacheControl.maxAge(60 * 60 * 24 * 30, TimeUnit.SECONDS)).contentType(MediaType.parseMediaType(contentType)).body(resource);
}
}
| true |
a2d8fe6a787612bf6ae94644f306bcefc673cb5d | Java | Wu-Liucheng/ejile | /src/main/java/xyz/somedefinitions/ejile/entity/SuperAdmin.java | UTF-8 | 1,118 | 2.546875 | 3 | [] | no_license | package xyz.somedefinitions.ejile.entity;
import javax.validation.constraints.NotNull;
import java.time.LocalDate;
import java.util.List;
public class SuperAdmin extends Admin {
private List<Business> businesses;
public SuperAdmin(List<Business> businesses) {
this.businesses = businesses;
}
public SuperAdmin(Integer id, String username, String password, Integer authority, Integer businessId, LocalDate createTime, LocalDate updateTime, Business business, List<Business> businesses) {
super(id, username, password, authority, businessId, createTime, updateTime, business);
this.businesses = businesses;
}
public SuperAdmin(@NotNull Admin admin, List<Business> businesses){
this(admin.getId(),admin.getUsername(),admin.getPassword(),admin.getAuthority(),admin.getBusinessId()
,admin.getCreateTime(),admin.getUpdateTime(),admin.getBusiness(),businesses);
}
public List<Business> getBusinesses() {
return businesses;
}
public void setBusinesses(List<Business> businesses) {
this.businesses = businesses;
}
}
| true |
9252184be0508105e33787ee064e411731e6a6e8 | Java | msalivar/Freya | /app/src/main/java/com/example/cil/freya/ModuleDisplayActivities/ComponentDisplayActivity.java | UTF-8 | 9,983 | 1.90625 | 2 | [] | no_license | package com.example.cil.freya.ModuleDisplayActivities;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import com.example.cil.freya.MainActivity;
import com.example.cil.freya.R;
import com.example.cil.freya.getInfo;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Objects;
public class ComponentDisplayActivity extends Activity implements View.OnClickListener, Spinner.OnItemSelectedListener
{
EditText installation, manufacturer, model, compname, serial_number, supplier, vendor, wiring_notes;
Spinner deployment;
Button saveButton;
EditText info;
int deploymentNumb;
boolean unsyncedFlag = false;
JSONObject thisComponent = null;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.component_display);
// Sets Name of Screen in top left corner
getActionBar().setTitle("Component");
saveButton = (Button) findViewById(R.id.saveButton);
saveButton.setOnClickListener(this);
installation = (EditText) findViewById(R.id.installation);
manufacturer = (EditText) findViewById(R.id.manufacturer);
model = (EditText) findViewById(R.id.model);
compname = (EditText) findViewById(R.id.compname);
serial_number = (EditText) findViewById(R.id.serial_number);
supplier = (EditText) findViewById(R.id.supplier);
vendor = (EditText) findViewById(R.id.vendor);
wiring_notes = (EditText) findViewById(R.id.wiring_notes);
deployment = (Spinner) findViewById(R.id.deployment);
ArrayAdapter<String> componentAdapter = new ArrayAdapter<>(this, R.layout.spinner_item, getInfo.deploymentNames);
componentAdapter.setDropDownViewResource(R.layout.spinner_item);
deployment.setAdapter(componentAdapter);
deployment.setOnItemSelectedListener(this);
getInfo(MainActivity.selectedModuleName);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
getMenuInflater().inflate(R.menu.activity_display_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem menu){
switch(menu.getItemId()){
case R.id.cancel_button:
finish();
return true;
case R.id.delete_button:
if (unsyncedFlag)
{
try
{
MainActivity.ListHandler.removeChild("Unsynced", MainActivity.selectedModuleName);
getInfo.unsynced.getJSONArray("Components").remove(findUnsyncedEntry(MainActivity.selectedModuleName, getInfo.unsynced));
} catch (JSONException e)
{
e.printStackTrace();
}
overridePendingTransition(0, 0);
finish();
return true;
}
else {
Toast.makeText(getBaseContext(),"You cannot delete data already synced to the server", Toast.LENGTH_LONG).show();
}
/* try
{
new CRUD.deleteMessage().execute(getInfo.components.getJSONObject(findEntry(MainActivity.selectedModuleName)).getString("Unique Identifier"));
} catch (JSONException e)
{
e.printStackTrace();
}*/
return true;
default:
return super.onOptionsItemSelected(menu);
}
}
@Override
public void onItemSelected (AdapterView<?> parent, View view, int position, long id)
{
if (position > 0)
deploymentNumb = getInfo.deploymentNumber[position - 1];
}
@Override
public void onNothingSelected(AdapterView<?> adapterView)
{}
private int findEntry(String name, JSONArray modules) throws JSONException
{
for(int i = 0; i < modules.length(); i++)
{
if (modules.getJSONObject(i).getString("Name").equals(name))
{
return i;
}
}
return 0;
}
@Override
public void onClick(View v)
{
switch (v.getId())
{
case (R.id.saveButton):
if (unsyncedFlag)
{
try
{
MainActivity.ListHandler.removeChild("Unsynced", MainActivity.selectedModuleName);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);
String date = sdf.format(new Date());
info = (EditText) findViewById(R.id.compname);
thisComponent.put("Name", info.getText().toString());
info = (EditText) findViewById(R.id.manufacturer);
thisComponent.put("Manufacturer", info.getText().toString());
info = (EditText) findViewById(R.id.model);
thisComponent.put("Model",info.getText().toString());
info = (EditText) findViewById(R.id.serial_number);
thisComponent.put("Serial Number", info.getText().toString());
// may need to be a spinner
info = (EditText) findViewById(R.id.vendor);
thisComponent.put("Vendor", info.getText().toString());
info = (EditText) findViewById(R.id.supplier);
thisComponent.put("Supplier", info.getText().toString());
info = (EditText) findViewById(R.id.installation);
thisComponent.put("Installation Details", info.getText().toString());
info = (EditText) findViewById(R.id.wiring_notes);
thisComponent.put("Wiring Notes", info.getText().toString());
// needs spinner
thisComponent.put("Deployment", deploymentNumb);
thisComponent.put("Modification Date", date);
thisComponent.put("Last Calibrated Date", date);
MainActivity.ListHandler.addChild("Unsynced", thisComponent.getString("Name"));
} catch (JSONException e)
{
e.printStackTrace();
}
}
else{
Toast.makeText(getBaseContext(),"Cannot edit data already synced to the Server", Toast.LENGTH_LONG);
}
finish();
break;
}
}
private int findUnsyncedEntry(String name, JSONObject modules) throws JSONException
{
for(int i = 0; i < modules.getJSONArray("Components").length(); i++)
{
if (modules.getJSONArray("Components").getJSONObject(i).getString("Name").equals(name))
{
return i;
}
}
return 0;
}
private void getInfo(String entryName)
{
try {
thisComponent = getInfo.components.getJSONObject(findEntry(entryName, getInfo.components));
} catch (JSONException e) {
e.printStackTrace();
}
try {
thisComponent = getInfo.unsynced.getJSONArray("Components").getJSONObject(findUnsyncedEntry(entryName, getInfo.unsynced));
unsyncedFlag = true;
} catch (JSONException e) {
e.printStackTrace();
}
try
{
installation.setText(thisComponent.getString("Installation Details"));
manufacturer.setText(thisComponent.getString("Manufacturer"));
model.setText(thisComponent.getString("Model"));
compname.setText(thisComponent.getString("Name"));
serial_number.setText(thisComponent.getString("Serial Number"));
supplier.setText(thisComponent.getString("Supplier"));
vendor.setText(thisComponent.getString("Vendor"));
wiring_notes.setText(thisComponent.getString("Wiring Notes"));
if (!thisComponent.isNull("Deployment"))
{
int deploymentIndex = thisComponent.getInt("Deployment");
String theirName = "error: not found";
for (int i = 0; i < getInfo.deployments.length(); i++)
{
if (getInfo.deployments.getJSONObject(i).getInt("Deployment") == deploymentIndex)
{
JSONObject dude = getInfo.deployments.getJSONObject(i);
theirName = dude.getString("Name");
break;
}
}
for (int i = 0; i < getInfo.deploymentNames.length; i++)
{
if (Objects.equals(getInfo.deploymentNames[i], theirName))
{
deployment.setSelection(i);
break;
}
}
}
else { deployment.setSelection(0); }
} catch (JSONException e)
{
e.printStackTrace();
}
}
@Override
public void onBackPressed()
{
Toast.makeText(this, "Please use cancel or save to exit.", Toast.LENGTH_SHORT).show();
}
}
| true |
678c307e3fff74774e12f6b7b92f766294cc2aac | Java | f-education/study-java | /src/main/java/com/luxoft/dnepr/courses/unit1/LuxoftUtils.java | UTF-8 | 2,883 | 2.9375 | 3 | [] | no_license | package com.luxoft.dnepr.courses.unit1;
/**
* Created with IntelliJ IDEA.
* User: Maxim
* Date: 31.10.13
* Time: 23:23
*/
public final class LuxoftUtils {
public static String getMonthName(int monthOrder, String language) {
String month;
if (language.equals("ru")) {
switch (monthOrder) {
case 1:
month = "Январь";
break;
case 2:
month = "Февраль";
break;
case 3:
month = "Март";
break;
case 4:
month = "Апрель";
break;
case 5:
month = "Май";
break;
case 6:
month = "Июнь";
break;
case 7:
month = "Июль";
break;
case 8:
month = "Август";
break;
case 9:
month = "Сентябрь";
break;
case 10:
month = "Октябрь";
break;
case 11:
month = "Ноябрь";
break;
case 12:
month = "Декабрь";
break;
default:
month = "Неизвестный месяц";
}
} else if (language.equals("en")) {
switch (monthOrder) {
case 1:
month = "January";
break;
case 2:
month = "February";
break;
case 3:
month = "March";
break;
case 4:
month = "April";
break;
case 5:
month = "May";
break;
case 6:
month = "June";
break;
case 7:
month = "July";
break;
case 8:
month = "August";
break;
case 9:
month = "September";
break;
case 10:
month = "October";
break;
case 11:
month = "November";
break;
case 12:
month = "December";
break;
default:
month = "Unknown Month";
}
} else month = "Unknown Language";
return month;
}
}
| true |
4c3b1b3afc3bbdfea3c128ddae74c4c64f60b5bf | Java | Snake02/enviocorreogmail | /src/test/java/com/bdd/page/LoginPage.java | UTF-8 | 1,493 | 1.992188 | 2 | [] | no_license | package com.bdd.page;
import com.bdd.generic.WebDriverDom;
import net.serenitybdd.core.pages.WebElementFacade;
import net.thucydides.core.annotations.DefaultUrl;
import org.openqa.selenium.By;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
@DefaultUrl("https://accounts.google.com/signin/v2/identifier?continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&service=mail&sacu=1&rip=1&flowName=GlifWebSignIn&flowEntry=ServiceLogin")
public class LoginPage extends WebDriverDom {
//@FindBy(xpath = "//*[@id=identifierId']")
@FindBy(xpath = "//input[@id='identifierId']")
private WebElementFacade emailOTelefonoEditText;
@FindBy(xpath = "//span/span[contains(.,'Siguiente')]")
private WebElementFacade siguienteButton;
@FindBy(xpath = "//input[@name='password']")
private WebElementFacade contrasenaEditText;
public void ingresarEmailOTelefono(String emailoTelefono){
sendKeyElement(emailOTelefonoEditText, emailoTelefono);
}
public void clickSiguiente(){
siguienteButton.click();
}
public void ingresarContrasena(String contrasena){
WebDriverWait webDriverWait = new WebDriverWait(getDriver(), 60);
webDriverWait.until(ExpectedConditions.elementToBeClickable(
By.cssSelector("input[type=password]"))).sendKeys(contrasena);
//sendKeyElement(contrasenaEditText, contrasena);
}
}
| true |
acf9820a0c315152d83f68af777697855bc14b13 | Java | jubincn/cs891s | /assignments/assignment2b/app/src/test/java/edu/vandy/simulator/managers/beings/executorService/ExecutorServiceMgrTest.java | UTF-8 | 6,405 | 2.296875 | 2 | [] | no_license | package edu.vandy.simulator.managers.beings.executorService;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import edu.vandy.simulator.ReflectionHelper;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doCallRealMethod;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class ExecutorServiceMgrTest {
private final int BEING_COUNT = 5;
@Mock
private ExecutorService mExecutor;
@InjectMocks
private ExecutorServiceMgr mManagerMock = mock(ExecutorServiceMgr.class);
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
@Test(timeout = 2000)
public void testNewBeing() {
doCallRealMethod().when(mManagerMock).newBeing();
BeingCallable beingCallable = mManagerMock.newBeing();
assertNotNull("newBeing should not return null.", beingCallable);
}
@Test(timeout = 2000)
public void testRunSimulation() {
doCallRealMethod().when(mManagerMock).runSimulation();
mManagerMock.runSimulation();
InOrder inOrder = inOrder(mManagerMock);
verify(mManagerMock).beginBeingThreadPool();
verify(mManagerMock).awaitCompletionOfFutures();
verify(mManagerMock).shutdownNow();
inOrder.verify(mManagerMock).beginBeingThreadPool();
inOrder.verify(mManagerMock).awaitCompletionOfFutures();
inOrder.verify(mManagerMock).shutdownNow();
}
@Test(timeout = 2000)
public void testShutdownNow() throws IllegalAccessException {
ReflectionHelper.injectFieldValueIntoFirstFieldOfType(
mManagerMock, ExecutorService.class, mExecutor);
List<Future<BeingCallable>> futureList = createMockFutureList(BEING_COUNT, false);
futureList.forEach(futureMock -> {
when(futureMock.isCancelled()).thenReturn(false);
when(futureMock.isDone()).thenReturn(false);
when(futureMock.cancel(any(Boolean.class))).thenReturn(true);
});
ReflectionHelper.injectFieldValueIntoFirstFieldOfType(
mManagerMock, List.class, futureList);
doCallRealMethod().when(mManagerMock).shutdownNow();
mManagerMock.shutdownNow();
futureList.forEach(futureMock -> {
try {
verify(futureMock, times(1)).cancel(any(Boolean.class));
} catch (Exception e) {
}
});
}
@Test(timeout = 2000)
public void testBeginBeingThreadPool() {
List<BeingCallable> mockBeings = createMockBeingList(BEING_COUNT);
when(mManagerMock.getBeings()).thenReturn(mockBeings);
when(mManagerMock.getBeingCount()).thenReturn(mockBeings.size());
doCallRealMethod().when(mManagerMock).beginBeingThreadPool();
mManagerMock.beginBeingThreadPool();
// Make sure to shutdown thread pool executor to prevent the autograder
// from hanging for while the threads continue running after the test is
// over.
try {
ExecutorService executor =
ReflectionHelper.findFirstFieldValueOfType(mManagerMock, ExecutorService.class);
assertNotNull("Unable to access ExecutorService " +
"field in ExecutorServiceMgr class.", executor);
executor.shutdownNow();
} catch (Exception e) {
fail("Unable to access ExecutorService " +
"field in ExecutorServiceMgr class: " + e);
}
try {
List<Future<BeingCallable>> futureList =
ReflectionHelper.findFirstFieldValueOfType(mManagerMock, List.class);
assertNotNull("Unable to access List<Future<BeingCallable>> field in " +
"ExecutorServiceMgr class.", futureList);
assertEquals(
"Futures list should contain " + BEING_COUNT + " threads.",
BEING_COUNT,
futureList.size());
} catch (Exception e) {
fail("Unable to access List<Future<BeingCallable>> field in " +
"ExecutorServiceMgr class: " + e);
}
}
@Test(timeout = 2000)
public void testAwaitCompletionOfFutures() throws IllegalAccessException {
List<Future<BeingCallable>> futureList = createMockFutureList(BEING_COUNT, true);
ReflectionHelper.injectFieldValueIntoFirstFieldOfType(
mManagerMock, List.class, futureList);
doCallRealMethod().when(mManagerMock).awaitCompletionOfFutures();
mManagerMock.awaitCompletionOfFutures();
futureList.forEach(futureMock -> {
try {
verify(futureMock).get();
} catch (Exception e) {
}
});
}
private List<Future<BeingCallable>> createMockFutureList(int count, boolean mockGet) {
return IntStream.rangeClosed(1, count)
.mapToObj(unused -> {
Future<BeingCallable> futureMock =
(Future<BeingCallable>) mock(Future.class);
try {
if (mockGet) {
when(futureMock.get()).thenReturn(mock(BeingCallable.class));
}
} catch (Exception e) {
}
return futureMock;
})
.collect(Collectors.toList());
}
private List<BeingCallable> createMockBeingList(int count) {
return IntStream.rangeClosed(1, count)
.mapToObj(unused -> {
BeingCallable being = mock(BeingCallable.class);
when(being.call()).thenReturn(being);
return being;
})
.collect(Collectors.toList());
}
}
| true |
3ed8cabf28850a936d0a9eda02faea6974bc2404 | Java | kathi19/LunchDate2.0 | /app/src/main/java/com/example/lunchdate/MainActivity.java | UTF-8 | 2,699 | 1.828125 | 2 | [] | no_license | package com.example.lunchdate;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.BottomNavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.annotation.NonNull;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.example.lunchdate.ui.login.LoginActivity;
public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BottomNavigationView navView = findViewById(R.id.nav_view);
navView.setOnNavigationItemSelectedListener(this);
FragmentManager fragmentManager= getSupportFragmentManager();
FragmentTransaction transaction= fragmentManager.beginTransaction();
transaction.replace(R.id.fragment_container, new HomeFragment()).commit();
loadFragment(new HomeFragment());
}
private boolean loadFragment(Fragment fragment)
{
if(fragment!=null)
{
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container,fragment)
.commit();
return true;
} return false;
}
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
/*Fragment fragment=null;*/
FragmentManager fragmentManager= getSupportFragmentManager();
FragmentTransaction transaction= fragmentManager.beginTransaction();
switch(menuItem.getItemId()){
case R.id.navigation_home:
transaction.replace(R.id.fragment_container, new HomeFragment()).commit();
return true;
case R.id.navigation_dashboard:
/* fragment= new DashboardFragment();*/
transaction.replace(R.id.fragment_container, new DashboardFragment()).commit();
return true;
case R.id.navigation_notifications:
/* fragment= new NotificationFragment();*/
transaction.replace(R.id.fragment_container, new NotificationFragment()).commit();
return true;
}
/* return loadFragment(fragment);*/
return false;
}
public void jumpToInfos(View view) {
Intent i = new Intent(MainActivity.this, AllgemeineInfos.class);
startActivity(i);
}
}
| true |
cf03258f0e095d337eef8ef781886a9d59f8bdc5 | Java | balduinopeixoto/APP | /apirh/src/main/java/com/apirh/modelo/ProcessamentoSalario.java | UTF-8 | 1,664 | 2.296875 | 2 | [] | no_license | package com.apirh.modelo;
import java.time.LocalDate;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
@Entity
public class ProcessamentoSalario {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private int mes;
private int exercicio;
private LocalDate dataprocessamento;
@ManyToOne
private FuncionarioContrato funcionariocontrato;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public int getMes() {
return mes;
}
public void setMes(int mes) {
this.mes = mes;
}
public int getExercicio() {
return exercicio;
}
public void setExercicio(int exercicio) {
this.exercicio = exercicio;
}
public LocalDate getDataprocessamento() {
return dataprocessamento;
}
public void setDataprocessamento(LocalDate dataprocessamento) {
this.dataprocessamento = dataprocessamento;
}
public FuncionarioContrato getFuncionariocontrato() {
return funcionariocontrato;
}
public void setFuncionariocontrato(FuncionarioContrato funcionariocontrato) {
this.funcionariocontrato = funcionariocontrato;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (id ^ (id >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ProcessamentoSalario other = (ProcessamentoSalario) obj;
if (id != other.id)
return false;
return true;
}
}
| true |
cc284fe94d16078917cf3d9a131ecb282c3df359 | Java | ActiveDev/adcloud | /services/templateservice/src/main/java/com/activedevsolutions/cloud/templateservice/exception/TemplateExceptionHandler.java | UTF-8 | 1,656 | 2.453125 | 2 | [
"Apache-2.0"
] | permissive | package com.activedevsolutions.cloud.templateservice.exception;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
/**
* Provides a central spot to handle any exceptions that may arise from the REST controller.
*
*/
@Component
@ControllerAdvice
public class TemplateExceptionHandler {
/**
* Exception handler that will handle anything that derives from the
* ResourceNotFoundException class. It will return a HTTP 404.
*
* @param e is the Exception object containing the exception thrown
* @return RestError containing the exception message
*/
@ResponseStatus(HttpStatus.NOT_FOUND)
@ExceptionHandler(value = ResourceNotFoundException.class)
public RestError handleNotFoundException(ResourceNotFoundException e) {
final RestError restError = new RestError();
restError.setMessage(e.getMessage());
return restError;
}
/**
* Exception handler that will handle anything that derives from the
* Exception class. It will return a HTTP 400 for all exceptions
*
* @param e is the Exception object containing the exception thrown
* @return RestError containing the exception message
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(value = Exception.class)
public RestError handleBaseException(Exception e) {
final RestError restError = new RestError();
restError.setMessage(e.getMessage());
return restError;
}
}
| true |
aa3987969188a0a973861e4ede28bb23bf61095e | Java | 18756/HWs | /web/fwdb2019/src/main/java/ru/itmo/wp/model/repository/EventRepository.java | UTF-8 | 152 | 1.757813 | 2 | [] | no_license | package ru.itmo.wp.model.repository;
import ru.itmo.wp.model.domain.Type;
public interface EventRepository {
void save(long userId, Type type);
}
| true |
860daa30497a75d8934295bee2a8577fa8807e07 | Java | xiaonuo/KEELEAN | /src/main/java/com/sec/framework/tags/Menu.java | UTF-8 | 952 | 2.125 | 2 | [] | no_license | package com.sec.framework.tags;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
@SuppressWarnings("serial")
public class Menu extends BaseInput {
@Override
public int doEndTag() throws JspException {
JspWriter out = this.pageContext.getOut();
StringBuffer model = new StringBuffer();
model.append("<div class=\"panel-header accordion-header\" id=\"")
.append(id)
.append("\" style=\"width: 100%; cursor:hand;\" ><div class=\"panel-tool\">")
.append(label
+ "<a style=\"float:right\" href=\"javaScript:;\" id=\""
+ id
+ "_a\"><img style=\"border:0px\" src=\"../images/accordion_expand.png\"></a></div></div>");
try {
out.print(model);
} catch (IOException e) {
e.printStackTrace();
}
return super.doEndTag();
}
@Override
public int doStartTag() throws JspException {
return super.doStartTag();
}
}
| true |
2e40f595cd78dc8a9f541ddf464809c62a7ffe80 | Java | fabienwarniez/jtwig | /jtwig-functions/src/main/java/org/jtwig/functions/builtin/ObjectFunctions.java | UTF-8 | 2,352 | 2.4375 | 2 | [
"Apache-2.0"
] | permissive | /**
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jtwig.functions.builtin;
import org.jtwig.functions.annotations.JtwigFunction;
import org.jtwig.functions.annotations.Parameter;
import java.lang.reflect.Array;
import static org.jtwig.types.Undefined.UNDEFINED;
public class ObjectFunctions {
@JtwigFunction(name = "default")
public Object defaultFunction (@Parameter Object input, @Parameter Object defaultValue) {
if (input == null || input.equals(UNDEFINED))
return defaultValue;
else
return input;
}
@JtwigFunction(name = "length")
public int length (@Parameter Object input) {
if (input instanceof String)
return ((String) input).length();
else
return 1;
}
@JtwigFunction(name = "first")
public Object first (@Parameter Object input) {
if (input == null) return input;
if (input.getClass().isArray()) {
if (Array.getLength(input) == 0) return null;
return Array.get(input, 0);
} else return input;
}
@JtwigFunction(name = "last")
public Object last (@Parameter Object input) {
if (input == null) return input;
if (input.getClass().isArray()) {
int length = Array.getLength(input);
if (length == 0) return null;
return Array.get(input, length - 1);
} else return input;
}
@JtwigFunction(name = "toDouble", aliases = { "toFloat" })
public Double toDouble (@Parameter Object input) {
return Double.valueOf(input.toString());
}
@JtwigFunction(name = "toInt")
public Integer toInt (@Parameter Object input) {
if (input instanceof Number)
return ((Number) input).intValue();
return Integer.parseInt(input.toString());
}
}
| true |
cbb2197e28b28925b3669507cdf527c9305b880d | Java | vickey2020/java_core | /Sample_Program/src/com/test/Map/IdentityHM.java | UTF-8 | 328 | 2.5625 | 3 | [] | no_license | package com.test.Map;
import java.util.HashMap;
import java.util.IdentityHashMap;
public class IdentityHM {
public static void main(String[] args) {
IdentityHashMap map=new IdentityHashMap();
Integer i1=new Integer(10);
Integer i2=new Integer(10);
map.put(12, i1);
map.put(13, i2);
System.out.println(map);
}
}
| true |
eaf4ebd5b731f6fa529ad533a5ce92234b76f789 | Java | phgbecker/product-category-service | /src/test/java/br/com/juno/recruta/backend/controller/CategoryControllerTest.java | UTF-8 | 4,454 | 2.046875 | 2 | [] | no_license | package br.com.juno.recruta.backend.controller;
import br.com.juno.recruta.backend.ProductCategoryServiceApplication;
import br.com.juno.recruta.backend.category.IntegrationTestCategory;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ProductCategoryServiceApplication.class)
@AutoConfigureMockMvc
@Category(IntegrationTestCategory.class)
public class CategoryControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void givenRequest_whenId_thenExpectEquals() throws Exception {
mockMvc.perform(get("/categories/1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id", is(1)))
.andExpect(jsonPath("$.name", is("Alimentos")));
}
@Test
public void givenInvalidRequest_whenId_thenStatusIsNotFound() throws Exception {
mockMvc.perform(get("/categories/-1"))
.andExpect(status().isNotFound());
}
@Test
public void givenRequest_whenListAll_thenExpectEquals() throws Exception {
mockMvc.perform(get("/categories/"))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(4)))
.andExpect(jsonPath("$[0].id", is(1)))
.andExpect(jsonPath("$[0].name", is("Alimentos")))
.andExpect(jsonPath("$[1].id", is(2)))
.andExpect(jsonPath("$[1].name", is("Eletrodomésticos")))
.andExpect(jsonPath("$[2].id", is(3)))
.andExpect(jsonPath("$[2].name", is("Móveis")))
.andExpect(jsonPath("$[3].id", is(4)))
.andExpect(jsonPath("$[3].name", is("Queima de estoque")));
}
@Test
public void givenRequest_whenListAllByProduct_thenExpectEquals() throws Exception {
mockMvc.perform(get("/categories/product/5"))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(2)))
.andExpect(jsonPath("$[0].id", is(2)))
.andExpect(jsonPath("$[0].name", is("Eletrodomésticos")))
.andExpect(jsonPath("$[1].id", is(4)))
.andExpect(jsonPath("$[1].name", is("Queima de estoque")));
}
@Test
public void givenInvalidRequest_whenListAllByProduct_thenStatusIsNotFound() throws Exception {
mockMvc.perform(get("/categories/product/-5"))
.andExpect(status().isNotFound());
}
@Test
public void givenRequest_whenListAllProducts_thenExpectEquals() throws Exception {
mockMvc.perform(get("/categories/1/products"))
.andExpect(status().isOk())
.andExpect(jsonPath("$", hasSize(2)))
.andExpect(jsonPath("$[0].id", is(1)))
.andExpect(jsonPath("$[0].name", is("Arroz")))
.andExpect(jsonPath("$[1].id", is(2)))
.andExpect(jsonPath("$[1].name", is("Feijão")));
}
@Test
public void givenInvalidRequest_whenListAllProducts_thenStatusIsNoContent() throws Exception {
mockMvc.perform(get("/categories/-1/products"))
.andExpect(status().isNoContent());
}
@Test
public void givenRequest_whenWithPattern_thenExpectEquals() throws Exception {
mockMvc.perform(get("/categories/pattern/e"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id", is(4)))
.andExpect(jsonPath("$.name", is("Queima de estoque")));
}
@Test
public void givenInvalidRequest_whenWithPattern_thenStatusIsNoContent() throws Exception {
mockMvc.perform(get("/categories/pattern/z"))
.andExpect(status().isNoContent());
}
} | true |
0395ff76b01c70dffb954a71accdab2a91cc15d5 | Java | JeffBobbo/javoip | /src/SocketTester.java | UTF-8 | 1,924 | 3.15625 | 3 | [] | no_license | import javax.sound.sampled.LineUnavailableException;
import java.io.IOException;
public class SocketTester
{
public static void main(String[] args) throws LineUnavailableException, IOException, InterruptedException
{
/*
final int port = 55555;
final String host = "localhost";
final int PACKETS = 1000;
final int BURSTS = 10;
CommunicatorDown downlink = new CommunicatorDown(port);
CommunicatorUp uplink = new CommunicatorUp(host, port);
downlink.start();
// generate an array of 256 bytes to send
final byte[] data = new byte[256];
for (int i = 0; i < data.length; ++i)
data[i] = (byte)i;
int recOkay = 0;
int recBad = 0;
int recCount = 0;
byte[] bytes;
for (int j = 0; j < BURSTS; ++j)
{
for (int i = 0; i < PACKETS; ++i)
uplink.send(data);
Thread.sleep(1000);
}
int pcount;
do
{
pcount = downlink.size();
Thread.sleep(25);
System.out.println(downlink.size() - pcount);
} while (pcount < downlink.size());
while ((bytes = downlink.poll()) != null)
{
++recCount;
boolean isBad = false;
for (int i = 0; i < data.length; ++i)
{
if (bytes[i] != data[i])
{
isBad = true;
break;
}
}
if (!isBad)
{
++recOkay;
}
else
++recBad;
}
uplink.close();
downlink.close();
StringBuilder sb = new StringBuilder();
sb.append("Sent: ").append(PACKETS * BURSTS).append(" packets, of which:").append(System.lineSeparator());
sb.append(recOkay).append(" were received correctly").append(System.lineSeparator());
sb.append(recBad).append(" were received with malformed data").append(System.lineSeparator());
sb.append(recCount).append(" were received in total").append(System.lineSeparator());
System.out.println(sb.toString());
*/
}
}
| true |
d61f0ea35fabef584c6197bcdbcae6722d3ea6bc | Java | yxw027/CoordinateMap | /tlslibrary/src/main/java/com/tencent/qcloud/tlslibrary/service/PhonePwdRegisterService.java | UTF-8 | 6,468 | 2.078125 | 2 | [
"Apache-2.0"
] | permissive | package com.tencent.qcloud.tlslibrary.service;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.tencent.qcloud.tlslibrary.activity.PhonePwdLoginActivity;
import com.tencent.qcloud.tlslibrary.helper.PassWord;
import com.tencent.qcloud.tlslibrary.helper.Util;
import tencent.tls.platform.TLSErrInfo;
import tencent.tls.platform.TLSPwdRegListener;
import tencent.tls.platform.TLSUserInfo;
/**
* Created by dgy on 15/8/14.
*/
public class PhonePwdRegisterService {
private final static String TAG = "PhonePwdRegisterService";
private Context context;
private EditText txt_countryCode;
private EditText txt_phoneNumber;
private EditText txt_checkCode;
private EditText txt_password;
private EditText txt_password1;
private Button btn_requireCheckCode;
private Button btn_verify;
private String countryCode;
private String phoneNumber;
private String checkCode;
private String password;
private String password1;
private PwdRegListener pwdRegListener;
private TLSService tlsService;
public PhonePwdRegisterService(Context context,
EditText txt_countryCode,
EditText txt_phoneNumber,
EditText txt_checkCode,
final EditText txt_password,
EditText txt_password1,
Button btn_requireCheckCode,
Button btn_verify) {
this.context = context;
this.txt_countryCode = txt_countryCode;
this.txt_phoneNumber = txt_phoneNumber;
this.txt_checkCode = txt_checkCode;
this.txt_password=txt_password;
this.txt_password1=txt_password1;
this.btn_requireCheckCode = btn_requireCheckCode;
this.btn_verify = btn_verify;
tlsService = TLSService.getInstance();
pwdRegListener = new PwdRegListener();
btn_requireCheckCode.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
countryCode = "中国大陆 +86";
countryCode = countryCode.substring(countryCode.indexOf('+') + 1); // 解析国家码
phoneNumber = PhonePwdRegisterService.this.txt_phoneNumber.getText().toString();
if (!Util.validPhoneNumber(countryCode, phoneNumber)) {
Util.showToast(PhonePwdRegisterService.this.context, "请输入有效的手机号");
return;
}
Log.e(TAG, Util.getWellFormatMobile(countryCode, phoneNumber));
tlsService.TLSPwdRegAskCode(countryCode, phoneNumber, pwdRegListener);
}
});
btn_verify.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
countryCode = "中国大陆 +86";
countryCode = countryCode.substring(countryCode.indexOf('+') + 1); // 解析国家码
phoneNumber = PhonePwdRegisterService.this.txt_phoneNumber.getText().toString();
checkCode = PhonePwdRegisterService.this.txt_checkCode.getText().toString();
password=PhonePwdRegisterService.this.txt_password.getText().toString();
password1=PhonePwdRegisterService.this.txt_password1.getText().toString();
if (!Util.validPhoneNumber(countryCode, phoneNumber)) {
Util.showToast(PhonePwdRegisterService.this.context, "请输入有效的手机号");
return;
}
if(PassWord.NumberCount(password)<6){
Util.showToast(PhonePwdRegisterService.this.context, "密码不能少于六位");
return;
}
if(!password.equals(password1)){
Util.showToast(PhonePwdRegisterService.this.context, "两次密码不相等");
}
if(!PassWord.Test(password)){
Util.showToast(PhonePwdRegisterService.this.context, "密码只能字母和数字");
}
if (checkCode.length() == 0) {
Util.showToast(PhonePwdRegisterService.this.context, "请输入验证码");
return;
}
Log.e(TAG, Util.getWellFormatMobile(countryCode, phoneNumber));
tlsService.TLSPwdRegVerifyCode(checkCode, pwdRegListener);
}
});
}
public class PwdRegListener implements TLSPwdRegListener {
@Override
public void OnPwdRegAskCodeSuccess(int reaskDuration, int expireDuration) {
Util.showToast(context, "请求下发短信成功,验证码" + expireDuration / 60 + "分钟内有效");
// 在获取验证码按钮上显示重新获取验证码的时间间隔
Util.startTimer(btn_requireCheckCode, "获取验证码", "重新获取", reaskDuration, 1);
}
@Override
public void OnPwdRegReaskCodeSuccess(int reaskDuration, int expireDuration) {
Util.showToast(context, "注册短信重新下发,验证码" + expireDuration / 60 + "分钟内有效");
Util.startTimer(btn_requireCheckCode, "获取验证码", "重新获取", reaskDuration, 1);
}
@Override
public void OnPwdRegVerifyCodeSuccess() {
tlsService.TLSPwdRegCommit(password,pwdRegListener);
}
@Override
public void OnPwdRegCommitSuccess(TLSUserInfo userInfo) {
Util.showToast(context, "注册验证通过");
Intent intent = new Intent(context, PhonePwdLoginActivity.class);
intent.putExtra(Constants.EXTRA_PHONEPWD_REG_RST, Constants.PHONEPWD_REGISTER);
intent.putExtra(Constants.PHONE_NUMBER, txt_phoneNumber.getText().toString());
context.startActivity(intent);
((Activity)context).finish();
}
@Override
public void OnPwdRegFail(TLSErrInfo errInfo) {
Util.notOK(context, errInfo);
}
@Override
public void OnPwdRegTimeout(TLSErrInfo errInfo) {
Util.notOK(context, errInfo);
}
}
}
| true |
5226648c05db0fa75fd93aa1ef72a2e5ac622ab7 | Java | AliMakni92/EMIEliteConseilBackend | /src/main/java/tn/esprit/spring/entity/Formation.java | UTF-8 | 1,382 | 1.882813 | 2 | [] | no_license | package tn.esprit.spring.entity;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name="formation")
public class Formation implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long idFormation;
@Column(name="type_formation")
private String typeFormation;
@OneToMany(mappedBy="formationparticipation")
private List<Participation> participations;
//@ManyToMany
//private List<User> userformations;
public Long getIdFormation() {
return idFormation;
}
public void setIdFormation(Long idFormation) {
this.idFormation = idFormation;
}
public String getTypeFormation() {
return typeFormation;
}
public void setTypeFormation(String typeFormation) {
this.typeFormation = typeFormation;
}
//public List<User> getUserformations() {
//return userformations;
//}
//public void setUserformations(List<User> userformations) {
//this.userformations = userformations;
//}
}
| true |
bdeeb5a900c80c2ab4f6758ae392f13fc6e1bf4e | Java | atantonova/training_accounting | /backend/training_accounting/src/main/java/com/coursework/training_accounting/util/SupervisorSerializer.java | UTF-8 | 752 | 2.453125 | 2 | [] | no_license | package com.coursework.training_accounting.util;
import com.coursework.training_accounting.domain.User;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import java.io.IOException;
public class SupervisorSerializer extends JsonSerializer<User> {
@Override
public void serialize(User user, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
jsonGenerator.writeStartObject();
jsonGenerator.writeNumberField("id", user.getId());
jsonGenerator.writeStringField("fullName", user.getLastName() + " " + user.getFirstName());
jsonGenerator.writeEndObject();
}
}
| true |
37ecb955da2f329e4555daa3f5538e5134cd3fb8 | Java | yarvs/java_bspb | /src/Lesson4/Main.java | UTF-8 | 1,412 | 3.359375 | 3 | [] | no_license | package Lesson4;
import java.util.Arrays;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
System.out.println("Вот что получилось то...");
ClientsGenerator generator = new Data();
Clients[] customers = new Clients[20];
for (int i = 0; i < customers.length; i++) {
customers[i] = generator.getRandomClients();
System.out.println(customers[i]);
System.out.println();
System.out.println();
System.out.println();
}
int f = 0;
for (int i = 0; i < customers.length; i++){
if (customers[i] instanceof FL) {
if (((FL) customers[i]).sex.equals("Male")) {
f++;
}
}
}
FL[] client_fl = new FL[f];
int j = 0;
for (int i = 0; i < customers.length; i++) {
if (customers[i] instanceof FL) {
if (((FL) customers[i]).sex.equals("Male")) {
client_fl[j] = (FL) customers[i];
j++;
}
}
}
Arrays.sort(client_fl, FL.SortYear);
System.out.println("А вот собственно и список:");
for (int i = 0; i < client_fl.length; i++) {
System.out.println(client_fl[i]);
}
}
}
| true |
9ad32e895211362c092eb60507b0eff6e82e0a90 | Java | williamgo0205/udemy-programacao-em-Java | /JavaEssencial/src/br/com/geekuniversity/secao22/Programa80.java | ISO-8859-1 | 1,530 | 3.828125 | 4 | [] | no_license | package br.com.geekuniversity.secao22;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
//Streams
public class Programa80 {
public static void main(String[] args) {
List<Curso> cursos = new ArrayList<>();
cursos.add(new Curso("Programao para Leigos", 170));
cursos.add(new Curso("Algortimos e Lgica de Programao: Essencial", 280));
cursos.add(new Curso("Programao em C: Essencial", 125));
cursos.add(new Curso("Programao em Java: Essencial", 0));
cursos.add(new Curso("Programao em Python: Essencial", 0));
cursos.add(new Curso("Banco de Dados: Essencial", 0));
System.out.println(">>>> Cursos Totais");
cursos.forEach(System.out::println);
// Como copiar o contedo do Stream para outra lista de curso;
List<Curso> resultado = cursos.stream()
.filter(c -> c.getAlunos() >= 100)
.collect(Collectors.toList()); // coleta as informaes e insere em uma nova lista
System.out.println();
System.out.println(">>>> Cursos filtrados pelo Collect do Stream");
resultado.forEach(System.out::println);
System.out.println();
System.out.println(">>>> Utilizao do Collectors.toMap");
cursos.stream()
.filter(c -> c.getAlunos() >= 100)
.collect(Collectors.toMap(c -> c.getNome(),
c -> c.getAlunos())) // Coleta pelo Map pelo nome a quantidade dos alunos
.forEach((nome, alunos) -> System.out.println("O curso " + nome + " tem " + alunos + " alunos"));
}
}
| true |
e0bdd9160e82fe29020943aab796ca989e7bf493 | Java | dinesh9696/Paddy-Fetch | /app/src/main/java/com/example/dinesh/firebase/Paddylifesearch.java | UTF-8 | 3,826 | 1.921875 | 2 | [] | no_license | package com.example.dinesh.firebase;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.telephony.SmsManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.app.ProgressDialog;
import android.content.Intent;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.client.ChildEventListener;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class Paddylifesearch extends AppCompatActivity {
TextView t1, t2, t3, t4, t5, t6, t7, t8, t9;
EditText paddyname1;
Button btnsearch;
Firebase firebase;
String pn,a,b,c,d,e,f,g,h,i,j;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_paddylifesearch);
t1 = (TextView) findViewById(R.id.txtpaddyname);
t2 = (TextView) findViewById(R.id.txtferttime);
t3 = (TextView) findViewById(R.id.txtfertilizers);
t4 = (TextView) findViewById(R.id.txtkalaitime);
t5 = (TextView) findViewById(R.id.txtsoil);
t6 = (TextView) findViewById(R.id.txtseason);
t7 = (TextView) findViewById(R.id.txtdurations);
t8 = (TextView) findViewById(R.id.txttime);
paddyname1 = (EditText) findViewById(R.id.txtpaddyname1);
btnsearch = (Button) findViewById(R.id.btnsearch);
btnsearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
search();
}
});
}
public void search() {
pn=paddyname1.getText().toString();
firebase.setAndroidContext(getApplicationContext());
firebase = new Firebase("https://demokmp.firebaseio.com/PADDY_DETAILS/");
firebase.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
a = (String) dataSnapshot.child("Paddy name").getValue();
if (pn.equals(a)) {
b = (String) dataSnapshot.child("Fertilizers time").getValue();
c = (String) dataSnapshot.child("Fertilizers name").getValue();
d = (String) dataSnapshot.child("Kalai time").getValue();
e = (String) dataSnapshot.child("Durations").getValue();
f = (String) dataSnapshot.child("Time").getValue();
g = (String) dataSnapshot.child("Soil type").getValue();
h = (String) dataSnapshot.child("Season").getValue();
t1.setText(a);
t2.setText(b);
t3.setText(c);
t4.setText(d);
t5.setText(g);
t6.setText(h);
t7.setText(e);
t8.setText(f);
}
}
@Override
public void onChildChanged (DataSnapshot dataSnapshot, String s){
}
@Override
public void onChildRemoved (DataSnapshot dataSnapshot){
}
@Override
public void onChildMoved (DataSnapshot dataSnapshot, String s){
}
@Override
public void onCancelled (FirebaseError firebaseError){
}
});
}
} | true |
ccbdad22ea3f45a5bc7c6afd57d3654c3f3790e8 | Java | alexhandzhiev/SortingShowcase | /src/sort/objects/ObjectSort.java | WINDOWS-1251 | 3,815 | 3.515625 | 4 | [] | no_license | package sort.objects;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;
import sort.comparators.AgeComparator;
import sort.comparators.BmiComparator;
import sort.comparators.FacultyNumberComparator;
import sort.comparators.HeightComparator;
import sort.comparators.NameComparator;
import sort.comparators.SexComparator;
import sort.reader.PeopleReader;
/**
* @author alex
* - 28.10.2012.
*/
public class ObjectSort {
/**
* . Person Comparable,
* , - .
* compareTo(), Arrays.sort() ,
* .
*
* @param args
*/
public static void main(String[] args) {
prepareMenu();
}
private static void prepareMenu() {
createMenu();
selectSorting();
}
private static void selectSorting() {
System.out.println(": ");
Scanner scan = new Scanner(System.in);
int input = scan.nextInt();
switch (input) {
case 1:
sortPersons(new SexComparator());
break;
case 2:
sortPersons(new HeightComparator());
break;
case 3:
sortPersons(new AgeComparator());
break;
case 4:
sortPersons(new BmiComparator());
break;
case 5:
sortPersons(new NameComparator());
break;
case 6:
sortPersons(new FacultyNumberComparator());
break;
case 7:
findByName();
break;
case 8:
exit();
break;
default:
System.out.println("Error! Please enter a valid value.");
selectSorting();
break;
}
prepareMenu();
}
private static void exit() {
System.out.println("Are you sure you want to exit.");
Scanner scan = new Scanner(System.in);
String answer = scan.nextLine();
if (answer.equals("y")) {
System.out.println("kthxbye");
System.exit(0);
}
prepareMenu();
}
private static void sortPersons(Comparator c) {
Person[] people = createPeople();
System.out.println(" : ");
System.out.println("----------------------");
printPersons(people);
Arrays.sort(people, c);
System.out.println(" :");
System.out.println("----------------------");
printPersons(people);
}
private static void findByName() {
System.out.println(" : ");
Scanner scan = new Scanner(System.in);
String input = scan.next().trim();
PeopleReader pplReader = new PeopleReader("databaseLOL.txt");
Person[] people = pplReader.readPeople();
Person personToSearch = new Person(input, null, null, null, null, null);
Person personFound = people[Collections.binarySearch(Arrays.asList(people), personToSearch, new NameComparator())];
personFound.print();
}
private static Person[] createPeople() {
PeopleReader peopleReader = new PeopleReader("databaseLOL.txt");
return peopleReader.readPeople();
}
private static void printPersons(Person[] people) {
for (int i = 0; i < people.length; i++) {
people[i].print();
}
}
private static void createMenu() {
System.out.println("======================");
System.out.println(" : ");
System.out.println("[1] ");
System.out.println("[2] ");
System.out.println("[3] ");
System.out.println("[4] BMI");
System.out.println("[5] ");
System.out.println("[6] ");
System.out.println("[7] ");
System.out.println("[8] ");
System.out.println("======================");
}
} | true |
dd4c2bbd1ed66c4e8d8e28f3c6fdeef0288efefe | Java | artiemq/balance | /src/test/java/com/example/balance/TestWalletController.java | UTF-8 | 2,266 | 2.453125 | 2 | [] | no_license | package com.example.balance;
import com.example.client.WalletClient;
import com.example.model.CreateWallet;
import com.example.model.DepositRequest;
import com.example.model.ExchangeRequest;
import io.micronaut.http.client.exceptions.HttpClientResponseException;
import io.micronaut.test.annotation.MicronautTest;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import javax.inject.Inject;
import java.math.BigInteger;
@MicronautTest
public class TestWalletController {
@Inject
WalletClient walletClient;
@Test
void shouldCreateWallet() {
var createWallet = new CreateWallet("wallet");
var wallet = walletClient.create(createWallet);
Assertions.assertEquals("wallet", wallet.getName());
}
@Test
void shouldNotCreateWalletWithSameName() {
var createWallet = new CreateWallet("wallet");
walletClient.create(createWallet);
Assertions.assertThrows(
HttpClientResponseException.class,
() -> walletClient.create(createWallet)
);
}
@Test
void shouldDeposit() {
var createWallet = new CreateWallet("wallet2");
var wallet = walletClient.create(createWallet);
var depositRequest = new DepositRequest(BigInteger.valueOf(100));
wallet = walletClient.deposit(wallet.getName(), depositRequest);
Assertions.assertEquals(BigInteger.valueOf(100), wallet.getBalance());
}
@Test
void shouldExchange() {
var depositRequest = new DepositRequest(BigInteger.valueOf(100));
var createWallet = new CreateWallet("wallet3");
var wallet = walletClient.create(createWallet);
walletClient.deposit(wallet.getName(), depositRequest);
var createWalletSecond = new CreateWallet("huelet3");
var walletSecond = walletClient.create(createWalletSecond);
var exchangeRequest = new ExchangeRequest(wallet.getName(), walletSecond.getName(), BigInteger.valueOf(50));
wallet = walletClient.exchange(exchangeRequest);
Assertions.assertEquals(BigInteger.valueOf(50), wallet.getBalance());
Assertions.assertEquals(BigInteger.valueOf(50), walletClient.getWallet(walletSecond.getName()).getBalance());
}
}
| true |
4c196fdee956ae85b68ed66a599f10d90151862b | Java | AwsRadwan/Java_Stack | /Spring_MVC/Dojos_And_Ninjas/src/main/java/com/aws/dojo/controllers/MainController.java | UTF-8 | 2,147 | 2.34375 | 2 | [] | no_license | package com.aws.dojo.controllers;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.aws.dojo.models.Dojo;
import com.aws.dojo.models.Ninja;
import com.aws.dojo.services.DandNService;
@Controller
public class MainController {
private final DandNService ser;
public MainController(DandNService ser) {
this.ser = ser;
}
@RequestMapping("/")
public String main(Model model) {
model.addAttribute("dojos", ser.allDojos());
model.addAttribute("ninjas", ser.allNinjas());
return "index.jsp";
}
@RequestMapping("/dojo")
public String dojo(@ModelAttribute("dojo") Dojo dojo) {
return "dojo.jsp";
}
@RequestMapping("/ninja")
public String ninja(@ModelAttribute("ninja") Ninja ninja, Model model) {
model.addAttribute("dojos", ser.allDojos());
return "ninja.jsp";
}
@RequestMapping(value="/adddojo", method = RequestMethod.POST)
public String adddojo(@Valid @ModelAttribute("dojo") Dojo dojo, BindingResult result) {
if (result.hasErrors()) {
return "/dojo.jsp";
} else {
ser.createDojo(dojo);
return "redirect:/";
}
}
@RequestMapping(value="/addninja", method = RequestMethod.POST)
public String addninja(@Valid @ModelAttribute("ninja") Ninja ninja, BindingResult result) {
if (result.hasErrors()) {
return "/ninja.jsp";
} else {
ser.createNinja(ninja);
return "redirect:/";
}
}
@RequestMapping(value="/ninja/{id}", method = RequestMethod.POST)
public String delete(@PathVariable("id") Long id) {
Ninja x = ser.findNinja(id);
ser.deleteNinja(x);
return "redirect:/";
}
@RequestMapping(value="/dojo/{id}", method = RequestMethod.POST)
public String deleted(@PathVariable("id") Long id) {
Dojo x = ser.findDojo(id);
ser.deleteDojo(x);
return "redirect:/";
}
}
| true |
cb4e8fe304b48cfc0ca280fbc8c5dc785366362d | Java | lllyyyggg/java-test-demo | /src/pattern/action/NullObjectTest.java | UTF-8 | 1,980 | 3.421875 | 3 | [] | no_license | package pattern.action;
import java.util.HashMap;
import java.util.Map;
public class NullObjectTest {
static abstract class AbstractPerson {
protected String name;
abstract String getName();
abstract boolean isNull();
}
static class Person extends AbstractPerson {
public Person() {
}
public Person(String name) {
this.name = name;
}
@Override
public String getName() {
return this.name;
}
@Override
boolean isNull() {
return false;
}
}
static class NullPerson extends AbstractPerson {
public NullPerson() {
}
@Override
String getName() {
// do something special
throw new RuntimeException("该用户不存在");
}
@Override
boolean isNull() {
return true;
}
}
static class PersonFactory {
private static final Map<String, Person> personMap = new HashMap<>();
private static final NullPerson nullPerson = new NullPerson();
static {
Person tom = new Person("Tom");
Person bob = new Person("Bob");
personMap.put(tom.getName(), tom);
personMap.put(bob.getName(), bob);
}
public static AbstractPerson get(String name) {
if (personMap.containsKey(name)) {
return personMap.get(name);
} else {
return nullPerson;
}
}
}
public static void main(String[] args) {
AbstractPerson tom = PersonFactory.get("Tom");
System.out.println(tom.getName() + " " + tom.isNull());
AbstractPerson bob = PersonFactory.get("Bob");
System.out.println(bob.getName() + " " + bob.isNull());
AbstractPerson lucy = PersonFactory.get("Lucy");
System.out.println(lucy.getName() + " " + lucy.isNull());
}
}
| true |
990dc7632507f0743e42c3e35a3ddd2069b4f565 | Java | xzslrnx/backend_cloud_commodity | /src/main/java/com/greyu/ysj/authorization/annotation/CurrentUserId.java | UTF-8 | 579 | 2.046875 | 2 | [] | no_license | package com.greyu.ysj.authorization.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @Description: 在Controller的方法参数中使用此注解,该方法在映射时会注入当前登录的userId
* @See: com.greyu.ysj.authorization.resolvers.CurrentUserIdMethodArgumentResolver
* @Author: gre_yu@163.com
* @Date: Created in 0:57 2018/2/1
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface CurrentUserId {
}
| true |
977d7629a6fcd9cdb5b58dbd26bac1ffb83b49e5 | Java | vesran/Phineloops | /src/main/java/model/enumtype/Orientation.java | UTF-8 | 420 | 2.890625 | 3 | [] | no_license | package model.enumtype;
/**
* All orientations possible for a piece
*/
public enum Orientation {
NORTH {public Orientation opposite() { return Orientation.SOUTH; }},
SOUTH {public Orientation opposite() { return Orientation.NORTH; }},
WEST {public Orientation opposite() { return Orientation.EAST; }},
EAST {public Orientation opposite() { return Orientation.WEST; }};
public abstract Orientation opposite();
}
| true |
ad295f15844fd5d64a6649901908356d519bbc1c | Java | webdes27/AionTypeZero | /AE-Game/data/scripts/system/handlers/ai/events/PigAI2.java | UTF-8 | 446 | 1.867188 | 2 | [] | no_license | package ai.events;
import ai.AggressiveNpcAI2;
import org.typezero.gameserver.ai2.AIName;
import org.typezero.gameserver.services.NpcShoutsService;
/**
*
* @author Romanz
*/
@AIName("pig")
public class PigAI2 extends AggressiveNpcAI2 {
@Override
protected void handleSpawned() {
NpcShoutsService.getInstance().sendMsg(getOwner(), 390005, getObjectId(), 0, 0);
super.handleSpawned();
}
}
| true |
625870c7ed28a56605eec2992872a98205aa48b2 | Java | cosemachi/alg | /src/test/java/homework/week4/GraphTest.java | UTF-8 | 437 | 2.203125 | 2 | [] | no_license | package homework.week4;
import java.io.*;
import org.junit.*;
public class GraphTest {
@Test
public void test_graph_1() {
final Graph test = new Graph(new File("/Users/Lansing/GitResource/alg/src/test/java/homework/week4/Test1.txt"));
test.printEdges();
}
@Test
public void test_graph_2() {
final Graph test = new Graph(new File("/Users/Lansing/Desktop/Course/Algorithm_part1 /week4/SCC.txt"));
test.printEdges();
}
}
| true |
f2b56447dffef320f6882ab41e9f66db9c5e50d2 | Java | alangonzalez93/redes | /src/redes/Message.java | UTF-8 | 1,042 | 2.640625 | 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 redes;
/**
*
* @author luciano
*/
class Message {
private int time;
private int state;
private int pid;
public Message(int time, int pid) {
this.time = time;
this.pid = pid;
}
public Message(int time, int pid, int state) {
this.time = time;
this.pid = pid;
this.state = state;
}
public int getState() {
return state;
}
public void setState(int parameter) {
this.state = parameter;
}
public int getTime() {
return time;
}
public void setTime(int time) {
this.time = time;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
@Override
public String toString() {
return time+"-"+state+"-"+pid+"-";
}
}
| true |
5cc6dee2bc8b239b8f533b8e6ed361d474ababa9 | Java | DimasDev/ShieldTaskBack | /src/main/java/application/repositories/StopWatchRepository.java | UTF-8 | 278 | 1.976563 | 2 | [] | no_license | package application.repositories;
import application.entities.TimeMarkEntity;
import org.springframework.data.jpa.repository.JpaRepository;
public interface StopWatchRepository extends JpaRepository<TimeMarkEntity, Integer> {
TimeMarkEntity findByTime(String timeMark);
}
| true |
0eae5df9cf92603944afc2a7180754007f47b022 | Java | carstendev/briefcase | /src/org/opendatakit/briefcase/ui/export/ExportPanel.java | UTF-8 | 5,570 | 1.765625 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright (C) 2018 Nafundi
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.opendatakit.briefcase.ui.export;
import static java.time.format.DateTimeFormatter.ISO_DATE_TIME;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
import static org.opendatakit.briefcase.export.ExportForms.buildCustomConfPrefix;
import static org.opendatakit.briefcase.model.FormStatus.TransferType.EXPORT;
import static org.opendatakit.briefcase.ui.ODKOptionPane.showErrorDialog;
import java.time.LocalDateTime;
import java.util.List;
import org.bushe.swing.event.annotation.AnnotationProcessor;
import org.bushe.swing.event.annotation.EventSubscriber;
import org.opendatakit.briefcase.export.ExportConfiguration;
import org.opendatakit.briefcase.export.ExportForms;
import org.opendatakit.briefcase.model.BriefcaseFormDefinition;
import org.opendatakit.briefcase.model.BriefcasePreferences;
import org.opendatakit.briefcase.model.FormStatus;
import org.opendatakit.briefcase.model.FormStatusEvent;
import org.opendatakit.briefcase.model.TerminationFuture;
import org.opendatakit.briefcase.ui.export.components.ConfigurationPanel;
import org.opendatakit.briefcase.util.ExportAction;
import org.opendatakit.briefcase.util.FileSystemUtils;
public class ExportPanel {
public static final String TAB_NAME = "Export";
private final TerminationFuture terminationFuture;
private final ExportForms forms;
private final ExportPanelForm form;
public ExportPanel(TerminationFuture terminationFuture, ExportForms forms, ExportPanelForm form, BriefcasePreferences preferences) {
this.terminationFuture = terminationFuture;
this.forms = forms;
this.form = form;
AnnotationProcessor.process(this);// if not using AOP
form.getConfPanel().onChange(() ->
forms.updateDefaultConfiguration(form.getConfPanel().getConfiguration())
);
forms.onSuccessfulExport((String formId, LocalDateTime exportDateTime) ->
preferences.put(ExportForms.buildExportDateTimePrefix(formId), exportDateTime.format(ISO_DATE_TIME))
);
form.onChange(() -> {
// Clean all default conf keys
preferences.removeAll(ExportConfiguration.keys());
// Put default conf
if (form.getConfPanel().isValid())
preferences.putAll(form.getConfPanel().getConfiguration().asMap());
// Clean all custom conf keys
forms.forEach(formId ->
preferences.removeAll(ExportConfiguration.keys(buildCustomConfPrefix(formId)))
);
// Put custom confs
forms.getCustomConfigurations().forEach((formId, configuration) ->
preferences.putAll(configuration.asMap(buildCustomConfPrefix(formId)))
);
if (forms.someSelected() && (form.getConfPanel().isValid() || forms.allSelectedFormsHaveConfiguration()))
form.enableExport();
else
form.disableExport();
if (forms.allSelected()) {
form.toggleClearAll();
} else {
form.toggleSelectAll();
}
});
form.onExport(() -> new Thread(() -> {
List<String> errors = export();
if (!errors.isEmpty()) {
String message = String.format(
"%s\n\n%s", "We have found some errors while performing the requested export actions:",
errors.stream().map(e -> "- " + e).collect(joining("\n"))
);
showErrorDialog(form.getContainer(), message, "Export error report");
}
}).start());
}
public static ExportPanel from(TerminationFuture terminationFuture, BriefcasePreferences preferences) {
ExportConfiguration defaultConfiguration = ExportConfiguration.load(preferences);
ConfigurationPanel confPanel = ConfigurationPanel.from(defaultConfiguration, false);
ExportForms forms = ExportForms.load(defaultConfiguration, getFormsFromStorage(), preferences);
ExportPanelForm form = ExportPanelForm.from(forms, confPanel);
return new ExportPanel(
terminationFuture,
forms,
form,
preferences
);
}
public void updateForms() {
forms.merge(getFormsFromStorage());
form.refresh();
}
private static List<FormStatus> getFormsFromStorage() {
return FileSystemUtils.formCache.getForms().stream()
.map(formDefinition -> new FormStatus(EXPORT, formDefinition))
.collect(toList());
}
public ExportPanelForm getForm() {
return form;
}
private List<String> export() {
form.disableUI();
terminationFuture.reset();
List<String> errors = forms.getSelectedForms().parallelStream()
.peek(FormStatus::clearStatusHistory)
.map(formStatus -> (BriefcaseFormDefinition) formStatus.getFormDefinition())
.flatMap(formDefinition -> ExportAction.export(formDefinition, forms.getConfiguration(formDefinition.getFormId()), terminationFuture).stream())
.collect(toList());
form.enableUI();
return errors;
}
@EventSubscriber(eventClass = FormStatusEvent.class)
public void onFormStatusEvent(FormStatusEvent event) {
updateForms();
}
}
| true |
123ed2e5efc6c7d1b20e7e3576a95bcede3b2e5e | Java | MartyMcAir/FromAppsAndBooks | /Codenza_Java/Graph_Problems_Algorithms/Java Program to Find Whether a Path Exists Between 2 Given Nodes.java | UTF-8 | 4,510 | 3.9375 | 4 | [] | no_license | /*This is a java program to construct a undirected graph and check whether path exists between two vertices, if it exists class return true, false otherwise. Class implements standard Breadth First Search algorithm to traverse from given source node to destination node.*/
//This is a sample program to check that there exists a path between source node and destination node
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class Path_Between_Nodes
{
private Map<String, LinkedHashSet<String>> map = new HashMap();
public void addEdge(String node1, String node2)
{
LinkedHashSet<String> adjacent = map.get(node1);
if (adjacent == null)
{
adjacent = new LinkedHashSet();
map.put(node1, adjacent);
}
adjacent.add(node2);
}
public void addTwoWayVertex(String node1, String node2)
{
addEdge(node1, node2);
addEdge(node2, node1);
}
public boolean isConnected(String node1, String node2)
{
Set adjacent = map.get(node1);
if (adjacent == null)
{
return false;
}
return adjacent.contains(node2);
}
public LinkedList<String> adjacentNodes(String last)
{
LinkedHashSet<String> adjacent = map.get(last);
if (adjacent == null)
{
return new LinkedList();
}
return new LinkedList<String>(adjacent);
}
private static String START;
private static String END;
private static boolean flag;
public static void main(String[] args)
{
// this graph is directional
Path_Between_Nodes graph = new Path_Between_Nodes();
// graph.addEdge("A", "B");
graph.addEdge("A", "C");
graph.addEdge("B", "A");
graph.addEdge("B", "D");
graph.addEdge("B", "E");
graph.addEdge("B", "F");
graph.addEdge("C", "A");
graph.addEdge("C", "E");
graph.addEdge("C", "F");
graph.addEdge("D", "B");
graph.addEdge("E", "C");
graph.addEdge("E", "F");
// graph.addEdge("F", "B");
graph.addEdge("F", "C");
graph.addEdge("F", "E");
LinkedList<String> visited = new LinkedList();
System.out.println("Enter the source node:");
Scanner sc = new Scanner(System.in);
START = sc.next();
System.out.println("Enter the destination node:");
END = sc.next();
visited.add(START);
new Path_Between_Nodes().breadthFirst(graph, visited);
sc.close();
}
private void breadthFirst(Path_Between_Nodes graph,
LinkedList<String> visited)
{
LinkedList<String> nodes = graph.adjacentNodes(visited.getLast());
for (String node : nodes)
{
if (visited.contains(node))
{
continue;
}
if (node.equals(END))
{
visited.add(node);
printPath(visited);
flag = true;
visited.removeLast();
break;
}
}
for (String node : nodes)
{
if (visited.contains(node) || node.equals(END))
{
continue;
}
visited.addLast(node);
breadthFirst(graph, visited);
visited.removeLast();
}
if (flag == false)
{
System.out.println("No path Exists between " + START + " and "
+ END);
flag = true;
}
}
private void printPath(LinkedList<String> visited)
{
if (flag == false)
System.out.println("Yes there exists a path between " + START
+ " and " + END);
for (String node : visited)
{
System.out.print(node);
System.out.print(" ");
}
System.out.println();
}
}
/*
Enter the source node:
E
Enter the destination node:
B
No path Exists between E and B
Enter the source node:
A
Enter the destination node:
E
Yes there exists a path between A and E
A C E
A C F E
| true |
8e1ff211012ae42e171eeb2ca36832b55dd487ef | Java | Pantherbotics/2018-practice | /src/main/java/frc/robot/Constants.java | UTF-8 | 913 | 2.21875 | 2 | [] | no_license | //this code was made by team 3863 FIRST Robotics, Newbury Park, CA 91320
package frc.robot;
public class Constants{
public double pie = Math.PI;
/*
--6 in wheel conversion--
(60*Math.PI*ticks)/6144
*/
//Robot Joystick Constants
public static int kJoystickPort = 0;
public static int kJoystickLeftXAxis = 0;
public static int kJoystickLeftYAxis = 1;
public static int kJoystickRightYAxis = 5;
public static int kJoystickRightXAxis = 2;
//Robot Talons Motors
public static int kLeftA = 13;
public static int kLeftB = 12;
public static int kRightA = 2;
public static int kRightB = 3;
//Drive PID
public static double driveKP = 8.0;
public static double driveKI = 0.0;
public static double driveKD = 0.0;
public static double driveKF = 1023.0/23.0;
public static int timoutMS = 10;
public static int primaryPIDIDX = 0;
} | true |
e8040ae34ac29d887557f481e45e8e1be21cd053 | Java | slievrly/spring-cloud-alibaba | /spring-cloud-alibaba-examples/rocketmq-example/rocketmq-tx-example/src/main/java/com/alibaba/cloud/examples/tx/TransactionListenerImpl.java | UTF-8 | 2,104 | 2.28125 | 2 | [
"Apache-2.0"
] | permissive | /*
* Copyright 2013-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.cloud.examples.tx;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.stereotype.Component;
/**
* @author <a href="mailto:fangjian0423@gmail.com">Jim</a>
*/
@Component("myTransactionListener")
public class TransactionListenerImpl implements TransactionListener {
/**
* Execute local transaction.
* @param msg messages
* @param arg message args
* @return Transaction state
*/
@Override
public LocalTransactionState executeLocalTransaction(Message msg, Object arg) {
Object num = msg.getProperty("test");
if ("1".equals(num)) {
System.out.println("executer: " + new String(msg.getBody()) + " unknown");
return LocalTransactionState.UNKNOW;
}
else if ("2".equals(num)) {
System.out.println("executer: " + new String(msg.getBody()) + " rollback");
return LocalTransactionState.ROLLBACK_MESSAGE;
}
System.out.println("executer: " + new String(msg.getBody()) + " commit");
return LocalTransactionState.COMMIT_MESSAGE;
}
/**
* MQ check back local transaction states.
* @param msg messages
* @return Transaction state
*/
@Override
public LocalTransactionState checkLocalTransaction(MessageExt msg) {
System.out.println("check: " + new String(msg.getBody()));
return LocalTransactionState.COMMIT_MESSAGE;
}
}
| true |
0da3275648284df514cbe25fe99e05c9535ef169 | Java | deepsoft-haolifa/haolifa | /src/main/java/com/deepsoft/haolifa/service/RejectMaterialService.java | UTF-8 | 673 | 1.820313 | 2 | [] | no_license | package com.deepsoft.haolifa.service;
import com.deepsoft.haolifa.model.dto.ResultBean;
import com.deepsoft.haolifa.model.dto.rejectMaterial.RejectMaterialListDto;
import com.deepsoft.haolifa.model.dto.rejectMaterial.RejectMaterialResultDto;
import com.deepsoft.haolifa.model.dto.rejectMaterial.RejectMaterialSaveDto;
public interface RejectMaterialService {
ResultBean save(RejectMaterialSaveDto dto);
ResultBean delete(String recordNo);
ResultBean updateRecordStatus(String recordNo, Integer status);
ResultBean info(String recordNo);
ResultBean list(RejectMaterialListDto listDto);
ResultBean updateRecordResult(RejectMaterialResultDto resultDto);
}
| true |
19e85c9209068da8e389fa48ce3af3f027be07a3 | Java | huanghuikang/java | /Count.java | GB18030 | 494 | 3.4375 | 3 | [] | no_license | import java.util.*;
class Count
{
//һ
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("һʱӢĶŸ");
String inputString=sc.next().toString();
String stringArray[]=inputString.split(",");
int num[]=new int[stringArray.length];
for(int i=0;i<stringArray.length;i++){
num[i]=Integer.parseInt(stringArray[i]);
System.out.print(num[i]+" ");
}
}
}
| true |
da7fb34c093d05b82cba6dff4022c2fb97a1784d | Java | TevJ/WebQuizEngine | /src/engine/repository/QuizCompletionRepository.java | UTF-8 | 490 | 1.921875 | 2 | [
"MIT"
] | permissive | package engine.repository;
import engine.entity.QuizCompletion;
import engine.entity.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.PagingAndSortingRepository;
public interface QuizCompletionRepository extends PagingAndSortingRepository<QuizCompletion, Long> {
Page<QuizCompletion> findAllByUser(User user, Pageable pageable);
}
| true |
0dab8dbc498931c1991da9e4375e4dd71111b3d5 | Java | karayan/medical_app | /MedicalApp/src/gr/forth/ics/urbanNet/json/QueryJsonSerializer.java | UTF-8 | 720 | 2.203125 | 2 | [] | no_license | package gr.forth.ics.urbanNet.json;
import gr.forth.ics.urbanNet.database.Query;
import java.lang.reflect.Type;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
public class QueryJsonSerializer implements JsonSerializer<Query>{
@Override
public JsonElement serialize(Query arg0, Type arg1, JsonSerializationContext arg2) {
JsonObject root = new JsonObject();
root.addProperty("id", arg0.getId());
root.addProperty("androidDelay" , arg0.getAndroidDelay());
root.addProperty("networkDelay" , arg0.getNetworkDelay());
root.addProperty("serverDelay" , arg0.getServerDelay());
return root;
}
}
| true |
cf9832bb76af1c9abc28f5041a4f87a4d0860040 | Java | PAChain/Server | /src/main/java/com/pachain/voting/service/fabric/WalletResponse.java | UTF-8 | 470 | 1.953125 | 2 | [
"Apache-2.0"
] | permissive | package com.pachain.voting.service.fabric;
import lombok.Getter;
import lombok.Setter;
import org.hyperledger.fabric.gateway.X509Identity;
@Setter
@Getter
public class WalletResponse {
private X509Identity identity;
private Integer status;
private String message;
public WalletResponse(Integer status, String message,X509Identity identity){
this.setStatus(status);
this.setMessage(message);
this.setIdentity(identity);
}
}
| true |
8512083f2e10334626922d6c3677762c90cfdfde | Java | flock0/cloud-calculator | /src/main/java/channels/TcpChannel.java | UTF-8 | 1,658 | 3.65625 | 4 | [] | no_license | package channels;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.SocketException;
/**
* A two-way communication channel based on a TCP connection
*
*/
public class TcpChannel implements Channel {
private Socket socket;
private BufferedReader reader;
private PrintWriter writer;
public TcpChannel(Socket socket) {
this.socket = socket;
initializeIOStreams();
}
private void initializeIOStreams() {
try {
reader = new BufferedReader(new InputStreamReader(
socket.getInputStream()));
writer = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException e) {
System.out.println("Error on creating stream IO: " + e.getMessage());
close();
}
}
@Override
public String readStringLine() throws IOException {
String message = reader.readLine();
if(message == null)
throw new SocketException("socket closed");
else
return message;
}
@Override
public byte[] readByteLine() throws IOException {
String message = reader.readLine();
if(message == null)
throw new SocketException("socket closed");
else
return message.getBytes();
}
@Override
public void println(String out) {
writer.println(out);
}
@Override
public void println(byte[] out) {
writer.print(out);
}
@Override
public void close() {
try {
if (socket != null && !socket.isClosed())
socket.close();
} catch (IOException e) {
// Nothing we can do about it
}
}
@Override
public boolean isClosed() {
if(socket != null)
return socket.isClosed();
else
return true;
}
}
| true |
5db629b9ecb9747b54a63dfb0add5e7d62f7cfba | Java | GauvainSeigneur/Drifter | /app/src/main/java/io/drifterapp/drifter/TestActivity.java | UTF-8 | 5,649 | 1.9375 | 2 | [] | no_license | package io.drifterapp.drifter;
import android.content.ContentUris;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.os.Bundle;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Toast;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import io.drifterapp.drifter.recyclerView.CustomTouchListener;
import io.drifterapp.drifter.recyclerView.RecyclerView_Adapter;
import io.drifterapp.drifter.recyclerView.onItemClickListener;
public class TestActivity extends AudioBaseActivity {
///ArrayList<Audio> audioList;
RecyclerView recyclerView;
RecyclerView_Adapter adapter;
private int mLoadedItems;
NestedScrollView nestedScrollView; //for smooth scrolling of recyclerview as well as to detect the end of recyclerview
ArrayList<Audio> songMainList = new ArrayList<>(); //partial list in which items are added
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_two);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setNestedScrollingEnabled(false);
adapter = new RecyclerView_Adapter(songMainList, getApplication());
recyclerView.setAdapter(adapter);
setRVContent();
nestedScrollView = (NestedScrollView) findViewById(R.id.nestedscrollview);
nestedScrollView.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener() {
@Override
public void onScrollChanged() {
View view = (View) nestedScrollView.getChildAt(nestedScrollView.getChildCount() - 1);
int diff = (view.getBottom() - (nestedScrollView.getHeight() + nestedScrollView
.getScrollY()));
if (diff == 0) {
//NestedScrollView scrolled to bottom
for (int i = 0; i <= 30; i++) {
if (mLoadedItems<songMainList.size()) {
adapter.setDisplayCount(mLoadedItems++);
adapter.notifyDataSetChanged();
Toast.makeText(TestActivity.this, ""+songMainList.size(), Toast.LENGTH_SHORT).show();
}
}
}
}
});
}
private void setRVContent() {
if (songMainList != null && songMainList.size() > 0) {
mLoadedItems = 2;//by default, load only ten item
adapter.setDisplayCount(mLoadedItems);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
//linearLayoutManager.setAutoMeasureEnabled(false);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.addOnItemTouchListener(new CustomTouchListener(this, new onItemClickListener() {
@Override
public void onClick(View view, int index) {
playAudio(index, songMainList);
}
}));
} else {
//todo - make stubview list is empty/null
}
}
private void initList() {
if (cursor != null && cursor.getCount() > 0) {
songMainList = new ArrayList<>();
while (cursor.moveToNext()) {
String artist = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST));
String album = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM));
String track = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.TITLE));
String data = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Media.DATA));
int duration = cursor.getInt(cursor.getColumnIndex(MediaStore.Audio.Media.DURATION));
String durationinString = String.valueOf(duration);
Long albumId = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM_ID));
Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
Uri albumArtUri = ContentUris.withAppendedId(sArtworkUri, albumId);
//Logger.debug(albumArtUri.toString());
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(contentResolver, albumArtUri);
bitmap = Bitmap.createScaledBitmap(bitmap, 30, 30, true);
} catch (FileNotFoundException exception) {
exception.printStackTrace();
//bitmap = BitmapFactory.decodeResource(MainActivity.this.getResources(), R.drawable.ga_july);
} catch (IOException e) {
e.printStackTrace();
}
songMainList.add(new Audio(data, track, album, artist, albumArtUri, durationinString, bitmap));
}
}
if (cursor != null)
cursor.close();
}
@Override
public void makeSomethingOnAccessGranted() {
//initSearchCursor();
initList();
}
}
| true |
5b69a156b480ced4adbd8ab37d8e5791abe47195 | Java | cococo111111/vng | /MVAS/Gateway/temp/src/com/vmg/smpp/gateway/Wait4Response.java | UTF-8 | 1,177 | 1.992188 | 2 | [] | no_license | // Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov.
// Jad home page: http://www.kpdus.com/jad.html
// Decompiler options: packimports(3)
// Source File Name: Wait4Response.java
package com.vmg.smpp.gateway;
import java.math.BigDecimal;
import java.sql.Timestamp;
public class Wait4Response
{
public Wait4Response()
{
emsId = null;
time = new Timestamp(System.currentTimeMillis());
}
public Wait4Response(BigDecimal emsId)
{
this.emsId = emsId;
time = new Timestamp(System.currentTimeMillis());
}
public Wait4Response(BigDecimal emsId, int totalSegments, int seqNum)
{
this.emsId = emsId;
this.totalSegments = totalSegments;
this.seqNum = seqNum;
time = new Timestamp(System.currentTimeMillis());
}
public boolean isLastSegment()
{
return seqNum == totalSegments;
}
public boolean isTimeout()
{
long currTime = System.currentTimeMillis();
return currTime - time.getTime() > 60000L;
}
static final long RESPONSE_TIMEOUT = 60000L;
BigDecimal emsId;
int totalSegments;
int seqNum;
Timestamp time;
}
| true |
6f2fcf8826fc20b76536dee9effa83781135b79f | Java | lluccia/yam | /yam-engine/src/main/java/yam/engine/StatusDaLinha.java | UTF-8 | 127 | 1.578125 | 2 | [] | no_license | package yam.engine;
public enum StatusDaLinha {
MARCADA,
RISCADA,
LIVRE,
MARCAVEL,
RISCAVEL;
}
| true |
38b7a7af0b9a5313984c89374121dfc5b0d2709f | Java | friveraortiz/Projects | /HRM/Original_Version/HRMApplication/src/gui/ModuleFormEvent.java | UTF-8 | 938 | 2.34375 | 2 | [] | no_license | package gui;
import java.util.EventObject;
public class ModuleFormEvent extends EventObject
{
private String moduleName;
private String subModuleName;
private String userLevel;
public ModuleFormEvent(Object source)
{
super(source);
}
public ModuleFormEvent(Object source, String moduleName, String subModuleName, String userLevel)
{
super(source);
this.moduleName = moduleName;
this.subModuleName = subModuleName;
this.userLevel = userLevel;
}
public String getModuleName()
{
return moduleName;
}
public void setModuleName(String moduleName)
{
this.moduleName = moduleName;
}
public String getSubModuleName()
{
return subModuleName;
}
public void setSubModuleName(String subModuleName)
{
this.subModuleName = subModuleName;
}
public String getUserLevel()
{
return userLevel;
}
public void setUserLevel(String userLevel)
{
this.userLevel = userLevel;
}
} | true |
27e5194235867af3ffca64751cbef72fa9540819 | Java | ITUkraine/JobsUkraine | /JobsUkraine/src/main/java/ua/com/jobsukraine/controllers/VacancyController.java | UTF-8 | 2,819 | 2.203125 | 2 | [] | no_license | package ua.com.jobsukraine.controllers;
import java.security.Principal;
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.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import ua.com.jobsukraine.entity.Category;
import ua.com.jobsukraine.entity.Vacancy;
import ua.com.jobsukraine.exceptions.CustomMessageException;
import ua.com.jobsukraine.service.CategoryService;
import ua.com.jobsukraine.service.EmployerService;
import ua.com.jobsukraine.service.LoginInfoService;
import ua.com.jobsukraine.service.VacancyService;
@Controller
public class VacancyController {
@Autowired
private CategoryService categoryService;
@Autowired
private EmployerService employerService;
@Autowired
private VacancyService vacancyService;
@Autowired
private LoginInfoService loginInfoService;
@RequestMapping(value = "/vacancy/delete")
public String deleteVacancy(@RequestParam("id") int id, Principal principal) {
vacancyService.delete(id);
if (loginInfoService.findByLogin(principal.getName()).getRole().getName().equals("ROLE_ADMIN")) {
return "redirect:/vacancies";
}
return "redirect:/empOffice/addVacancy";
}
@RequestMapping(value = "/empOffice/addVacancy", method = RequestMethod.POST)
public String goAddVacancy(@ModelAttribute("vacancy") Vacancy vacancy, BindingResult bindingResult,
Principal principal) {
vacancyService.save(employerService.findByLogin(principal.getName()), vacancy);
return "redirect:/empOffice/addVacancy";
}
@RequestMapping(value = "/empOffice/addVacancy")
public String goAddVacancyPage(Model model, Principal principal) {
model.addAttribute("vacancy", new Vacancy());
model.addAttribute("vacancies", employerService.findByLogin(principal.getName()).getVacancy());
model.addAttribute("list", categoryService.getAll());
model.addAttribute("category", new Category());
return "empOffice/addVacancy";
}
@RequestMapping(value = "/vacancy/{id}")
public ModelAndView showVacancyInfoPage(@PathVariable(value = "id") int id, Principal principal) {
ModelAndView modelAndView = new ModelAndView("vacancy");
Vacancy vacancy = vacancyService.find(id);
if (vacancy == null) {
throw new CustomMessageException("No vacancy founded");
}
modelAndView.addObject("vacancy", vacancy);
return modelAndView;
}
}
| true |
1251f99f5ea79863356ee67750fa29a380a338d6 | Java | aayushkapadia/connect_dot_game | /app/src/main/java/com/example/aayushkapadia/connectdots/Line.java | UTF-8 | 2,510 | 3.0625 | 3 | [] | no_license | package com.example.aayushkapadia.connectdots;
/**
* Created by aayushkapadia on 15/4/16.
*/
public class Line {
public static int padding=60;
public static float radius=26;
public static float gapX=40;
public static float gapY=40;
private float xStart;
private float yStart;
private float xEnd;
private float yEnd;
private boolean isHori;
private boolean clicked;
private int type=0; // who has claimed the line
public void setClicked(boolean clicked) {
this.clicked = clicked;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public Line()
{
}
public Line(float con,float start,float end,boolean hor) {
this.isHori = hor;
clicked=false;
if(hor)
{
yStart=con;
yEnd=con;
xStart=start;
xEnd=end;
}
else
{
xStart=con;
xEnd=con;
yStart=start;
yEnd=end;
}
}
public float getxStart() {
return xStart;
}
public float getyStart() {
return yStart;
}
public float getxEnd() {
return xEnd;
}
public float getyEnd() {
return yEnd;
}
public boolean isHori() {
return isHori;
}
public boolean contains(float x,float y)
{
if(clicked)
return false;
// Log.d("OBJECT", xStart + " " + yStart + " " + isHori);
if(isHori)
{
boolean val = Math.abs(y-yStart)<=Math.min(40, gapY / 4) && x>=(xStart+radius) && x<=(xEnd-radius);
if(val)
clicked = true;
return val;
}
else {
boolean val = Math.abs(x - xStart) <= Math.min(40, gapX / 4) && y >= (yStart+radius) && y <= (yEnd-radius);
if(val)
clicked = true;
return val;
}
}
public void set(float xStart,float yStart,float xEnd,float yEnd,boolean isHori,boolean clicked)
{
this.xStart=xStart;
this.xEnd=xEnd;
this.yStart=yStart;
this.yEnd=yEnd;
this.clicked=clicked;
this.isHori=isHori;
}
public boolean isClicked()
{
return clicked;
}
public Line clone()
{
Line line = new Line();
line.set(xStart,yStart,xEnd,yEnd,isHori,clicked);
return line;
}
}
| true |
9b068c82ac1449fa50061cb02e01828afdb1f830 | Java | TatooMyHeart/test | /src/main/java/com/schedule/tool/wechat/WxPKCS7Encoder.java | UTF-8 | 1,047 | 2.75 | 3 | [] | no_license | package com.schedule.tool.wechat;
import java.nio.charset.Charset;
import java.util.Arrays;
/**
* Created by dell on 2017/7/30.
*/
public class WxPKCS7Encoder {
private static final Charset CHARSET= Charset.forName("utf-8");
private static final int BLOCK_SIZE=32;
public static byte[] encode(int count)
{
int amountToPad = BLOCK_SIZE - (count%BLOCK_SIZE);
if(amountToPad==0)
{
amountToPad=BLOCK_SIZE;
}
char padChr = chr(amountToPad);
String tmp = new String();
for(int index=0;index<amountToPad;index++)
{
tmp+=padChr;
}
return tmp.getBytes(CHARSET);
}
public static byte[] decode(byte[] decrypted)
{
int pad=decrypted[decrypted.length-1];
if(pad<1||pad>32)
{
pad=0;
}
return Arrays.copyOfRange(decrypted,0,decrypted.length-pad);
}
public static char chr(int a)
{
byte target = (byte)(a & 0xFF);
return (char)target;
}
}
| true |
4b3050d0244552c6d7accd80aabe629ffed8e916 | Java | t1030338120/TangycStudyDemo | /base_abstract/src/main/java/demo/study/app/com/tangycstudydemo/AppMainActivity.java | UTF-8 | 963 | 2.015625 | 2 | [] | no_license | package demo.study.app.com.tangycstudydemo;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import demo.study.app.com.tangycstudydemo.base_abstract.activity.MainActivity;
import demo.study.app.com.tangycstudydemo.mvp_loader.MvpLoaderActivity;
public class AppMainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_main);
}
public void click(View view){
switch (view.getId()){
case R.id.button_01:
startActivity(new Intent(this, MainActivity.class));
break;
case R.id.button_02:
break;
case R.id.button_03:
startActivity(new Intent(this, MvpLoaderActivity.class));
break;
}
}
}
| true |
36e9be9ae42c31ee625f36a8fe09a2c6b5451718 | Java | gambol/chunqingaikan | /smali/com/twocloooo/az.java | UTF-8 | 20,771 | 1.96875 | 2 | [] | no_license | package com.twocloooo; class az { void a() { int a;
a=0;// .class public final Lcom/twocloooo/az;
a=0;// .super Ljava/lang/Object;
a=0;//
a=0;//
a=0;// # direct methods
a=0;// .method public static a(Landroid/content/Context;Ljava/lang/String;)Ljava/lang/String;
a=0;// .locals 4
a=0;//
a=0;// const-string v0, ""
a=0;//
a=0;// #v0=(Reference,Ljava/lang/String;);
a=0;// new-instance v1, Ljava/lang/StringBuilder;
a=0;//
a=0;// #v1=(UninitRef,Ljava/lang/StringBuilder;);
a=0;// invoke-static {}, Lcom/twocloooo/be;->a()Ljava/lang/String;
a=0;//
a=0;// move-result-object v2
a=0;//
a=0;// #v2=(Reference,Ljava/lang/String;);
a=0;// invoke-static {v2}, Ljava/lang/String;->valueOf(Ljava/lang/Object;)Ljava/lang/String;
a=0;//
a=0;// move-result-object v2
a=0;//
a=0;// invoke-direct {v1, v2}, Ljava/lang/StringBuilder;-><init>(Ljava/lang/String;)V
a=0;//
a=0;// #v1=(Reference,Ljava/lang/StringBuilder;);
a=0;// const-string v2, "/build/"
a=0;//
a=0;// invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
a=0;//
a=0;// move-result-object v1
a=0;//
a=0;// invoke-virtual {v1, p1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
a=0;//
a=0;// move-result-object v1
a=0;//
a=0;// invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
a=0;//
a=0;// move-result-object v1
a=0;//
a=0;// new-instance v2, Ljava/io/File;
a=0;//
a=0;// #v2=(UninitRef,Ljava/io/File;);
a=0;// invoke-direct {v2, v1}, Ljava/io/File;-><init>(Ljava/lang/String;)V
a=0;//
a=0;// #v2=(Reference,Ljava/io/File;);
a=0;// invoke-virtual {v2}, Ljava/io/File;->exists()Z
a=0;//
a=0;// move-result v2
a=0;//
a=0;// #v2=(Boolean);
a=0;// if-nez v2, :cond_1
a=0;//
a=0;// :cond_0
a=0;// :goto_0
a=0;// #v1=(Conflicted);v2=(Conflicted);v3=(Conflicted);
a=0;// return-object v0
a=0;//
a=0;// :cond_1
a=0;// :try_start_0
a=0;// #v1=(Reference,Ljava/lang/String;);v2=(Boolean);v3=(Uninit);
a=0;// new-instance v2, Ljava/io/FileInputStream;
a=0;//
a=0;// #v2=(UninitRef,Ljava/io/FileInputStream;);
a=0;// invoke-direct {v2, v1}, Ljava/io/FileInputStream;-><init>(Ljava/lang/String;)V
a=0;//
a=0;// #v2=(Reference,Ljava/io/FileInputStream;);
a=0;// invoke-virtual {v2}, Ljava/io/FileInputStream;->available()I
a=0;//
a=0;// move-result v1
a=0;//
a=0;// #v1=(Integer);
a=0;// new-array v1, v1, [B
a=0;//
a=0;// #v1=(Reference,[B);
a=0;// invoke-virtual {v2, v1}, Ljava/io/FileInputStream;->read([B)I
a=0;//
a=0;// const-string v3, "UTF-8"
a=0;//
a=0;// #v3=(Reference,Ljava/lang/String;);
a=0;// invoke-static {v1, v3}, Lorg/apache/http/util/EncodingUtils;->getString([BLjava/lang/String;)Ljava/lang/String;
a=0;//
a=0;// move-result-object v0
a=0;//
a=0;// invoke-virtual {v2}, Ljava/io/FileInputStream;->close()V
a=0;//
a=0;// const-string v1, ""
a=0;//
a=0;// invoke-virtual {v0, v1}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z
a=0;//
a=0;// move-result v1
a=0;//
a=0;// #v1=(Boolean);
a=0;// if-nez v1, :cond_2
a=0;//
a=0;// if-nez v0, :cond_0
a=0;//
a=0;// :cond_2
a=0;// const-string v0, "[]"
a=0;// :try_end_0
a=0;// .catch Ljava/lang/Exception; {:try_start_0 .. :try_end_0} :catch_0
a=0;//
a=0;// goto :goto_0
a=0;//
a=0;// :catch_0
a=0;// #v1=(Conflicted);v2=(Conflicted);v3=(Conflicted);
a=0;// move-exception v1
a=0;//
a=0;// #v1=(Reference,Ljava/lang/Exception;);
a=0;// invoke-virtual {v1}, Ljava/lang/Exception;->printStackTrace()V
a=0;//
a=0;// goto :goto_0
a=0;// .end method
a=0;//
a=0;// .method public static a(Landroid/content/Context;)V
a=0;// .locals 4
a=0;//
a=0;// invoke-static {p0}, Lcom/twocloooo/bb;->b(Landroid/content/Context;)Ljava/lang/String;
a=0;//
a=0;// move-result-object v0
a=0;//
a=0;// #v0=(Reference,Ljava/lang/String;);
a=0;// invoke-static {p0, v0}, Lcom/twocloooo/bb;->a(Landroid/content/Context;Ljava/lang/String;)V
a=0;//
a=0;// sget-object v1, Lcom/twocloooo/bf;->t:Ljava/lang/String;
a=0;//
a=0;// #v1=(Reference,Ljava/lang/String;);
a=0;// new-instance v2, Ljava/lang/StringBuilder;
a=0;//
a=0;// #v2=(UninitRef,Ljava/lang/StringBuilder;);
a=0;// invoke-static {p0, v0}, Lcom/twocloooo/bm;->e(Landroid/content/Context;Ljava/lang/String;)Ljava/lang/String;
a=0;//
a=0;// move-result-object v0
a=0;//
a=0;// invoke-static {v0}, Ljava/lang/String;->valueOf(Ljava/lang/Object;)Ljava/lang/String;
a=0;//
a=0;// move-result-object v0
a=0;//
a=0;// invoke-direct {v2, v0}, Ljava/lang/StringBuilder;-><init>(Ljava/lang/String;)V
a=0;//
a=0;// #v2=(Reference,Ljava/lang/StringBuilder;);
a=0;// const-string v0, "&pplib_version="
a=0;//
a=0;// invoke-virtual {v2, v0}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
a=0;//
a=0;// move-result-object v0
a=0;//
a=0;// const-string v2, "1.5.0.w"
a=0;//
a=0;// invoke-virtual {v0, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
a=0;//
a=0;// move-result-object v0
a=0;//
a=0;// invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
a=0;//
a=0;// move-result-object v0
a=0;//
a=0;// invoke-static {v1, v0}, Lcom/twocloooo/at;->a(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
a=0;//
a=0;// move-result-object v0
a=0;//
a=0;// const-string v1, "contentsavetime"
a=0;//
a=0;// invoke-static {}, Ljava/lang/System;->currentTimeMillis()J
a=0;//
a=0;// move-result-wide v2
a=0;//
a=0;// #v2=(LongLo);v3=(LongHi);
a=0;// invoke-static {v2, v3}, Ljava/lang/String;->valueOf(J)Ljava/lang/String;
a=0;//
a=0;// move-result-object v2
a=0;//
a=0;// #v2=(Reference,Ljava/lang/String;);
a=0;// invoke-static {p0, v1, v2}, Lcom/twocloooo/bm;->b(Landroid/content/Context;Ljava/lang/String;Ljava/lang/String;)V
a=0;//
a=0;// if-eqz v0, :cond_0
a=0;//
a=0;// invoke-virtual {v0}, Ljava/lang/String;->trim()Ljava/lang/String;
a=0;//
a=0;// move-result-object v1
a=0;//
a=0;// const-string v2, ""
a=0;//
a=0;// invoke-virtual {v1, v2}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z
a=0;//
a=0;// move-result v1
a=0;//
a=0;// #v1=(Boolean);
a=0;// if-nez v1, :cond_0
a=0;//
a=0;// invoke-virtual {v0}, Ljava/lang/String;->trim()Ljava/lang/String;
a=0;//
a=0;// move-result-object v1
a=0;//
a=0;// #v1=(Reference,Ljava/lang/String;);
a=0;// const-string v2, "null"
a=0;//
a=0;// invoke-virtual {v1, v2}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z
a=0;//
a=0;// move-result v1
a=0;//
a=0;// #v1=(Boolean);
a=0;// if-nez v1, :cond_0
a=0;//
a=0;// const-string v1, "xpdatasuccess"
a=0;//
a=0;// #v1=(Reference,Ljava/lang/String;);
a=0;// const-string v2, "true"
a=0;//
a=0;// invoke-static {p0, v1, v2}, Lcom/twocloooo/bm;->b(Landroid/content/Context;Ljava/lang/String;Ljava/lang/String;)V
a=0;//
a=0;// const-string v1, "content.dat"
a=0;//
a=0;// invoke-static {p0, v0, v1}, Lcom/twocloooo/az;->a(Landroid/content/Context;Ljava/lang/String;Ljava/lang/String;)V
a=0;//
a=0;// :goto_0
a=0;// return-void
a=0;//
a=0;// :cond_0
a=0;// #v1=(Conflicted);
a=0;// const-string v0, "xpdatasuccess"
a=0;//
a=0;// const-string v1, "false"
a=0;//
a=0;// #v1=(Reference,Ljava/lang/String;);
a=0;// invoke-static {p0, v0, v1}, Lcom/twocloooo/bm;->b(Landroid/content/Context;Ljava/lang/String;Ljava/lang/String;)V
a=0;//
a=0;// goto :goto_0
a=0;// .end method
a=0;//
a=0;// .method public static a(Landroid/content/Context;Ljava/lang/String;Ljava/lang/String;)V
a=0;// .locals 4
a=0;//
a=0;// new-instance v0, Ljava/lang/StringBuilder;
a=0;//
a=0;// #v0=(UninitRef,Ljava/lang/StringBuilder;);
a=0;// invoke-static {}, Lcom/twocloooo/be;->a()Ljava/lang/String;
a=0;//
a=0;// move-result-object v1
a=0;//
a=0;// #v1=(Reference,Ljava/lang/String;);
a=0;// invoke-static {v1}, Ljava/lang/String;->valueOf(Ljava/lang/Object;)Ljava/lang/String;
a=0;//
a=0;// move-result-object v1
a=0;//
a=0;// invoke-direct {v0, v1}, Ljava/lang/StringBuilder;-><init>(Ljava/lang/String;)V
a=0;//
a=0;// #v0=(Reference,Ljava/lang/StringBuilder;);
a=0;// const-string v1, "/build/"
a=0;//
a=0;// invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
a=0;//
a=0;// move-result-object v0
a=0;//
a=0;// invoke-virtual {v0}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
a=0;//
a=0;// move-result-object v0
a=0;//
a=0;// new-instance v1, Ljava/io/File;
a=0;//
a=0;// #v1=(UninitRef,Ljava/io/File;);
a=0;// new-instance v2, Ljava/lang/StringBuilder;
a=0;//
a=0;// #v2=(UninitRef,Ljava/lang/StringBuilder;);
a=0;// invoke-static {v0}, Ljava/lang/String;->valueOf(Ljava/lang/Object;)Ljava/lang/String;
a=0;//
a=0;// move-result-object v3
a=0;//
a=0;// #v3=(Reference,Ljava/lang/String;);
a=0;// invoke-direct {v2, v3}, Ljava/lang/StringBuilder;-><init>(Ljava/lang/String;)V
a=0;//
a=0;// #v2=(Reference,Ljava/lang/StringBuilder;);
a=0;// invoke-virtual {v2, p2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
a=0;//
a=0;// move-result-object v2
a=0;//
a=0;// invoke-virtual {v2}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
a=0;//
a=0;// move-result-object v2
a=0;//
a=0;// invoke-direct {v1, v2}, Ljava/io/File;-><init>(Ljava/lang/String;)V
a=0;//
a=0;// #v1=(Reference,Ljava/io/File;);
a=0;// new-instance v2, Ljava/io/File;
a=0;//
a=0;// #v2=(UninitRef,Ljava/io/File;);
a=0;// invoke-direct {v2, v0}, Ljava/io/File;-><init>(Ljava/lang/String;)V
a=0;//
a=0;// #v2=(Reference,Ljava/io/File;);
a=0;// invoke-virtual {v2}, Ljava/io/File;->exists()Z
a=0;//
a=0;// move-result v0
a=0;//
a=0;// #v0=(Boolean);
a=0;// if-nez v0, :cond_0
a=0;//
a=0;// invoke-virtual {v2}, Ljava/io/File;->mkdir()Z
a=0;//
a=0;// :cond_0
a=0;// :try_start_0
a=0;// invoke-virtual {v1}, Ljava/io/File;->exists()Z
a=0;// :try_end_0
a=0;// .catch Ljava/lang/Exception; {:try_start_0 .. :try_end_0} :catch_1
a=0;//
a=0;// move-result v0
a=0;//
a=0;// if-nez v0, :cond_1
a=0;//
a=0;// :try_start_1
a=0;// invoke-virtual {v1}, Ljava/io/File;->createNewFile()Z
a=0;// :try_end_1
a=0;// .catch Ljava/io/IOException; {:try_start_1 .. :try_end_1} :catch_0
a=0;// .catch Ljava/lang/Exception; {:try_start_1 .. :try_end_1} :catch_1
a=0;//
a=0;// :cond_1
a=0;// :goto_0
a=0;// :try_start_2
a=0;// #v0=(Conflicted);
a=0;// new-instance v0, Ljava/io/FileOutputStream;
a=0;//
a=0;// #v0=(UninitRef,Ljava/io/FileOutputStream;);
a=0;// invoke-virtual {v1}, Ljava/io/File;->getAbsolutePath()Ljava/lang/String;
a=0;//
a=0;// move-result-object v1
a=0;//
a=0;// invoke-direct {v0, v1}, Ljava/io/FileOutputStream;-><init>(Ljava/lang/String;)V
a=0;//
a=0;// #v0=(Reference,Ljava/io/FileOutputStream;);
a=0;// invoke-virtual {p1}, Ljava/lang/String;->getBytes()[B
a=0;//
a=0;// move-result-object v1
a=0;//
a=0;// invoke-virtual {v0, v1}, Ljava/io/FileOutputStream;->write([B)V
a=0;//
a=0;// invoke-virtual {v0}, Ljava/io/FileOutputStream;->close()V
a=0;//
a=0;// :goto_1
a=0;// return-void
a=0;//
a=0;// :catch_0
a=0;// #v0=(Boolean);
a=0;// move-exception v0
a=0;//
a=0;// #v0=(Reference,Ljava/io/IOException;);
a=0;// invoke-virtual {v0}, Ljava/io/IOException;->printStackTrace()V
a=0;// :try_end_2
a=0;// .catch Ljava/lang/Exception; {:try_start_2 .. :try_end_2} :catch_1
a=0;//
a=0;// goto :goto_0
a=0;//
a=0;// :catch_1
a=0;// #v0=(Conflicted);
a=0;// move-exception v0
a=0;//
a=0;// #v0=(Reference,Ljava/lang/Exception;);
a=0;// invoke-virtual {v0}, Ljava/lang/Exception;->printStackTrace()V
a=0;//
a=0;// goto :goto_1
a=0;// .end method
a=0;//
a=0;// .method public static b(Landroid/content/Context;Ljava/lang/String;)Ljava/util/List;
a=0;// .locals 6
a=0;//
a=0;// new-instance v3, Ljava/util/ArrayList;
a=0;//
a=0;// #v3=(UninitRef,Ljava/util/ArrayList;);
a=0;// invoke-direct {v3}, Ljava/util/ArrayList;-><init>()V
a=0;//
a=0;// #v3=(Reference,Ljava/util/ArrayList;);
a=0;// invoke-static {p0, p1}, Lcom/twocloooo/az;->a(Landroid/content/Context;Ljava/lang/String;)Ljava/lang/String;
a=0;//
a=0;// move-result-object v0
a=0;//
a=0;// #v0=(Reference,Ljava/lang/String;);
a=0;// invoke-static {v0}, Lcom/twocloooo/a;->a(Ljava/lang/String;)[B
a=0;//
a=0;// move-result-object v0
a=0;//
a=0;// const-string v1, "dianjoy~~"
a=0;//
a=0;// #v1=(Reference,Ljava/lang/String;);
a=0;// invoke-static {v0, v1}, Lcom/twocloooo/bm;->a([BLjava/lang/String;)[B
a=0;//
a=0;// move-result-object v0
a=0;//
a=0;// invoke-static {v0}, Lcom/twocloooo/bn;->a([B)Ljava/lang/String;
a=0;//
a=0;// move-result-object v0
a=0;//
a=0;// const-string v1, ""
a=0;//
a=0;// if-ne v0, v1, :cond_0
a=0;//
a=0;// move-object v0, v3
a=0;//
a=0;// :goto_0
a=0;// #v1=(Conflicted);v2=(Conflicted);v4=(Conflicted);v5=(Conflicted);
a=0;// return-object v0
a=0;//
a=0;// :cond_0
a=0;// #v1=(Reference,Ljava/lang/String;);v2=(Uninit);v4=(Uninit);v5=(Uninit);
a=0;// new-instance v1, Lorg/json/JSONObject;
a=0;//
a=0;// #v1=(UninitRef,Lorg/json/JSONObject;);
a=0;// invoke-direct {v1, v0}, Lorg/json/JSONObject;-><init>(Ljava/lang/String;)V
a=0;//
a=0;// #v1=(Reference,Lorg/json/JSONObject;);
a=0;// if-nez v1, :cond_1
a=0;//
a=0;// move-object v0, v3
a=0;//
a=0;// goto :goto_0
a=0;//
a=0;// :cond_1
a=0;// const-string v0, "list"
a=0;//
a=0;// invoke-virtual {v1, v0}, Lorg/json/JSONObject;->get(Ljava/lang/String;)Ljava/lang/Object;
a=0;//
a=0;// move-result-object v0
a=0;//
a=0;// check-cast v0, Lorg/json/JSONArray;
a=0;//
a=0;// if-nez v0, :cond_2
a=0;//
a=0;// move-object v0, v3
a=0;//
a=0;// goto :goto_0
a=0;//
a=0;// :cond_2
a=0;// const/4 v1, 0x0
a=0;//
a=0;// #v1=(Null);
a=0;// move v2, v1
a=0;//
a=0;// :goto_1
a=0;// #v1=(Integer);v2=(Integer);v4=(Conflicted);v5=(Conflicted);
a=0;// invoke-virtual {v0}, Lorg/json/JSONArray;->length()I
a=0;//
a=0;// move-result v1
a=0;//
a=0;// if-lt v2, v1, :cond_3
a=0;//
a=0;// move-object v0, v3
a=0;//
a=0;// goto :goto_0
a=0;//
a=0;// :cond_3
a=0;// new-instance v4, Lcom/twocloooo/ay;
a=0;//
a=0;// #v4=(UninitRef,Lcom/twocloooo/ay;);
a=0;// invoke-direct {v4}, Lcom/twocloooo/ay;-><init>()V
a=0;//
a=0;// #v4=(Reference,Lcom/twocloooo/ay;);
a=0;// invoke-virtual {v0, v2}, Lorg/json/JSONArray;->get(I)Ljava/lang/Object;
a=0;//
a=0;// move-result-object v1
a=0;//
a=0;// #v1=(Reference,Ljava/lang/Object;);
a=0;// check-cast v1, Lorg/json/JSONObject;
a=0;//
a=0;// const-string v5, "id"
a=0;//
a=0;// #v5=(Reference,Ljava/lang/String;);
a=0;// invoke-virtual {v1, v5}, Lorg/json/JSONObject;->getString(Ljava/lang/String;)Ljava/lang/String;
a=0;//
a=0;// move-result-object v5
a=0;//
a=0;// iput-object v5, v4, Lcom/twocloooo/ay;->a:Ljava/lang/String;
a=0;//
a=0;// const-string v5, "image_url"
a=0;//
a=0;// invoke-virtual {v1, v5}, Lorg/json/JSONObject;->getString(Ljava/lang/String;)Ljava/lang/String;
a=0;//
a=0;// move-result-object v5
a=0;//
a=0;// iput-object v5, v4, Lcom/twocloooo/ay;->k:Ljava/lang/String;
a=0;//
a=0;// const-string v5, "ad_type"
a=0;//
a=0;// invoke-virtual {v1, v5}, Lorg/json/JSONObject;->getInt(Ljava/lang/String;)I
a=0;//
a=0;// move-result v5
a=0;//
a=0;// #v5=(Integer);
a=0;// invoke-static {v5}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;
a=0;//
a=0;// move-result-object v5
a=0;//
a=0;// #v5=(Reference,Ljava/lang/Integer;);
a=0;// iput-object v5, v4, Lcom/twocloooo/ay;->b:Ljava/lang/Integer;
a=0;//
a=0;// const-string v5, "download_url"
a=0;//
a=0;// invoke-virtual {v1, v5}, Lorg/json/JSONObject;->getString(Ljava/lang/String;)Ljava/lang/String;
a=0;//
a=0;// move-result-object v5
a=0;//
a=0;// iput-object v5, v4, Lcom/twocloooo/ay;->h:Ljava/lang/String;
a=0;//
a=0;// const-string v5, "x_offset"
a=0;//
a=0;// invoke-virtual {v1, v5}, Lorg/json/JSONObject;->getInt(Ljava/lang/String;)I
a=0;//
a=0;// move-result v5
a=0;//
a=0;// #v5=(Integer);
a=0;// invoke-static {v5}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;
a=0;//
a=0;// move-result-object v5
a=0;//
a=0;// #v5=(Reference,Ljava/lang/Integer;);
a=0;// iput-object v5, v4, Lcom/twocloooo/ay;->d:Ljava/lang/Integer;
a=0;//
a=0;// const-string v5, "x_offset"
a=0;//
a=0;// invoke-virtual {v1, v5}, Lorg/json/JSONObject;->getInt(Ljava/lang/String;)I
a=0;//
a=0;// move-result v5
a=0;//
a=0;// #v5=(Integer);
a=0;// invoke-static {v5}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;
a=0;//
a=0;// move-result-object v5
a=0;//
a=0;// #v5=(Reference,Ljava/lang/Integer;);
a=0;// iput-object v5, v4, Lcom/twocloooo/ay;->e:Ljava/lang/Integer;
a=0;//
a=0;// const-string v5, "content_name"
a=0;//
a=0;// invoke-virtual {v1, v5}, Lorg/json/JSONObject;->getString(Ljava/lang/String;)Ljava/lang/String;
a=0;//
a=0;// move-result-object v5
a=0;//
a=0;// iput-object v5, v4, Lcom/twocloooo/ay;->f:Ljava/lang/String;
a=0;//
a=0;// const-string v5, "download_packagename"
a=0;//
a=0;// invoke-virtual {v1, v5}, Lorg/json/JSONObject;->getString(Ljava/lang/String;)Ljava/lang/String;
a=0;//
a=0;// move-result-object v5
a=0;//
a=0;// iput-object v5, v4, Lcom/twocloooo/ay;->g:Ljava/lang/String;
a=0;//
a=0;// const-string v5, "context_packagename"
a=0;//
a=0;// invoke-virtual {v1, v5}, Lorg/json/JSONObject;->getString(Ljava/lang/String;)Ljava/lang/String;
a=0;//
a=0;// move-result-object v5
a=0;//
a=0;// iput-object v5, v4, Lcom/twocloooo/ay;->c:Ljava/lang/String;
a=0;//
a=0;// const-string v5, "html_text"
a=0;//
a=0;// invoke-virtual {v1, v5}, Lorg/json/JSONObject;->getString(Ljava/lang/String;)Ljava/lang/String;
a=0;//
a=0;// move-result-object v5
a=0;//
a=0;// iput-object v5, v4, Lcom/twocloooo/ay;->j:Ljava/lang/String;
a=0;//
a=0;// const-string v5, "title_text"
a=0;//
a=0;// invoke-virtual {v1, v5}, Lorg/json/JSONObject;->getString(Ljava/lang/String;)Ljava/lang/String;
a=0;//
a=0;// move-result-object v5
a=0;//
a=0;// iput-object v5, v4, Lcom/twocloooo/ay;->i:Ljava/lang/String;
a=0;//
a=0;// const-string v5, "force_download"
a=0;//
a=0;// invoke-virtual {v1, v5}, Lorg/json/JSONObject;->getInt(Ljava/lang/String;)I
a=0;//
a=0;// move-result v5
a=0;//
a=0;// #v5=(Integer);
a=0;// invoke-static {v5}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;
a=0;//
a=0;// move-result-object v5
a=0;//
a=0;// #v5=(Reference,Ljava/lang/Integer;);
a=0;// iput-object v5, v4, Lcom/twocloooo/ay;->l:Ljava/lang/Integer;
a=0;//
a=0;// const-string v5, "must_wifi"
a=0;//
a=0;// invoke-virtual {v1, v5}, Lorg/json/JSONObject;->getInt(Ljava/lang/String;)I
a=0;//
a=0;// move-result v1
a=0;//
a=0;// #v1=(Integer);
a=0;// invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;
a=0;//
a=0;// move-result-object v1
a=0;//
a=0;// #v1=(Reference,Ljava/lang/Integer;);
a=0;// iput-object v1, v4, Lcom/twocloooo/ay;->m:Ljava/lang/Integer;
a=0;//
a=0;// iget-object v1, v4, Lcom/twocloooo/ay;->l:Ljava/lang/Integer;
a=0;//
a=0;// invoke-virtual {v1}, Ljava/lang/Integer;->intValue()I
a=0;//
a=0;// move-result v1
a=0;//
a=0;// #v1=(Integer);
a=0;// const/4 v5, 0x1
a=0;//
a=0;// #v5=(One);
a=0;// if-ne v1, v5, :cond_4
a=0;//
a=0;// sget-object v1, Lcom/twocloooo/DevNativeService;->e:Ljava/util/List;
a=0;//
a=0;// #v1=(Reference,Ljava/util/List;);
a=0;// invoke-interface {v1, v4}, Ljava/util/List;->add(Ljava/lang/Object;)Z
a=0;//
a=0;// :cond_4
a=0;// #v1=(Conflicted);
a=0;// invoke-interface {v3, v4}, Ljava/util/List;->add(Ljava/lang/Object;)Z
a=0;//
a=0;// add-int/lit8 v1, v2, 0x1
a=0;//
a=0;// #v1=(Integer);
a=0;// move v2, v1
a=0;//
a=0;// goto/16 :goto_1
a=0;// .end method
}}
| true |
4558a9aa7b4e3c8ccb4f9c019a68a77d83a2046b | Java | witekrob/SpaceTravel | /SpaceTravel/src/main/java/com/witek/controller/FlightController.java | UTF-8 | 2,488 | 2.40625 | 2 | [] | no_license | package com.witek.controller;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.witek.model.Flight;
import com.witek.model.Tourist;
import com.witek.repo.FlightRepo;
import com.witek.service.FlightListService;
import com.witek.service.TouristService;
@Controller
public class FlightController {
private FlightListService flightService;
private TouristService touristService;
private FlightRepo flightRepo;
@Autowired
public FlightController(FlightListService fService, TouristService touristService, FlightRepo flightRepo) {
this.flightService = fService;
this.touristService = touristService;
this.flightRepo=flightRepo;
}
@GetMapping("/flights")
public String showAllFLights(Model model) {
Flight flight = new Flight();
List<Flight> flightsList = flightService.getListOfAllFlights();
model.addAttribute("flightsList", flightsList);
model.addAttribute("flight", flight);
return "allFlights";
}
@GetMapping("/showInfoAboutFlight")
public String showOneFlight(Long flightId, Model model) {
Flight flight = flightService.getOneFlightById(flightId);
model.addAttribute("flight", flight);
return "flightpage";
}
@PostMapping("/flights")
public String createNewFlight(@ModelAttribute Flight flight) {
flightService.createNewFLight(flight);
return "allFlights";
}
@GetMapping("/removeFromFlightList")
public String removeFromFlightList(HttpServletRequest request) {
String touristIdString = request.getParameter("tourist_id");
String flightIdString = request.getParameter("flightId");
System.out.println("PARAMETRY : " + touristIdString + " " + flightIdString);
Long tourist_id = Long.parseLong(touristIdString);
Long flightId = Long.parseLong(flightIdString);
System.out.println(tourist_id + " " + flightId);
Tourist tourist = touristService.getOneTouristById(tourist_id);
flightService.removeTouristFromFlight(tourist, flightId);
return "index";
}
}
| true |
6f2c3f443325cf35b3164957a6df92e35809e2f3 | Java | olwiley/StudyGroup__ | /app/src/main/java/edu/fsu/cs/mobile/studygroup_/joinGroup.java | UTF-8 | 794 | 2.046875 | 2 | [] | no_license | package edu.fsu.cs.mobile.studygroup_;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class joinGroup extends AppCompatActivity {
Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_join_group);
Button searchButton = (Button) findViewById(R.id.searchButton);
searchButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
intent = new Intent(joinGroup.this, joinGroup.class);
startActivity(intent);
}
});
}
}
| true |
cf8c37278a943d0cdc0d9eab12da264b3df89562 | Java | enaawy/gproject | /gp_JADX/com/google/wireless/android/finsky/dfe/nano/gm.java | UTF-8 | 2,315 | 1.726563 | 2 | [] | no_license | package com.google.wireless.android.finsky.dfe.nano;
import com.google.protobuf.nano.C7213a;
import com.google.protobuf.nano.CodedOutputByteBufferNano;
import com.google.protobuf.nano.b;
import com.google.protobuf.nano.i;
public final class gm extends b {
public int f39104a;
public String f39105b;
public String f39106c;
public String f39107d;
public gm() {
this.f39104a = 0;
this.f39105b = "";
this.f39106c = "";
this.f39107d = "";
this.aO = null;
this.aP = -1;
}
public final void m36514a(CodedOutputByteBufferNano codedOutputByteBufferNano) {
if ((this.f39104a & 1) != 0) {
codedOutputByteBufferNano.m33521a(1, this.f39105b);
}
if ((this.f39104a & 2) != 0) {
codedOutputByteBufferNano.m33521a(2, this.f39106c);
}
if ((this.f39104a & 4) != 0) {
codedOutputByteBufferNano.m33521a(3, this.f39107d);
}
super.a(codedOutputByteBufferNano);
}
protected final int m36515b() {
int b = super.b();
if ((this.f39104a & 1) != 0) {
b += CodedOutputByteBufferNano.m33493b(1, this.f39105b);
}
if ((this.f39104a & 2) != 0) {
b += CodedOutputByteBufferNano.m33493b(2, this.f39106c);
}
if ((this.f39104a & 4) != 0) {
return b + CodedOutputByteBufferNano.m33493b(3, this.f39107d);
}
return b;
}
public final /* synthetic */ i m36513a(C7213a c7213a) {
while (true) {
int a = c7213a.m33550a();
switch (a) {
case 0:
break;
case 10:
this.f39105b = c7213a.m33564f();
this.f39104a |= 1;
continue;
case 18:
this.f39106c = c7213a.m33564f();
this.f39104a |= 2;
continue;
case 26:
this.f39107d = c7213a.m33564f();
this.f39104a |= 4;
continue;
default:
if (!super.a(c7213a, a)) {
break;
}
continue;
}
return this;
}
}
}
| true |
bec89fe509d055f27566b6e8eb0b9331e0049697 | Java | seosain/RecycleView | /app/src/main/java/com/example/uts_angel/greeting_adapter.java | UTF-8 | 1,516 | 2.5625 | 3 | [] | no_license | package com.example.uts_angel;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
public class greeting_adapter extends RecyclerView.Adapter<greeting_adapter.MahasiswaViewHolder> {
private ArrayList<greeting> dataList;
public greeting_adapter(ArrayList<greeting> dataList) {
this.dataList = dataList;
}
@Override
public MahasiswaViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View view = layoutInflater.inflate(R.layout.greeting_bahasa, parent, false);
return new MahasiswaViewHolder(view);
}
@Override
public void onBindViewHolder(MahasiswaViewHolder holder, int position) {
holder.txtIndonesia.setText(dataList.get(position).getIndonesia());
holder.txtJepang.setText(dataList.get(position).getJepang());
}
@Override
public int getItemCount() {
return (dataList != null) ? dataList.size() : 0;
}
public class MahasiswaViewHolder extends RecyclerView.ViewHolder{
private TextView txtIndonesia, txtJepang;
public MahasiswaViewHolder(View itemView) {
super(itemView);
txtIndonesia = (TextView) itemView.findViewById(R.id.indonesia);
txtJepang = (TextView) itemView.findViewById(R.id.jepang);
}
}
}
| true |