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
646992aad2dca0df06a0a91f7f423eb3e255f53f
Java
Prashast09/retrofit_demo
/app/src/main/java/com/example/earthshaker/myapplication/GithubService.java
UTF-8
293
1.835938
2
[]
no_license
package com.example.earthshaker.myapplication; import java.util.List; import retrofit2.Call; import retrofit2.http.GET; /** * Created by earthshaker on 10/3/17. */ public interface GithubService { @GET("users/{user}/repo") public Call<List<GithubRepo>> getRepos(String user); }
true
337d6fd0ed05cfae9770c60dd1122eb8803f0ee6
Java
CkyZzzz/Leetcode
/297. Serialize and Deserialize Binary Tree/code.java
UTF-8
1,145
3.515625
4
[]
no_license
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Codec { private static final String SPLITER = ","; private static final String NAN = "#"; // Encodes a tree to a single string. public String serialize(TreeNode root) { if(root == null) return NAN; return root.val + SPLITER + serialize(root.left) + SPLITER + serialize(root.right); } // Decodes your encoded data to tree. public TreeNode deserialize(String data) { if(data.equals("")) return null; List<String> tempList = Arrays.asList(data.split(SPLITER)); Queue<String> queue = new LinkedList<>(); queue.addAll(tempList); return helper(queue); } private TreeNode helper(Queue<String> queue){ String curr = queue.poll(); if(curr.equals(NAN)) return null; TreeNode root = new TreeNode(Integer.valueOf(curr)); root.left = helper(queue); root.right = helper(queue); return root; } } // Your Codec object will be instantiated and called as such: // Codec codec = new Codec(); // codec.deserialize(codec.serialize(root));
true
4bc1d0bf1b20b88fe67d9fed2e12e3401a034492
Java
amitrajan012/LeetCode
/src/medium/UglyNumber2.java
UTF-8
457
3.328125
3
[]
no_license
package medium; import java.util.TreeSet; /* * https://leetcode.com/problems/ugly-number-ii/description/ */ public class UglyNumber2 { public int nthUglyNumber(int n) { TreeSet<Long> set = new TreeSet<Long>(); set.add(1l); for(int i=1;i<n;i++) { long first = set.pollFirst(); set.add(first*2); set.add(first*3); set.add(first*5); } return set.pollFirst().intValue(); } }
true
c5a209605a30dcc6e26678b27e362f770a3c07ee
Java
svenleonhard/aldi-api
/src/main/java/de/offersapp/aldiapi/service/dto/OfferCriteria.java
UTF-8
4,458
2.28125
2
[]
no_license
package de.offersapp.aldiapi.service.dto; import java.io.Serializable; import java.util.Objects; import io.github.jhipster.service.Criteria; import io.github.jhipster.service.filter.BooleanFilter; import io.github.jhipster.service.filter.DoubleFilter; import io.github.jhipster.service.filter.Filter; import io.github.jhipster.service.filter.FloatFilter; import io.github.jhipster.service.filter.IntegerFilter; import io.github.jhipster.service.filter.LongFilter; import io.github.jhipster.service.filter.StringFilter; import io.github.jhipster.service.filter.BigDecimalFilter; import io.github.jhipster.service.filter.LocalDateFilter; /** * Criteria class for the {@link de.offersapp.aldiapi.domain.Offer} entity. This class is used * in {@link de.offersapp.aldiapi.web.rest.OfferResource} to receive all the possible filtering options from * the Http GET request parameters. * For example the following could be a valid request: * {@code /offers?id.greaterThan=5&attr1.contains=something&attr2.specified=false} * As Spring is unable to properly convert the types, unless specific {@link Filter} class are used, we need to use * fix type specific filters. */ public class OfferCriteria implements Serializable, Criteria { private static final long serialVersionUID = 1L; private LongFilter id; private BigDecimalFilter advantage; private StringFilter amount; private LocalDateFilter startDate; private LocalDateFilter endDate; private LongFilter articleId; public OfferCriteria() { } public OfferCriteria(OfferCriteria other) { this.id = other.id == null ? null : other.id.copy(); this.advantage = other.advantage == null ? null : other.advantage.copy(); this.amount = other.amount == null ? null : other.amount.copy(); this.startDate = other.startDate == null ? null : other.startDate.copy(); this.endDate = other.endDate == null ? null : other.endDate.copy(); this.articleId = other.articleId == null ? null : other.articleId.copy(); } @Override public OfferCriteria copy() { return new OfferCriteria(this); } public LongFilter getId() { return id; } public void setId(LongFilter id) { this.id = id; } public BigDecimalFilter getAdvantage() { return advantage; } public void setAdvantage(BigDecimalFilter advantage) { this.advantage = advantage; } public StringFilter getAmount() { return amount; } public void setAmount(StringFilter amount) { this.amount = amount; } public LocalDateFilter getStartDate() { return startDate; } public void setStartDate(LocalDateFilter startDate) { this.startDate = startDate; } public LocalDateFilter getEndDate() { return endDate; } public void setEndDate(LocalDateFilter endDate) { this.endDate = endDate; } public LongFilter getArticleId() { return articleId; } public void setArticleId(LongFilter articleId) { this.articleId = articleId; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } final OfferCriteria that = (OfferCriteria) o; return Objects.equals(id, that.id) && Objects.equals(advantage, that.advantage) && Objects.equals(amount, that.amount) && Objects.equals(startDate, that.startDate) && Objects.equals(endDate, that.endDate) && Objects.equals(articleId, that.articleId); } @Override public int hashCode() { return Objects.hash( id, advantage, amount, startDate, endDate, articleId ); } // prettier-ignore @Override public String toString() { return "OfferCriteria{" + (id != null ? "id=" + id + ", " : "") + (advantage != null ? "advantage=" + advantage + ", " : "") + (amount != null ? "amount=" + amount + ", " : "") + (startDate != null ? "startDate=" + startDate + ", " : "") + (endDate != null ? "endDate=" + endDate + ", " : "") + (articleId != null ? "articleId=" + articleId + ", " : "") + "}"; } }
true
6c81e08381ca655c6fa0e19d93a95451db099f47
Java
josejlm2/HackathonEvents
/app/src/main/java/com/dreamtheimpossiblestudios/hackathonevents/MainActivity.java
UTF-8
6,942
2.25
2
[]
no_license
package com.dreamtheimpossiblestudios.hackathonevents; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.EditText; import android.widget.ListView; import android.widget.Toast; import com.parse.FindCallback; import com.parse.Parse; import com.parse.ParseException; import com.parse.ParseObject; import com.parse.ParseQuery; import java.util.ArrayList; import java.util.List; public class MainActivity extends ActionBarActivity { private EditText mHackInput; private ListView mListView; private HackAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //initialize parse Parse.enableLocalDatastore(this); // Enable Local Datastore Parse.initialize(this, "SlkykJCMuwaB3A9kA1E0iaAGXmxyiWWbHqF2Pxes", "rwJHOyXjGhe6Gr97UfOguHuLtt5ucNxIZhdYFuHq"); ParseObject.registerSubclass(Hackathon.class); //register class with activity mAdapter = new HackAdapter(this, new ArrayList<Hackathon>()); mHackInput = (EditText) findViewById(R.id.hackathon_input); mListView = (ListView) findViewById(R.id.theListView); mListView.setAdapter(mAdapter); // mListView.setOnItemClickListener(this); // updateData(); updateData2(); /* // Simple array with a list of my favorite TV shows String[] favoriteTVShows = {"Pushing Daisies", "Better Off Ted", "Twin Peaks", "Freaks and Geeks", "Orphan Black", "Walking Dead", "Breaking Bad", "The 400", "Alphas", "Life on Mars"}; // A View is the generic term and class for every widget you put on your screen. // Views occupy a rectangular area and are responsible for handling events // and drawing the widget. // The ListAdapter acts as a bridge between the data and each ListItem // You fill the ListView with a ListAdapter. You pass it a context represented by // this. // A Context provides access to resources you need. It provides the current Context, or // facts about the app and the events that have occurred with in it. // android.R.layout.simple_list_item_1 is one of the resources needed. // It is a predefined layout provided by Android that stands in as a default ListAdapter theAdapter = new MyAdapter(this,favoriteTVShows); // We point the ListAdapter to our custom adapter // ListAdapter theAdapter = new MyAdapter(this, favoriteTVShows); // Get the ListView so we can work with it ListView theListView = (ListView) findViewById(R.id.theListView); // Connect the ListView with the Adapter that acts as a bridge between it and the array theListView.setAdapter(theAdapter); */ mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { String tvShowPicked = "You selected " + String.valueOf(adapterView.getItemAtPosition(i)); Toast.makeText(MainActivity.this, tvShowPicked, Toast.LENGTH_SHORT).show(); } }); } public void createHackathon(View v) { if (mHackInput.getText().length() > 0){ Hackathon t = new Hackathon(); t.setName(mHackInput.getText().toString()); Log.d("TEST", mHackInput.getText().toString()); t.setLocation(""); t.saveEventually(); mAdapter.insert(t, 0); //inserts new info into views mHackInput.setText(""); } HackAdapter mAdapter = new HackAdapter(this, new ArrayList<Hackathon>()); mListView.setAdapter(mAdapter); } public void updateData2(){ ParseQuery<Hackathon> query = ParseQuery.getQuery(Hackathon.class); query.findInBackground(new FindCallback<Hackathon>() { @Override public void done(List<Hackathon> tasks, ParseException error) { if(tasks != null){ mAdapter.clear(); mAdapter.addAll(tasks); } } }); } public void updateData(){ ParseQuery<Hackathon> query = ParseQuery.getQuery(Hackathon.class); //query.whereEqualTo("user", ParseUser.getCurrentUser()); query.setCachePolicy(ParseQuery.CachePolicy.CACHE_THEN_NETWORK); query.findInBackground(new FindCallback<Hackathon>() { @Override public void done(List<Hackathon> tasks, ParseException error) { if(tasks != null){ //mAdapter.clear(); for (int i = 0; i < tasks.size(); i++) { Log.d("DATA?", tasks.get(i).getName()); mAdapter.add(tasks.get(i)); } } } }); /* ParseQuery<Hackathon> query = ParseQuery.getQuery(Hackathon.class); query.findInBackground(new FindCallback<Hackathon>() { @Override public void done(List<Hackathon> tasks, ParseException error) { if(tasks != null){ //mAdapter.clear(); //mAdapter.addAll(tasks); } } });*/ } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main, menu); // Inflate the menu; this adds items to the action bar if it is present. 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(); if (id == R.id.action_settings) { //noinspection SimplifiableIfStatement return true; } return super.onOptionsItemSelected(item); } }
true
3ee7e389d617dd1c90ddb0df36099ab59fbd4f66
Java
Sorridian/BroDudeAdventure
/src/finalProject/Frame.java
UTF-8
1,112
3.5
4
[]
no_license
package finalProject; import javax.swing.JFrame; /** *Creates a frame that will call a method to draw a level and a character into the frame, then allow the player to move left or right in the window. *We used a tutorial to help get us started and understand how to create the methods and classes required to make the character move in the window. *We will use this tutorial as our jumping off point. *@author Derek Borden, Stephen Marsh and Charles Dieffenbach *@date 11/10/2013 *@course CIS 111B Online *@instructor Dr. Kendall Martin * */ public class Frame { public static void main(String[] args) { new Frame(); } //Create a frame with a specific size to build the level for the character to interact with. //Calls the GameWorld method to get the information and images for the background and character //Have a way to exit the game, by closing the window public Frame() { JFrame frame = new JFrame("BroDude Adventure"); frame.add(new GameWorld()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(1152, 695); frame.setLocationRelativeTo(null); frame.setVisible(true); } }
true
0e175bdda85baf647c7271cb9a49dbb7d3400228
Java
fraziercs2i/Datastructure-in-Java
/MP2/src/main/java/de/tukl/programmierpraktikum2020/mp2/functions/Exp.java
UTF-8
520
3.09375
3
[]
no_license
package de.tukl.programmierpraktikum2020.mp2.functions; public class Exp implements Function { Function funktion; public Exp(Function funktion) { this.funktion = funktion; } @Override public String toString() { return ("exp(" + funktion.toString() + ")"); } @Override public double apply(double x) { return Math.exp(funktion.apply(x)); } @Override public Function derive() { return new Mult(funktion.derive(), new Exp(funktion)); } }
true
15347e1ddcbe7453c3e31ccc6414a3724a9eecd2
Java
abionics/Denumberizator
/src/main/java/com/abionics/denumberizator/Main.java
UTF-8
727
2.3125
2
[]
no_license
package com.abionics.denumberizator; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; import org.jetbrains.annotations.NotNull; public class Main extends Application { @Override public void start(@NotNull Stage primaryStage) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("/denumberizator.fxml")); primaryStage.setTitle("Denumberizator"); primaryStage.setScene(new Scene(root, 1000, 685)); primaryStage.setOnCloseRequest(t -> Controller.exit()); primaryStage.show(); } public static void main(String[] args) { launch(args); } }
true
a166f7522a86b1f730e2294551a6edf017de38bf
Java
dinudelia/OnlineTickets-Java
/src/main/java/model/Client.java
UTF-8
717
2.796875
3
[]
no_license
package model; import java.util.ArrayList; import java.util.List; public class Client extends User{ private List<Order> orders= new ArrayList<Order>(); private int seniority; public Client(Integer idUser,String username, String password, String firstName, String lastName, int seniority) { super(idUser, username, password, firstName, lastName); this.seniority = seniority; } public int getSeniority(){ return seniority; } public void setSeniority(int seniority){ this.seniority = seniority; } public List<Order> getOrders() { return orders; } public void setOrders(List<Order> orders) { this.orders = orders; } }
true
fb3d43f19bc9981b026d732e87414a2304beb3c8
Java
futuremakers/DarkCastleConsole
/src/test/java/com/yaa/rpg/playit/theme/color/ColorTest.java
UTF-8
149
1.867188
2
[]
no_license
package com.yaa.rpg.playit.theme.color; public class ColorTest { public static void main(String[] args) { System.out.println(Color.BLACK); } }
true
4f5db696659cb0f62cd65912999c7d1b240a7e83
Java
Sage-ERP-X3/izpack
/src/lib/com/izforge/izpack/util/OsVersion.java
UTF-8
18,078
2.25
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* * IzPack - Copyright 2001-2008 Julien Ponge, All Rights Reserved. * * http://izpack.org/ http://izpack.codehaus.org/ * * Copyright 2004 Hani Suleiman * * 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.izforge.izpack.util; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Iterator; /** * This is a convienient class, which helps you to detect / identify the running OS/Distribution * <p/> * Created at: Date: Nov 9, 2004 Time: 8:53:22 PM * * @author hani, Marc.Eppelmann&#064;reddot.de */ public final class OsVersion implements OsVersionConstants, StringConstants { // ~ Static fields/initializers // ******************************************************************************************************************************* /** * OS_NAME = System.getProperty( "os.name" ) */ public static final String OS_NAME = System.getProperty(OSNAME); /** * OS_ARCH = System.getProperty("os.arch") */ public static final String OS_ARCH = System.getProperty(OSARCH); /** * True if the processor is in the Intel x86 family. */ public static final boolean IS_X86 = (StringTool.startsWithIgnoreCase(OS_ARCH, X86) && !StringTool.startsWithIgnoreCase(OS_ARCH, X86_64)) || StringTool.startsWithIgnoreCase(OS_ARCH, I386); /** * True if the processor is in the Intel x86_64 family. */ public static final boolean IS_X86_64 = StringTool.startsWithIgnoreCase(OS_ARCH, X86_64) || StringTool.startsWithIgnoreCase(OS_ARCH, AMD64); /** * True if the processor is in the PowerPC family. */ public static final boolean IS_PPC = StringTool.startsWithIgnoreCase(OS_ARCH, PPC); /** * True if the processor is in the SPARC family. */ public static final boolean IS_SPARC = StringTool.startsWithIgnoreCase(OS_ARCH, SPARC); /** * True if this is FreeBSD. */ public static final boolean IS_FREEBSD = StringTool.startsWithIgnoreCase(OS_NAME, FREEBSD); /** * True if this is Linux. */ public static final boolean IS_LINUX = StringTool.startsWithIgnoreCase(OS_NAME, LINUX); /** * True if this is HP-UX. */ public static final boolean IS_HPUX = StringTool.startsWithIgnoreCase(OS_NAME, HP_UX); /** * True if this is AIX. */ public static final boolean IS_AIX = StringTool.startsWithIgnoreCase(OS_NAME, AIX); /** * True if this is SunOS. */ public static final boolean IS_SUNOS = StringTool.startsWithIgnoreCase(OS_NAME, SUNOS) || StringTool.startsWithIgnoreCase(OS_NAME, SOLARIS); /** * True if this is SunOS / x86 */ public static final boolean IS_SUNOS_X86 = IS_SUNOS && IS_X86; /** * True if this is SunOS / sparc */ public static final boolean IS_SUNOS_SPARC = IS_SUNOS && IS_SPARC; /** * True if this is OS/2. */ public static final boolean IS_OS2 = StringTool.startsWith(OS_NAME, OS_2); /** * True is this is Mac OS */ public static final boolean IS_MAC = StringTool.startsWith(OS_NAME, MAC); /** * True if this is the Mac OS X. */ public static final boolean IS_OSX = StringTool.startsWithIgnoreCase(OS_NAME, MACOSX); /** * True if this is Windows. */ public static final boolean IS_WINDOWS = StringTool.startsWith(OS_NAME, WINDOWS); /** * True if this is Windows 2000 */ public static final boolean IS_WINDOWS_2000 = StringTool.startsWithIgnoreCase(OS_NAME, WINDOWS_2000_NAME); /** * True if this is Windows XP */ public static final boolean IS_WINDOWS_XP = StringTool.startsWithIgnoreCase(OS_NAME, WINDOWS_XP_NAME); // IS_WINDOWS && OS_VERSION.equals(WINDOWS_XP_VERSION); /** * True if this is Windows 2003 */ public static final boolean IS_WINDOWS_2003 = StringTool.startsWithIgnoreCase(OS_NAME, WINDOWS_2003_NAME); // IS_WINDOWS && OS_VERSION.equals(WINDOWS_2003_VERSION); /** * True if this is Windows VISTA */ public static final boolean IS_WINDOWS_VISTA = StringTool.startsWithIgnoreCase(OS_NAME, WINDOWS_VISTA_NAME); // IS_WINDOWS && OS_VERSION.equals(WINDOWS_VISTA_VERSION); /** * True if this is Windows 7 */ public static final boolean IS_WINDOWS_7 = StringTool.startsWithIgnoreCase(OS_NAME, WINDOWS_7_NAME); // IS_WINDOWS && OS_VERSION.equals(WINDOWS_7_VERSION); /** * True if this is Windows 7 */ public static final boolean IS_WINDOWS_8 = StringTool.startsWithIgnoreCase(OS_NAME, WINDOWS_8_NAME); /** * True if this is some variant of Unix (OSX, Linux, Solaris, FreeBSD, etc). */ public static final boolean IS_UNIX = !IS_OS2 && !IS_WINDOWS; /** * True if CentOS Linux was detected */ public static final boolean IS_CENTOS_LINUX = IS_LINUX && FileUtil.fileContains("/etc/centos-release", CENTOS); /** * True if Oracle Linux was detected */ public static final boolean IS_ORACLE_LINUX = IS_LINUX && ((FileUtil.fileContains("/etc/oracle-release", ORACLE) || FileUtil.fileContains("/etc/oracle-release", EL))); /** * True if RedHat Linux was detected */ public static final boolean IS_REDHAT_LINUX = IS_LINUX && !IS_CENTOS_LINUX && !IS_ORACLE_LINUX && ((FileUtil.fileContains("/etc/redhat-release", REDHAT) || FileUtil.fileContains("/etc/redhat-release", RED_HAT))); /** * True if Fedora Linux was detected */ public static final boolean IS_FEDORA_LINUX = IS_LINUX && FileUtil.fileContains("/etc/fedora-release", FEDORA); /** * True if Ubuntu Linux was detected */ public static final boolean IS_UBUNTU_LINUX = IS_LINUX && FileUtil.fileContains("/etc/lsb-release", UBUNTU); /** * True if Mandriva(Mandrake) Linux was detected */ public static final boolean IS_MANDRAKE_LINUX = IS_LINUX && FileUtil.fileContains("/etc/mandrake-release", MANDRAKE); /** * True if Amazon AMI Linux was detected */ public static final boolean IS_AMI_LINUX = IS_LINUX && FileUtil.fileContains(getReleaseFileName(), AMI); /** * True if Mandrake/Mandriva Linux was detected */ public static final boolean IS_MANDRIVA_LINUX = (IS_LINUX && FileUtil.fileContains(getReleaseFileName(), MANDRIVA)) || IS_MANDRAKE_LINUX; /** * True if SuSE Linux was detected */ public static final boolean IS_SUSE_LINUX = IS_LINUX && FileUtil.fileContains(getReleaseFileName(), SUSE, true); /* caseInsensitive , since 'SUSE' 10 */ /** * True if Debian Linux or derived was detected */ public static final boolean IS_DEBIAN_LINUX = (IS_LINUX && FileUtil.fileContains(PROC_VERSION, DEBIAN)) || (IS_LINUX && new File("/etc/debian_version").exists()); /** * OS_VERSION = System.getProperty("os.version") */ public static final String OS_VERSION = (IS_LINUX) ? getLinuxversion() : System.getProperty(OSVERSION); /** * MACHINE_ID = /etc/machine_id || /var/lib/dbus/machine_id */ public static final String MACHINE_ID = getLinuxMachineId(); /** * MACHINE_ID_REGISTERED = Machine_ID != null */ public static final boolean MACHINE_ID_REGISTERED = IS_LINUX && (MACHINE_ID != null); /** * True if this is Windows 2008 */ public static final boolean IS_WINDOWS_2008 = StringTool.startsWithIgnoreCase(OS_NAME, WINDOWS_2008_NAME) && StringTool.equalsWithIgnoreCase(OS_VERSION, WINDOWS_2008_VERSION); /** * True if this is Windows 2008R2 */ public static final boolean IS_WINDOWS_2008R2 = StringTool.startsWithIgnoreCase(OS_NAME, WINDOWS_2008R2_NAME) && StringTool.equalsWithIgnoreCase(OS_VERSION, WINDOWS_2008R2_VERSION); // TODO detect the newcomer (K)Ubuntu */ // ~ Methods // ************************************************************************************************************************************************** /** * Gets the etc Release Filename * * @return name of the file the release info is stored in for Linux distributions */ private static String getReleaseFileName() { String result = ""; File[] etcList = new File("/etc").listFiles(); if (etcList != null) { for (File etcEntry : etcList) { if (etcEntry.isFile()) { if (etcEntry.getName().endsWith("-release")) { // match :-) return result = etcEntry.toString(); } } } } return result; } private static String getLinuxMachineId() { String result = null; File machineIdFile = new File("/var/lib/dbus/machine-id"); try { if (!machineIdFile.exists()) machineIdFile = new File("/etc/machine-id"); if (machineIdFile.exists()) result = (String) FileUtil.getFileContent(machineIdFile.getAbsolutePath()).get(0); } catch (Exception ex) { ex.printStackTrace(); } return result; } /* * Samples: * Red Hat/older CentOS: * $ cat /etc/redhat-release * CentOS release 5.3 (Final) * * newer CentOS: * $ cat /etc/centos-release * CentOS Linux release 7.1.1503 (Core) * * $ more /etc/lsb-release * DISTRIB_ID=Ubuntu * DISTRIB_RELEASE=16.04 * DISTRIB_CODENAME=xenial * DISTRIB_DESCRIPTION="Ubuntu 16.04.2 LTS" * * @return version number with the pattern $MAJOR.$MINOR.$SECURITY. * Ex: "16.04.2", "5.3", "7.1.1503", etc ... */ private static String getLinuxVersionFromFile(String strReleaseFile) { final String regex = "^(?:(\\d+)\\.)?(?:(\\d+)\\.)?(\\*|\\d+)$"; String result = null; try { ArrayList lstLines = FileUtil.getFileContent(strReleaseFile); Iterator linesIter = lstLines.iterator(); while (linesIter.hasNext()) { String strline = (String) linesIter.next(); String[] strPattern = strline.trim().split(" |="); for (int i = 0; i < strPattern.length; i++) { // result = Float.valueOf(strPattern[i]).toString(); // Improvement to manage version string like $MAJOR.$MINOR.$SECURITY like "16.04.09" // Full match 0-8 `16.04.09` Group 1. 0-2 `16` Group 2. 3-5 `04` Group 3. 6-8 `09` if (strPattern[i].matches(regex)) { result = strPattern[i]; break; } } } } catch (Exception e1) { // TODO handle Exception e1.printStackTrace(); } return result; } private static String getLinuxversion() { String result = null; if (IS_SUSE_LINUX) { result = getLinuxVersionFromFile("/etc/sles-release"); if (result == null) result = getLinuxVersionFromFile("/etc/novell-release"); if (result == null) result = getLinuxVersionFromFile("/etc/SuSE-release"); } else if (IS_UBUNTU_LINUX) { // $ more /etc/lsb-release // DISTRIB_ID=Ubuntu // DISTRIB_RELEASE=16.04 // DISTRIB_CODENAME=xenial // DISTRIB_DESCRIPTION="Ubuntu 16.04.2 LTS" result = getLinuxVersionFromFile("/etc/lsb-release"); } else if (IS_REDHAT_LINUX) { result = getLinuxVersionFromFile("/etc/redhat-release"); } else if (IS_CENTOS_LINUX) { // Red Hat/older CentOS: $ cat /etc/redhat-release // CentOS release 5.3 (Final) // newer CentOS: $ cat /etc/centos-release // CentOS Linux release 7.1.1503 (Core) result = getLinuxVersionFromFile("/etc/centos-release"); } else if (IS_ORACLE_LINUX) { result = getLinuxVersionFromFile("/etc/oracle-release"); } else if (IS_FEDORA_LINUX) { // Fedora: $ cat /etc/fedora-release // Fedora release 10 (Cambridge) result = getLinuxVersionFromFile("/etc/fedora-release"); } else if (IS_MANDRAKE_LINUX) { result = getLinuxVersionFromFile("/etc/mandrake-release"); } else if (IS_MANDRIVA_LINUX) { result = getLinuxVersionFromFile("/etc/mandriva-release"); if (result == null) result = getLinuxVersionFromFile("/etc/mandrake-release"); if (result == null) result = getLinuxVersionFromFile("/etc/mandrakelinux-release"); } else if (IS_DEBIAN_LINUX) { // $ cat /etc/debian_version // 5.0.2 result = getLinuxVersionFromFile("/etc/debian_version"); } else { result = getLinuxVersionFromFile(getReleaseFileName()); } return result; } /** * Gets the Details of a Linux Distribution * * @return description string of the Linux distribution * Ex: Red Hat 7.2, SuSE * Linux 15.3 */ public static String getLinuxDistribution() { String result = null; if (IS_SUSE_LINUX) { try { result = SUSE + SP + LINUX + NL + StringTool.stringArrayListToString(FileUtil.getFileContent(getReleaseFileName())); } catch (IOException e) { // TODO ignore } } else if (IS_UBUNTU_LINUX) { try { result = UBUNTU + SP + LINUX + NL + getLinuxversion(); // NOOK: java.lang.ArrayIndexOutOfBoundsException: // result = (String)FileUtil.getFileContent(getReleaseFileName()).get(3); // result = result.split("\"")[1]; } catch (Exception e) { // TODO ignore } } else if (IS_REDHAT_LINUX) { try { result = REDHAT + SP + LINUX + NL + StringTool.stringArrayListToString(FileUtil.getFileContent("/etc/redhat-release")); } catch (IOException e) { // TODO ignore } } else if (IS_CENTOS_LINUX) { try { result = CENTOS + SP + LINUX + NL + StringTool.stringArrayListToString(FileUtil.getFileContent("/etc/centos-release")); } catch (IOException e) { // TODO ignore } } else if (IS_ORACLE_LINUX) { try { result = ORACLE + SP + LINUX + NL + StringTool.stringArrayListToString(FileUtil.getFileContent("/etc/oracle-release")); } catch (IOException e) { // TODO ignore } } else if (IS_FEDORA_LINUX) { try { result = FEDORA + SP + LINUX + NL + StringTool.stringArrayListToString(FileUtil.getFileContent(getReleaseFileName())); } catch (IOException e) { // TODO ignore } } else if (IS_MANDRAKE_LINUX) { try { result = MANDRAKE + SP + LINUX + NL + StringTool.stringArrayListToString(FileUtil.getFileContent(getReleaseFileName())); } catch (IOException e) { // TODO ignore } } else if (IS_MANDRIVA_LINUX) { try { result = MANDRIVA + SP + LINUX + NL + StringTool.stringArrayListToString(FileUtil.getFileContent(getReleaseFileName())); } catch (IOException e) { // TODO ignore } } else if (IS_DEBIAN_LINUX) { try { result = DEBIAN + SP + LINUX + NL + StringTool.stringArrayListToString(FileUtil.getFileContent("/etc/debian_version")); } catch (IOException e) { // TODO ignore } } else { try { result = "Unknown Linux Distribution\n" + StringTool.stringArrayListToString(FileUtil.getFileContent(getReleaseFileName())); } catch (IOException e) { // TODO ignore } } return result; } /** * returns a String which contains details of known OSs * * @return the details */ public static String getOsDetails() { StringBuffer result = new StringBuffer(); result.append("OS_NAME=").append(OS_NAME).append(NL); if (IS_UNIX) { if (IS_LINUX) { result.append(getLinuxDistribution()).append(NL); } else { try { result.append(FileUtil.getFileContent(getReleaseFileName())).append(NL); } catch (IOException e) { Debug.log("Unable to get release file contents in 'getOsDetails'."); } } } if (IS_WINDOWS) { result.append(System.getProperty(OSNAME)).append(SP).append(System.getProperty("sun.os.patch.level", "")).append(NL); } return result.toString(); } /** * Testmain * * @param args * Commandline Args */ public static void main(String[] args) { System.out.println(getOsDetails()); } }
true
6c8f2d607e7bd97336c028fdc94c3f68c47c11a9
Java
Furzoom/demo-J
/thinkInJava/TIJ/src/com/furzoom/lab/ch9/E02.java
UTF-8
806
3.09375
3
[]
no_license
/** * Description : E02, E03 * Author : mn@furzoom.com * Date : Jun 28, 2016 2:36:56 PM * Copyright (c) 2013-2016, http://furzoom.com All Rights Reserved. */ package com.furzoom.lab.ch9; /** * ClassName : E02 <br> * Function : TODO ADD FUNCTION. <br> * Reason : TODO ADD REASON. <br> * date : Jun 28, 2016 2:36:56 PM <br> * * @author furzoom * @version */ public class E02 { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub Base base; // error //base = new Base(); base = new Derived(); base.print(); } } abstract class Base { public Base() { print(); } public abstract void print(); } class Derived extends Base { private int a = 10; public void print() { System.out.println(a); } }
true
1e780797cad5b932ce33cb481596e466a1803792
Java
a2en/Zenly_re
/src/app.zenly.locator_4.8.0_base_source_from_JADX/sources/zendesk/support/guide/HelpCenterModel.java
UTF-8
1,266
1.742188
2
[]
no_license
package zendesk.support.guide; import com.zendesk.service.C12008e; import java.util.List; import zendesk.support.HelpCenterProvider; import zendesk.support.HelpCenterSearch.Builder; import zendesk.support.SearchArticle; import zendesk.support.SupportSdkSettings; import zendesk.support.SupportSettingsProvider; class HelpCenterModel implements HelpCenterMvp$Model { private final HelpCenterProvider provider; private final SupportSettingsProvider settingsProvider; HelpCenterModel(HelpCenterProvider helpCenterProvider, SupportSettingsProvider supportSettingsProvider) { this.provider = helpCenterProvider; this.settingsProvider = supportSettingsProvider; } public void getSettings(C12008e<SupportSdkSettings> eVar) { this.settingsProvider.getSettings(eVar); } public void search(List<Long> list, List<Long> list2, String str, String[] strArr, C12008e<List<SearchArticle>> eVar) { HelpCenterProvider helpCenterProvider = this.provider; Builder builder = new Builder(); builder.withQuery(str); builder.withCategoryIds(list); builder.withSectionIds(list2); builder.withLabelNames(strArr); helpCenterProvider.searchArticles(builder.build(), eVar); } }
true
324914b3fa98d180a0d58719f81f51eac61be17f
Java
soy6032/JAVA
/ch07/src/ch07/A.java
UHC
418
2.84375
3
[]
no_license
package ch07; public class A { // protected Ͽ ӹ ü (ܺ Ű ) // ڰ protected protected String field; // ڰ protected protected A() { } // ڰ protected ޼ protected void method() { } }
true
d8245122b9b0bd35f5b9601e80fca42fc513e79a
Java
sarahaabed/Java-chat-Application
/client/src/pkg1/conversation.java
UTF-8
23,377
1.914063
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package pkg1; import java.awt.Color; import java.awt.Font; import static java.awt.Font.BOLD; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Date; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import javax.naming.spi.ObjectFactory; import javax.swing.ImageIcon; import javax.swing.JColorChooser; import javax.swing.JFileChooser; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBElement; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import model.Contact; import model.Message; import model.Room; import model.User; import view.ClientInputHandler; import view.IClientInputHandler; /** * * @author Radwa Manssour */ public class conversation extends javax.swing.JFrame { /** * Creates new form conversation */ private String roomId; private Room room; private User user; chatCui gui; public void setRoom(Room room) { this.room = room; name.setText(room.contactVector.get(1).getName()); } public Room getRoom() { return room; } public void setRoomId(String roomId) { this.roomId = roomId; } public String getRoomId() { return roomId; } public conversation(chatCui gui) { //super(parent, modal); initComponents(); this.user=gui.user; setSize(700, 700); this.gui = gui; } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel2 = new javax.swing.JPanel(); img1 = new javax.swing.JLabel(); name = new javax.swing.JLabel(); jScrollPane3 = new javax.swing.JScrollPane(); text2 = new javax.swing.JTextArea(); send1 = new javax.swing.JButton(); jPanel3 = new javax.swing.JPanel(); jScrollPane4 = new javax.swing.JScrollPane(); text1 = new javax.swing.JTextArea(); saveMessage = new javax.swing.JButton(); attach2 = new javax.swing.JButton(); jComboBox2 = new javax.swing.JComboBox(); attach1 = new javax.swing.JButton(); color = new javax.swing.JButton(); jTextField1 = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); fontChooserComboBox = new javax.swing.JComboBox(); jButton1 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setBackground(new java.awt.Color(25, 173, 250)); jPanel2.setBackground(new java.awt.Color(25, 173, 250)); jPanel2.setMaximumSize(new java.awt.Dimension(2147483647, 2147483647)); jPanel2.setMinimumSize(new java.awt.Dimension(0, 0)); jPanel2.setPreferredSize(new java.awt.Dimension(450, 426)); img1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pkg1/Person_1.png"))); // NOI18N img1.setText("jLabel1"); name.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N name.setForeground(new java.awt.Color(255, 255, 255)); name.setText("name"); text2.setColumns(20); text2.setRows(5); jScrollPane3.setViewportView(text2); send1.setBackground(new java.awt.Color(25, 173, 250)); send1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N send1.setForeground(new java.awt.Color(255, 255, 255)); send1.setText("send"); send1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { send1ActionPerformed(evt); } }); jPanel3.setMaximumSize(new java.awt.Dimension(20, 20)); jPanel3.setMinimumSize(new java.awt.Dimension(20, 20)); jPanel3.setLayout(new javax.swing.BoxLayout(jPanel3, javax.swing.BoxLayout.LINE_AXIS)); text1.setColumns(20); text1.setRows(5); jScrollPane4.setViewportView(text1); saveMessage.setBackground(new java.awt.Color(63, 129, 179)); saveMessage.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N saveMessage.setForeground(new java.awt.Color(255, 255, 255)); saveMessage.setText("save"); saveMessage.setMaximumSize(new java.awt.Dimension(100, 35)); saveMessage.setMinimumSize(new java.awt.Dimension(0, 0)); saveMessage.setPreferredSize(new java.awt.Dimension(100, 35)); saveMessage.setRolloverEnabled(false); saveMessage.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { saveMessageActionPerformed(evt); } }); attach2.setMaximumSize(new java.awt.Dimension(35, 35)); attach2.setMinimumSize(new java.awt.Dimension(0, 0)); attach2.setPreferredSize(new java.awt.Dimension(35, 35)); attach2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { attach2ActionPerformed(evt); } }); jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); attach1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pkg1/file_1.png"))); // NOI18N attach1.setMaximumSize(new java.awt.Dimension(35, 35)); attach1.setMinimumSize(new java.awt.Dimension(0, 35)); attach1.setPreferredSize(new java.awt.Dimension(35, 35)); attach1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { attach1ActionPerformed(evt); } }); color.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pkg1/colorgrid.gif"))); // NOI18N color.setText("jButton1"); color.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { colorActionPerformed(evt); } }); jTextField1.setBackground(new java.awt.Color(191, 225, 252)); jTextField1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jTextField1.setForeground(new java.awt.Color(0, 170, 240)); jTextField1.setText("write status"); jTextField1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jTextField1ActionPerformed(evt); } }); jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setText("status"); fontChooserComboBox.setBackground(new java.awt.Color(63, 129, 179)); fontChooserComboBox.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N fontChooserComboBox.setForeground(new java.awt.Color(255, 255, 255)); fontChooserComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "fonts" })); fontChooserComboBox.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { fontChooserComboBoxActionPerformed(evt); } }); jButton1.setBackground(new java.awt.Color(63, 129, 179)); jButton1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N jButton1.setForeground(new java.awt.Color(255, 255, 255)); jButton1.setText("add member"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(img1, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 201, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, 165, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(178, Short.MAX_VALUE)) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel2Layout.createSequentialGroup() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(4, 4, 4) .addComponent(attach1, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(color, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(fontChooserComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 116, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(saveMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jScrollPane4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(send1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))) .addComponent(jScrollPane3)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 166, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(438, 438, 438) .addComponent(attach2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jComboBox2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE))))) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(name, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(img1) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(192, 192, 192) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(22, 22, 22) .addComponent(jComboBox2, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(143, 143, 143) .addComponent(attach2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addGap(8, 8, 8) .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 170, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(14, 14, 14) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(attach1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jButton1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(saveMessage, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(fontChooserComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(color, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)))) .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(10, 10, 10) .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(jPanel2Layout.createSequentialGroup() .addGap(28, 28, 28) .addComponent(send1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addContainerGap(83, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 536, javax.swing.GroupLayout.PREFERRED_SIZE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, 486, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void send1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_send1ActionPerformed String s = text1.getText(); Message m = new Message(roomId, null, user.getUserName(), s, true); IClientInputHandler cih = new ClientInputHandler(); cih.sendMessage(room, m); }//GEN-LAST:event_send1ActionPerformed private void saveMessageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveMessageActionPerformed /* try { // TODO add your handling code here: xmlproject.ObjectFactory factory = new ObjectFactory(); ChatType ch = factory.createChatType(); ch.setHeader("sent messages"); GregorianCalendar c = new GregorianCalendar(); Date d = new Date(); c.setTime(d); XMLGregorianCalendar date2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(c); ch.setDate(date2); // // for (int i = 0; i < room.messageVector.size(); i++) { // Message m = room.messageVector.get(i); // MsgType msg2 = factory.createMsgType(); // msg2.setName(m.getSender()); // msg2.setBody(m.getTxt()); // ch.getMsg().add(msg2); // // } System.out.println("before xml ..."); Message m = new Message(roomId, null, "sarah@aabed", "hello i am sarah aabed 000", true); MsgType msg2 = factory.createMsgType(); msg2.setName("sarah"); msg2.setBody("btfdes"); ch.getMsg().add(msg2); JAXBContext context = JAXBContext.newInstance("xmlproject"); JAXBElement<ChatType> element = factory.createMyMsg(ch); Marshaller marsh = context.createMarshaller(); marsh.setProperty("jaxb.formatted.output", Boolean.TRUE); marsh.marshal(element, new File("E:\\SARAH\\ITI_Resources\\Java\\Project\\lastVersionProject\\demo1.xml")); } catch (DatatypeConfigurationException | JAXBException ex) { Logger.getLogger(conversation.class.getName()).log(Level.SEVERE, null, ex); }*/ }//GEN-LAST:event_saveMessageActionPerformed private void attach2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_attach2ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_attach2ActionPerformed private void attach1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_attach1ActionPerformed ImageIcon i = new ImageIcon("src/pkg1/file.png"); JFileChooser f = new JFileChooser(); if (f.showOpenDialog(conversation.this) == JFileChooser.APPROVE_OPTION) { String path = f.getSelectedFile().getPath(); try { FileInputStream fis = new FileInputStream(path); int size = fis.available(); byte[] b = new byte[size]; fis.read(b); // Message m=new Message(roomId, null, null, null, true); IClientInputHandler cih = new ClientInputHandler(); cih.sendFile(user,room,b); // jTextArea1.setText(new String(b)); fis.close(); } catch (FileNotFoundException e) { System.out.println("FileNotFound"); } catch (IOException ex) { Logger.getLogger(conversation.class.getName()).log(Level.SEVERE, null, ex); } } }//GEN-LAST:event_attach1ActionPerformed private void colorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_colorActionPerformed // TODO add your handling code here: Color initialBackground = this.getBackground(); Color colorChooser = JColorChooser.showDialog(null,"JColorChooser Sample", initialBackground); text1.setForeground(colorChooser); }//GEN-LAST:event_colorActionPerformed private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextField1ActionPerformed // TODO add your handling code here: }//GEN-LAST:event_jTextField1ActionPerformed private void fontChooserComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fontChooserComboBoxActionPerformed // TODO add your handling code here: String selectedItem=(String) fontChooserComboBox.getSelectedItem(); Font font=new Font(selectedItem,Font.BOLD,12); text1.setFont(font); }//GEN-LAST:event_fontChooserComboBoxActionPerformed private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed // TODO add your handling code here: new FriendList(gui,gui.user,this).setVisible(true); }//GEN-LAST:event_jButton1ActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton attach1; private javax.swing.JButton attach2; private javax.swing.JButton color; private javax.swing.JComboBox fontChooserComboBox; public javax.swing.JLabel img1; private javax.swing.JButton jButton1; private javax.swing.JComboBox jComboBox2; private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JScrollPane jScrollPane4; public javax.swing.JTextField jTextField1; public javax.swing.JLabel name; private javax.swing.JButton saveMessage; private javax.swing.JButton send1; public javax.swing.JTextArea text1; public javax.swing.JTextArea text2; // End of variables declaration//GEN-END:variables }
true
4e79ff92ff488f30046f9744820a857852d41e18
Java
NatsuchaS/oop
/Exchange.java
UTF-8
316
2.40625
2
[]
no_license
import java.util.Scanner; public class Exchange { // กำหนดตัวแปร public static void main(String [] args){ Scanner sc=new Scanner(System.in); System.out.print("Enter a : "); int a=sc.nextInt(); System.out.println(Integer.toHexString(a)); } }
true
fe74998434555a133ac8b500331d39d3a1d9f131
Java
whb1219/17042019
/src/LCT/Parameter_O.java
UTF-8
4,846
1.8125
2
[]
no_license
package LCT; //25042019 test public class Parameter_O { //Properties String Transportation_fuel_type; String Electricity_type; String Fuel_type; String LO_type; double Number =0; double SFOC =0; double Ohour =0; double Engine_No =0; double Eload =0; double SLOC =0; double SFOC_2 =0; double Ohour_2 =0; double Engine_No_2 =0; double Eload_2 =0; double SLOC_2 =0; double SFOC_3 =0; double Ohour_3 =0; double Engine_No_3 =0; double Eload_3 =0; double SLOC_3 =0; double Fuel_price =0; double LO_price =0; double Transportation_distance =0; double Transportation_fee =0; double Transportation_SFOC =0; double Transportation_fuel_price =0; double Electricity_quantity = 0; double Electricity_price = 0; double Life_span =0; double Interest =0; double PV=0; double Cost_O=0; double Spec_GWP_Trans=0; double Spec_AP_Trans=0; double Spec_EP_Trans=0; double Spec_POCP_Trans=0; double Spec_GWP_E=0; double Spec_AP_E=0; double Spec_EP_E=0; double Spec_POCP_E=0; double Spec_GWP_FO=0; double Spec_AP_FO=0; double Spec_EP_FO=0; double Spec_POCP_FO=0; double Spec_GWP_LO=0; double Spec_AP_LO=0; double Spec_EP_LO=0; double Spec_POCP_LO=0; double GWP =0; double AP =0; double EP =0; double POCP =0; double C_Factor=0; double S_Factor=0; double N_Factor=0; public void run(){ //Interim results double Fuel_consumption_1 = Engine_No*SFOC*Ohour*Eload/1000000; double Fuel_consumption_2 = Engine_No_2*SFOC_2*Ohour_2*Eload_2/1000000; double Fuel_consumption_3 = Engine_No_3*SFOC_3*Ohour_3*Eload_3/1000000; double Fuel_consumption = Fuel_consumption_1+Fuel_consumption_2+Fuel_consumption_3; //double LO_consumption = Engine_No*Ohour*Eload*SLOC/1000000; double LO_consumption_1 = Engine_No*SLOC*Ohour*Eload/1000000; double LO_consumption_2 = Engine_No_2*SLOC_2*Ohour_2*Eload_2/1000000; double LO_consumption_3 = Engine_No_3*SLOC_3*Ohour_3*Eload_3/1000000; double LO_consumption = LO_consumption_1+LO_consumption_2+LO_consumption_3; double Transportation_fuel_quantity = (Fuel_consumption+LO_consumption)*1000*Transportation_distance/100*Transportation_SFOC/1000; double Fuel_cost = Fuel_consumption*Fuel_price; double LO_cost = LO_consumption*LO_price; double Transportation_fuel_cost = Transportation_fuel_quantity*Transportation_fuel_price; Electricity_quantity=Eload*Ohour*Number; double Electricity_cost = Electricity_price*Electricity_quantity; // System.out.println("xxx1"+Electricity_price); // System.out.println("xxx2"+Electricity_quantity); // System.out.println("xxx3"+Eload); // System.out.println("xxx4"+Ohour); // System.out.println("xxx5"+Number); //Final result //LCA GWP = (Spec_GWP_Trans * (Fuel_consumption+LO_consumption)*Transportation_distance/100 + Spec_GWP_E*Electricity_quantity + Spec_GWP_FO*Fuel_consumption +C_Factor*Fuel_consumption + Spec_GWP_LO*LO_consumption)*Life_span; AP = (Spec_AP_Trans * (Fuel_consumption+LO_consumption)*Transportation_distance/100 + Spec_AP_E*Electricity_quantity + Spec_AP_FO*Fuel_consumption+1.2*S_Factor*Fuel_consumption+0.5*N_Factor*Fuel_consumption+ Spec_AP_LO*LO_consumption)*Life_span; EP = (Spec_EP_Trans * (Fuel_consumption+LO_consumption)*Transportation_distance/100 + Spec_EP_E*Electricity_quantity+ Spec_EP_FO*Fuel_consumption+0.13*N_Factor*Fuel_consumption+ Spec_EP_LO*LO_consumption)*Life_span; POCP= (Spec_POCP_Trans * (Fuel_consumption+LO_consumption)*Transportation_distance/100 + Spec_POCP_E*Electricity_quantity+ Spec_POCP_FO*Fuel_consumption+0.048*S_Factor*Fuel_consumption+0.028*N_Factor*Fuel_consumption+ Spec_POCP_LO*LO_consumption)*Life_span; //LCCA double Cost_O_Annual = Fuel_cost+LO_cost+Transportation_fuel_cost+Electricity_cost; if (PV==0){ Cost_O = Cost_O_Annual*Life_span; } else{ Cost_O = Cost_O_Annual/(Math.pow((1+Interest),Life_span))*(Math.pow((1+Interest),Life_span)-1)/Interest; } // System.out.println("FC is : " + Fuel_consumption +"ton"); // System.out.println("T" + Spec_GWP_Trans * (Fuel_consumption+LO_consumption)*Transportation_distance/100*30 + "ton"); // System.out.println("P" + Spec_GWP_FO*Fuel_consumption*30 + "ton"); // System.out.println("Em" +C_Factor*Fuel_consumption*30+ "ton"); // System.out.println("Operation: cost is : " + Cost_O +"Euro"); // System.out.println("Operation: GWP is :" + GWP + "ton CO2e"); // System.out.println("Operation: AP is :" + AP + "ton SO2e"); // System.out.println("Operation: EP is :" + EP + "ton PO4e"); // System.out.println("Operation: POCP is :" + POCP + "ton C2H6e"); } }
true
ab1886e05ea9839774133c93e942197618c6d821
Java
zhongxingyu/Seer
/Diff-Raw-Data/35/35_c1d6286bc134d54ce3fb1c31f476e517e8f1faac/EntityManager/35_c1d6286bc134d54ce3fb1c31f476e517e8f1faac_EntityManager_s.java
UTF-8
1,601
2.75
3
[]
no_license
package org.jakub1221.herobrineai.entity; import java.util.HashMap; import java.util.Map; import org.bukkit.Location; import org.bukkit.World; import org.jakub1221.herobrineai.HerobrineAI; public class EntityManager { private HashMap<Integer,CustomEntity> mobList = new HashMap<Integer,CustomEntity>(); public void spawnCustomZombie(Location loc,MobType mbt){ World world = loc.getWorld(); net.minecraft.server.v1_5_R2.World mcWorld = ((org.bukkit.craftbukkit.v1_5_R2.CraftWorld) world).getHandle(); CustomZombie zmb = new CustomZombie(mcWorld,loc,mbt); mcWorld.addEntity(zmb); mobList.put(new Integer(zmb.getBukkitEntity().getEntityId()),zmb); } public void spawnCustomSkeleton(Location loc,MobType mbt){ World world = loc.getWorld(); net.minecraft.server.v1_5_R2.World mcWorld = ((org.bukkit.craftbukkit.v1_5_R2.CraftWorld) world).getHandle(); CustomSkeleton zmb = new CustomSkeleton(mcWorld,loc,mbt); mcWorld.addEntity(zmb); mobList.put(new Integer(zmb.getBukkitEntity().getEntityId()),zmb); } public boolean isCustomMob(int id){ return mobList.containsKey(new Integer(id)); } public CustomEntity getMobType(int id){ return mobList.get(new Integer(id)); } public void removeMob(int id){ mobList.remove(new Integer(id)); } public void removeAllMobs(){ mobList.clear(); } public void killAllMobs(){ for(Map.Entry<Integer, CustomEntity> s : mobList.entrySet()){ s.getValue().Kill(); } removeAllMobs(); } }
true
9cb2dd1465e1703ea85d3c841900c1d19e725fd8
Java
FloLehner/AV
/app/src/main/java/com/example/flo/av/calcMaedchengroessen.java
UTF-8
14,211
2.140625
2
[]
no_license
package com.example.flo.av; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.TextView; import java.util.ArrayList; import java.util.List; public class calcMaedchengroessen extends AppCompatActivity implements AdapterView.OnItemSelectedListener { Spinner originDropdownMädchengrößen; Spinner convertDropdownMädchengrößen; Spinner sizeDropdownMädchengrößen; TextView outcome; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_calc_maedchengroessen); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); originDropdownMädchengrößen = (Spinner) findViewById(R.id.originDropdownMädchengrößen); convertDropdownMädchengrößen = (Spinner) findViewById(R.id.convertDropdownMädchengrößen); sizeDropdownMädchengrößen = (Spinner) findViewById(R.id.sizeDropdownMädchengrößen); outcome = (TextView) findViewById(R.id.textviewSizecalculationMädchengrößen); List<String> origin = new ArrayList<>(); origin.add("International"); origin.add("Amerika"); origin.add("Europa"); ArrayAdapter origins = new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, origin); origins.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); originDropdownMädchengrößen.setAdapter(origins); convertDropdownMädchengrößen.setAdapter(origins); originDropdownMädchengrößen.setOnItemSelectedListener(this); } @Override public boolean onOptionsItemSelected(MenuItem item) { Intent backToCalcMenu = new Intent(this, chooseClothChild.class); startActivity(backToCalcMenu); return true; } @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { String value = String.valueOf(originDropdownMädchengrößen.getSelectedItem()); if(value=="International"){ List<String> sizes = new ArrayList<>(); sizes.add("2XS"); sizes.add("XS"); sizes.add("S"); sizes.add("M"); sizes.add("L"); sizes.add("XL"); sizes.add("2XL"); ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, sizes); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); sizeDropdownMädchengrößen.setAdapter(adapter); } if(value=="Amerika"){ List<String> sizes = new ArrayList<>(); sizes.add("3"); sizes.add("4 - 5"); sizes.add("6 - 7"); sizes.add("8"); sizes.add("10"); sizes.add("12"); sizes.add("14"); ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, sizes); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); sizeDropdownMädchengrößen.setAdapter(adapter); } if(value=="Europa"){ List<String> sizes = new ArrayList<>(); sizes.add("4 - 5"); sizes.add("6 - 8"); sizes.add("9"); sizes.add("10 - 11"); sizes.add("12"); sizes.add("14 - 16"); ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_dropdown_item, sizes); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); sizeDropdownMädchengrößen.setAdapter(adapter); } } public void calcFinalSizeMädchengrößen(View view){ outcome.setBackgroundResource(R.drawable.image_border); String finalOriginDropdown = String.valueOf(originDropdownMädchengrößen.getSelectedItem()); String finalConvertDropdown = String.valueOf(convertDropdownMädchengrößen.getSelectedItem()); String finalSizeDropdown = String.valueOf(sizeDropdownMädchengrößen.getSelectedItem()); //International in Amerika und Europa if(finalOriginDropdown=="International"){ if(finalSizeDropdown=="2XS"){ if(finalConvertDropdown=="Amerika"){ outcome.setText("3"); } if(finalConvertDropdown=="Europa"){ outcome.setText("Berechnung mit den angegebenen Kriterien nicht möglich."); } if(finalConvertDropdown=="International"){ outcome.setText("Berechnung mit den angegebenen Kriterien nicht möglich."); } } if(finalSizeDropdown=="XS"){ if(finalConvertDropdown=="Amerika"){ outcome.setText("4 - 5"); } if(finalConvertDropdown=="Europa"){ outcome.setText("4 - 5"); } if(finalConvertDropdown=="International"){ outcome.setText("Berechnung mit den angegebenen Kriterien nicht möglich."); } } if(finalSizeDropdown=="S"){ if(finalConvertDropdown=="Amerika"){ outcome.setText("6 - 7"); } if(finalConvertDropdown=="Europa"){ outcome.setText("6 - 8"); } if(finalConvertDropdown=="International"){ outcome.setText("Berechnung mit den angegebenen Kriterien nicht möglich."); } } if(finalSizeDropdown=="M"){ if(finalConvertDropdown=="Amerika"){ outcome.setText("8"); } if(finalConvertDropdown=="Europa"){ outcome.setText("9"); } if(finalConvertDropdown=="International"){ outcome.setText("Berechnung mit den angegebenen Kriterien nicht möglich."); } } if(finalSizeDropdown=="L"){ if(finalConvertDropdown=="Amerika"){ outcome.setText("10"); } if(finalConvertDropdown=="Europa"){ outcome.setText("10 - 11"); } if(finalConvertDropdown=="International"){ outcome.setText("Berechnung mit den angegebenen Kriterien nicht möglich."); } } if(finalSizeDropdown=="XL"){ if(finalConvertDropdown=="Amerika"){ outcome.setText("12"); } if(finalConvertDropdown=="Europa"){ outcome.setText("12"); } if(finalConvertDropdown=="International"){ outcome.setText("Berechnung mit den angegebenen Kriterien nicht möglich."); } } if(finalSizeDropdown=="2XL"){ if(finalConvertDropdown=="Amerika"){ outcome.setText("14"); } if(finalConvertDropdown=="Europa"){ outcome.setText("14 - 16"); } if(finalConvertDropdown=="International"){ outcome.setText("Berechnung mit den angegebenen Kriterien nicht möglich."); } } } if(finalOriginDropdown=="Amerika"){ if(finalSizeDropdown=="3"){ if(finalConvertDropdown=="Europa"){ outcome.setText("Berechnung mit den angegebenen Kriterien nicht möglich."); } if(finalConvertDropdown=="International"){ outcome.setText("2XS"); } if(finalConvertDropdown=="Amerika"){ outcome.setText("Berechnung mit den angegebenen Kriterien nicht möglich."); } } if(finalSizeDropdown=="4 - 5"){ if(finalConvertDropdown=="Europa"){ outcome.setText("4 - 5"); } if(finalConvertDropdown=="International"){ outcome.setText("XS"); } if(finalConvertDropdown=="Amerika"){ outcome.setText("Berechnung mit den angegebenen Kriterien nicht möglich."); } } if(finalSizeDropdown=="6 - 7"){ if(finalConvertDropdown=="Europa"){ outcome.setText("6 - 8"); } if(finalConvertDropdown=="International"){ outcome.setText("S"); } if(finalConvertDropdown=="Amerika"){ outcome.setText("Berechnung mit den angegebenen Kriterien nicht möglich."); } } if(finalSizeDropdown=="8"){ if(finalConvertDropdown=="Europa"){ outcome.setText("9"); } if(finalConvertDropdown=="International"){ outcome.setText("M"); } if(finalConvertDropdown=="Amerika"){ outcome.setText("Berechnung mit den angegebenen Kriterien nicht möglich."); } } if(finalSizeDropdown=="10"){ if(finalConvertDropdown=="Europa"){ outcome.setText("10 - 11"); } if(finalConvertDropdown=="International"){ outcome.setText("L"); } if(finalConvertDropdown=="Amerika"){ outcome.setText("Berechnung mit den angegebenen Kriterien nicht möglich."); } } if(finalSizeDropdown=="12"){ if(finalConvertDropdown=="Europa"){ outcome.setText("12"); } if(finalConvertDropdown=="International"){ outcome.setText("XL"); } if(finalConvertDropdown=="Amerika"){ outcome.setText("Berechnung mit den angegebenen Kriterien nicht möglich."); } } if(finalSizeDropdown=="14"){ if(finalConvertDropdown=="Europa"){ outcome.setText("14 - 16"); } if(finalConvertDropdown=="International"){ outcome.setText("2XL"); } if(finalConvertDropdown=="Amerika"){ outcome.setText("Berechnung mit den angegebenen Kriterien nicht möglich."); } } } if(finalOriginDropdown=="Europa"){ if(finalSizeDropdown=="4 - 5"){ if(finalConvertDropdown=="Amerika"){ outcome.setText("4 - 5"); } if(finalConvertDropdown=="International"){ outcome.setText("XS"); } if(finalConvertDropdown=="Europa"){ outcome.setText("Berechnung mit den angegebenen Kriterien nicht möglich."); } } if(finalSizeDropdown=="6 - 8"){ if(finalConvertDropdown=="Amerika"){ outcome.setText("6 - 7"); } if(finalConvertDropdown=="International"){ outcome.setText("S"); } if(finalConvertDropdown=="Europa"){ outcome.setText("Berechnung mit den angegebenen Kriterien nicht möglich."); } } if(finalSizeDropdown=="9"){ if(finalConvertDropdown=="Amerika"){ outcome.setText("8"); } if(finalConvertDropdown=="International"){ outcome.setText("M"); } if(finalConvertDropdown=="Europa"){ outcome.setText("Berechnung mit den angegebenen Kriterien nicht möglich."); } } if(finalSizeDropdown=="10 - 11"){ if(finalConvertDropdown=="Amerika"){ outcome.setText("10"); } if(finalConvertDropdown=="International"){ outcome.setText("L"); } if(finalConvertDropdown=="Europa"){ outcome.setText("Berechnung mit den angegebenen Kriterien nicht möglich."); } } if(finalSizeDropdown=="12"){ if(finalConvertDropdown=="Amerika"){ outcome.setText("12"); } if(finalConvertDropdown=="International"){ outcome.setText("XL"); } if(finalConvertDropdown=="Europa"){ outcome.setText("Berechnung mit den angegebenen Kriterien nicht möglich."); } } if(finalSizeDropdown=="14 - 16"){ if(finalConvertDropdown=="Amerika"){ outcome.setText("14"); } if(finalConvertDropdown=="International"){ outcome.setText("2XL"); } if(finalConvertDropdown=="Europa"){ outcome.setText("Berechnung mit den angegebenen Kriterien nicht möglich."); } } } } @Override public void onNothingSelected(AdapterView<?> parent) { } }
true
ba499eb88eedfe91bd73035aa81d85dac635b16f
Java
dcoraboeuf/orbe
/doolin/Doolin-Application/src/main/java/net/sf/doolin/gui/service/SwingFactory.java
UTF-8
1,427
2.3125
2
[]
no_license
/* * Created on Jul 17, 2007 */ package net.sf.doolin.gui.service; import java.awt.Component; import javax.swing.Action; import net.sf.doolin.gui.core.View; import net.sf.doolin.gui.core.action.ActionControler; import net.sf.doolin.gui.core.icon.IconSize; import net.sf.doolin.gui.swing.BarContainer; /** * Factory for Swing objects from Doolin GUI objects. * * @author Damien Coraboeuf * @version $Id: SwingFactory.java,v 1.1 2007/08/10 16:54:36 guinnessman Exp $ */ public interface SwingFactory { /** * Creates a Swing action from a Doolin GUI action. * * @param action * Encapsulated action * @param view * Hosting view * @param controler * Controler for the action before execution * @param iconSize * Requested icon size for the any icon. * @return Swing action */ Action createSwingAction(net.sf.doolin.gui.core.Action action, View view, ActionControler controler, IconSize iconSize); /** * Sets the menubar on a component * * @param view * View definition that mayb contain a menubar definition * @param component * Component to host to menubar */ void setMenubar(View view, Component component); /** * Sets the toolbars on a component. * * @param view * Hosting view * @param container * Container to set */ void setToolbars(View view, BarContainer container); }
true
049d00bf283bf850cc6f043c68626a7616eab614
Java
PaoloSani/ing-sw-2020-Paolini-Pellini-Sani
/src/main/java/it/polimi/ingsw/GUI/ChooseGodWindow.java
UTF-8
8,666
2.921875
3
[]
no_license
package it.polimi.ingsw.GUI; import it.polimi.ingsw.model.God; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.stage.Stage; import java.net.URL; import java.util.List; import java.util.ResourceBundle; /** * It is the window where the player can choose the god to play with, among those chosen by the challenger. */ public class ChooseGodWindow extends GameWindow implements Initializable { /** * It is the button to scroll backwards the gods */ @FXML public Button backGodButton; /** * It is the button to scroll forward the gods */ @FXML public Button nextGodButton; /** * It shows god's name. * It changes when the current god on screen changes. */ @FXML public Label godLabel; /** * It shows a short description of god's power. */ @FXML public Label powerLabel; /** * It is the button to press to choose a god. */ @FXML public Button chooseButton; /** * It is the image where the current god is shown. It changes by pressing nextGodButton and backGodButton. */ @FXML public ImageView godCard; /** * It is the image of chooseButton. */ @FXML public ImageView chooseButtonImage; /** * It is the image of backGodButton. */ @FXML public ImageView backButtonImage; /** * It is the image of nextGodButton. */ @FXML public ImageView nextButtonImage; /** * It is the pane of this window. */ @FXML public AnchorPane chooseGodPane; /** * It is the stage which succeeds the current one. */ private final Stage nextStage = new Stage(); /** * It is the god shown on mirror. */ private God currGod = guiHandler.getGods().get(0); /** * It changes the current god, rolling currGod back and loading a new image on godCard. * @param actionEvent generated by clicking on backGodButton. */ public void backGod(ActionEvent actionEvent) { if (currGod == guiHandler.getGods().get(0)){ if (guiHandler.getNumOfPlayers() == 3 && guiHandler.getGods().size() == 3) currGod = guiHandler.getGods().get(2); else currGod = guiHandler.getGods().get(1); } else if (currGod == guiHandler.getGods().get(1)){ currGod = guiHandler.getGods().get(0); } else if (currGod == guiHandler.getGods().get(2)){ currGod = guiHandler.getGods().get(1); } setGodImage(); } /** * It changes the current god, rolling currGod on and loading a new image on godCard. * @param actionEvent generated by clicking on nextGodButton. */ public void nextGod(ActionEvent actionEvent) { if (currGod == guiHandler.getGods().get(0)){ currGod = guiHandler.getGods().get(1); } else if (currGod == guiHandler.getGods().get(1)){ if (guiHandler.getNumOfPlayers() == 3 && guiHandler.getGods().size() == 3) currGod = guiHandler.getGods().get(2); else currGod = guiHandler.getGods().get(0); } else if (currGod == guiHandler.getGods().get(2)){ currGod = guiHandler.getGods().get(0); } setGodImage(); } /** * It loads the image of the current god on screen. */ private void setGodImage() { switch (currGod){ case APOLLO:{ godCard.setImage(new Image("FullGodAvatar/full_0000s_0043_god_and_hero_cards_0013_apollo.png")); break; } case ARTEMIS:{ godCard.setImage(new Image("FullGodAvatar/full_0000s_0054_god_and_hero_cards_0002_Artemis.png")); break; } // case ATHENA:{ godCard.setImage(new Image("FullGodAvatar/full_0000s_0052_god_and_hero_cards_0004_Athena.png")); break; } case ATLAS:{ godCard.setImage(new Image("FullGodAvatar/full_0000s_0053_god_and_hero_cards_0003_Atlas.png")); break; } // case CHARON:{ godCard.setImage(new Image("FullGodAvatar/full_0000s_0020_god_and_hero_cards_0036_charon.png")); break; } // case DEMETER:{ godCard.setImage(new Image("FullGodAvatar/full_0000s_0050_god_and_hero_cards_0006_Demeter.png")); break; } case HEPHAESTUS:{ godCard.setImage(new Image("FullGodAvatar/full_0000s_0009_god_and_hero_cards_0047_Hephaestus.png")); break; } // case HYPNUS:{ godCard.setImage(new Image("FullGodAvatar/full_0000s_0019_god_and_hero_cards_0037_Hypnus.png")); break; } case MINOTAUR:{ godCard.setImage(new Image("FullGodAvatar/full_0000s_0008_god_and_hero_cards_0048_Minotaur.png")); break; } case MORTAL:{ godCard.setImage(new Image("FullGodAvatar/full_0000s_0000_god_and_hero_cards_0057_HumanGord.png")); break; } case PAN:{ godCard.setImage(new Image("FullGodAvatar/full_0000s_0046_god_and_hero_cards_0010_Pan.png")); break; } case POSEIDON:{ godCard.setImage(new Image("FullGodAvatar/full_0000s_0045_god_and_hero_cards_0011_Poseidon.png")); break; } case PROMETHEUS:{ godCard.setImage(new Image("FullGodAvatar/full_0000s_0004_god_and_hero_cards_0052_Prometheus.png")); break; } case TRITON:{ godCard.setImage(new Image("FullGodAvatar/full_0000s_0028_god_and_hero_cards_0028_triton.png")); break; } case ZEUS:{ godCard.setImage(new Image("FullGodAvatar/full_0000s_0014_god_and_hero_cards_0042_zeus.png")); break; } } godLabel.setText(currGod.toString()); powerLabel.setText(currGod.getPower()); } /** * It let the player to choose his/her god. It changes the current stage. * @param actionEvent */ public void chooseGod(ActionEvent actionEvent) { guiHandler.setClientMessage(currGod); guiHandler.loadFXMLFile(chooseButton,nextStage,"/GUIScenes/beginningMatchWindow.fxml"); } /** * It shows a graphical effect when pressing backGodButton. * @param mouseEvent generated by pressing backGodButton. */ public void clickBack(MouseEvent mouseEvent) { backButtonImage.setImage(new Image("Buttons/btn_back_pressed.png")); } /** * It shows a graphical effect when releasing backGodButton. * @param mouseEvent generated by releasing backGodButton. */ public void releaseBack(MouseEvent mouseEvent) { backButtonImage.setImage(new Image("Buttons/btn_back.png")); } /** * It shows a graphical effect when pressing nextGodButton. * @param mouseEvent generated by pressing nextGodButton. */ public void clickNext(MouseEvent mouseEvent) { nextButtonImage.setImage(new Image("Buttons/btn_back_pressed.png")); } /** * It shows a graphical effect when releasing nextGodButton. * @param mouseEvent generated by releasing nextGodButton. */ public void releaseNext(MouseEvent mouseEvent) { nextButtonImage.setImage(new Image("Buttons/btn_back.png")); } /** * It shows a graphical effect when pressing chooseButton. * @param mouseEvent generated by pressing chooseButton. */ public void clickChoose(MouseEvent mouseEvent) { chooseButtonImage.setImage(new Image("Buttons/cm_btn_blue_pressed.png")); } /** * It shows a graphical effect when releasing chooseButton. * @param mouseEvent generated by releasing chooseButton. */ public void releaseChoose(MouseEvent mouseEvent) { chooseButtonImage.setImage(new Image("Buttons/cm_btn_blue.png")); } @Override public void initialize(URL location, ResourceBundle resources) { currGod = guiHandler.getGods().get(0); setGodImage(); guiHandler.setCurrPane(chooseGodPane); } }
true
5ce05aa6bc6861f85a5ec0d5d949769ed21717b9
Java
rkliuha/oms_test_framework
/src/test/java/academy/softserve/edu/domains/User.java
UTF-8
5,993
2.34375
2
[]
no_license
package academy.softserve.edu.domains; import academy.softserve.edu.enums.CustomerTypes; import academy.softserve.edu.enums.Regions; import academy.softserve.edu.enums.Roles; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; @Getter @Setter @EqualsAndHashCode public final class User { private int id; private int userActive; private int balance; private String email; private String firstName; private String lastName; private String login; private String password; private int customerTypeReference; private int regionReference; private int roleReference; private User() { } public final String getRoleName() { return Roles.getRoleNameByReference(roleReference); } public final String getRegionName() { return Regions.getRegionNameByReference(regionReference); } public final String getCustomerTypeName() { return CustomerTypes.getCustomerTypeNameByReference(customerTypeReference); } @Override public final String toString() { return "User {" + "ID=" + id + ", isUserActive=" + userActive + ", Balance=" + balance + ", Email=" + email + ", FirstName=" + firstName + ", LastName=" + lastName + ", Login=" + login + ", Password=" + password + ", CustomerTypeRef=" + customerTypeReference + ", RegionRef=" + regionReference + ", RoleRef=" + roleReference + "}"; } public static FirstIdStep newBuilder() { return new Builder(); } public interface FirstIdStep { UserActiveStep setId(final int id); } public interface UserActiveStep { BalanceStep setUserActive(final int userActive); } public interface BalanceStep { EmailStep setBalance(final int balance); } public interface EmailStep { FirstNameStep setEmail(final String email); } public interface FirstNameStep { LastNameStep setFirstName(final String firstName); } public interface LastNameStep { LoginStep setLastName(final String lastName); } public interface LoginStep { PasswordStep setLogin(final String login); } public interface PasswordStep { CustomerTypeReferenceStep setPassword(final String password); } public interface CustomerTypeReferenceStep { RegionReferenceStep setCustomerTypeReference(final int customerTypeReference); } public interface RegionReferenceStep { RoleReferenceStep setRegionReference(final int regionReference); } public interface RoleReferenceStep { BuildStep setRoleReference(final int roleReference); } public interface BuildStep { User build(); } private static class Builder implements FirstIdStep, UserActiveStep, BalanceStep, EmailStep, FirstNameStep, LastNameStep, LoginStep, PasswordStep, CustomerTypeReferenceStep, RegionReferenceStep, RoleReferenceStep, BuildStep { private int id; private int userActive; private int balance; private String email; private String firstName; private String lastName; private String login; private String password; private int customerTypeReference; private int regionReference; private int roleReference; @Override public final UserActiveStep setId(final int id) { this.id = id; return this; } @Override public final BalanceStep setUserActive(final int userActive) { this.userActive = userActive; return this; } @Override public final EmailStep setBalance(final int balance) { this.balance = balance; return this; } @Override public final FirstNameStep setEmail(final String email) { this.email = email; return this; } @Override public final LastNameStep setFirstName(final String firstName) { this.firstName = firstName; return this; } @Override public final LoginStep setLastName(final String lastName) { this.lastName = lastName; return this; } @Override public final PasswordStep setLogin(final String login) { this.login = login; return this; } @Override public final CustomerTypeReferenceStep setPassword(final String password) { this.password = password; return this; } @Override public final RegionReferenceStep setCustomerTypeReference(final int customerTypeReference) { this.customerTypeReference = customerTypeReference; return this; } @Override public final RoleReferenceStep setRegionReference(final int regionReference) { this.regionReference = regionReference; return this; } @Override public final BuildStep setRoleReference(final int roleReference) { this.roleReference = roleReference; return this; } @Override public final User build() { final User user = new User(); user.setId(id); user.setUserActive(userActive); user.setBalance(balance); user.setEmail(email); user.setFirstName(firstName); user.setLastName(lastName); user.setLogin(login); user.setPassword(password); user.setCustomerTypeReference(customerTypeReference); user.setRegionReference(regionReference); user.setRoleReference(roleReference); return user; } } }
true
54d0715fdf5a25e671eb872a01c35e65073fe79d
Java
daniedev/Solved-Problems
/src/main/java/basicproblems/hackerearth/implementation/PrintHackerEarth.java
UTF-8
4,405
4.125
4
[]
no_license
package basicproblems.hackerearth.implementation; /*Problem Url: https://www.hackerearth.com/practice/basic-programming/implementation/basics-of-implementation/practice-problems/algorithm/print-hackerearth/ Problem Description: As a beginner to the programming, Mishki came to Hackerearth platform, to become a better programmer. She solved some problems and felt very confident. Later being a fan of Hackerearth, she gave a problem to her friends to solve. They will be given a string containing only lower case characters (a-z), and they need to find that by using the characters of the given string, how many times they can print "hackerearth"(without quotes). As they are new to programming world, please help them. Input: The first line will consists of one integer 'N' denoting the length of string. Next line will contain the string 'str' containing only lower case characters. Output: Print one integer, denoting the number of times her friends can print "hackerearth" (without quotes). Constraints: Each character of string 'str' will be in range [a to z] SAMPLE INPUT 13 aahkcreeatrha SAMPLE OUTPUT 1*/ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class PrintHackerEarth { public static void main(String[] args) throws IOException { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in)); bufferedReader.readLine(); char[] inputWord = bufferedReader.readLine().toCharArray(); //Identify the count of each letters int a = 0, c = 0, e = 0, h = 0, k = 0, r = 0, t = 0; for (char value : inputWord) { switch (value) { case 'a': a++; break; case 'c': c++; break; case 'e': e++; break; case 'h': h++; break; case 'k': k++; break; case 'r': r++; break; case 't': t++; break; } } // Determine the smallest among a,e,h,r int minimumCountOfLettersWithTwoOccurrences = 0; if (a < e) { if (a < h) { if (a < r) { minimumCountOfLettersWithTwoOccurrences = a; } else { minimumCountOfLettersWithTwoOccurrences = r; } } else { if (h < r) { minimumCountOfLettersWithTwoOccurrences = h; } else { minimumCountOfLettersWithTwoOccurrences = r; } } } else { if (e < h) { if (e < r) { minimumCountOfLettersWithTwoOccurrences = e; } else { minimumCountOfLettersWithTwoOccurrences = r; } } else { if (h < r) { minimumCountOfLettersWithTwoOccurrences = h; } else { minimumCountOfLettersWithTwoOccurrences = r; } } } // Determine the smallest among c,k,t int minimumCountOfLettersWithOneOccurrence = 0; if (c < k) { if (c < t) minimumCountOfLettersWithOneOccurrence = c; else minimumCountOfLettersWithOneOccurrence = t; } else { if (k < t) minimumCountOfLettersWithOneOccurrence = k; else minimumCountOfLettersWithOneOccurrence = t; } // Determine number of words. int numberOfWords = 0; if(minimumCountOfLettersWithOneOccurrence > 0) { if (minimumCountOfLettersWithTwoOccurrences / (2 * minimumCountOfLettersWithOneOccurrence) >= 1) numberOfWords = minimumCountOfLettersWithOneOccurrence; else numberOfWords = minimumCountOfLettersWithTwoOccurrences / 2; } System.out.println(numberOfWords); } }
true
cec667fabb6b51e10319817dbf28248f8d9cf809
Java
green-fox-academy/josanandi
/Week-10/bankofsimba/src/main/java/com/greenfoxacademy/bankofsimba/models/ListOfAccounts.java
UTF-8
272
1.796875
2
[]
no_license
package com.greenfoxacademy.bankofsimba.models; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class ListOfAccounts { public List<BankAccount> list; public ListOfAccounts() { this.list = new ArrayList<>(); } }
true
48756027b100ead35a8c62a2263345a15b5a4b97
Java
GuilhermeSilva-code/turma14java
/Java/Aulas/src/listatarefa2/exercicio8.java
ISO-8859-1
625
4.0625
4
[]
no_license
package listatarefa2; import java.util.Scanner; public class exercicio8 { public static void main(String[] args) { /* * 8) Construa um sistema para ler uma varivel numrica N e imprimi-la * somente se a mesma for maior que 100, caso contrrio imprimi-la com o * valor zero. */ Scanner leia = new Scanner(System.in); int numero=0; System.out.println("Digite um nmero maior que 100: "); numero = leia.nextInt(); if (numero>=100) { System.out.println("O nmero digitado : "+numero); } else { System.out.println("O nmero informado menor que 100!!!"); } } }
true
d46c219c23d16491aec1f8cc5d01f542ddbeec4d
Java
mkhuram/JavaExercise
/09-Apr-18/src/conditionmethod2a.java
UTF-8
533
3.5
4
[]
no_license
//Exercise 7 /*CONDITIONALS 2 Modify your method from the previous task to have another if statement that checks if one of the numbers is 0, if this is true then return the other non-0 number. */ //Main method public class conditionmethod2a { public static void main(String[] args) { // TODO Auto-generated method stub conditionmethod2 con = new conditionmethod2(); System.out.println(con.conditionfunction(2, 0)); System.out.println(con.conditionfunction(0, 3)); System.out.println(con.conditionfunction(2, 6)); } }
true
634b79b177f36934dc77d4733b314b502afaded8
Java
javacoderxxp/its-ch-cloud
/sc-aa/aa-server/src/main/java/com/its/aa/server/service/LoginService.java
UTF-8
601
1.78125
2
[ "Apache-2.0" ]
permissive
package com.its.aa.server.service; import com.baomidou.mybatisplus.extension.service.IService; import com.its.aa.common.model.entity.AaRole; import com.its.aa.common.model.entity.AaUser; import com.its.aa.common.model.vo.UserVO; import java.util.List; import java.util.Map; /** * <p> * 角色表 服务类 * </p> * * @author guzf * @since 2019-08-08 */ public interface LoginService extends IService<AaRole> { public boolean checkUsernameAndPwd(String username,String password); public String getToken(String username); public UserVO verifyToken(String token) throws Exception; }
true
6483c56162301f811809bbc79f4bd47e4d3eb282
Java
DwlRNG/leranJava
/IDEAWorkspaces/studay/src/MultithreadedProgramming/RunnableNoeImp.java
UTF-8
397
2.4375
2
[]
no_license
package MultithreadedProgramming; /** * Created by Dw.L on 2017/7/26. * RunnableNoe类实现类 测试类 * */ public class RunnableNoeImp { public static void main(String[] args) { RunnableNoe runnableNoe1 = new RunnableNoe("线程一"); RunnableNoe runnableNoe2 = new RunnableNoe("线程二"); runnableNoe1.start(); runnableNoe2.start(); } }
true
80bdca0f1235d495e798c5e4db9facc591bfed0b
Java
Spencerx/DiscoveryEnvironment
/modules/de-common-module/src/main/java/org/iplantc/de/client/models/apps/AppAutoBeanFactory.java
UTF-8
591
1.625
2
[]
no_license
package org.iplantc.de.client.models.apps; import com.google.web.bindery.autobean.shared.AutoBean; import com.google.web.bindery.autobean.shared.AutoBeanFactory; public interface AppAutoBeanFactory extends AutoBeanFactory { AutoBean<App> app(); AutoBean<AppFeedback> appFeedback(); AutoBean<PipelineEligibility> pipelineEligibility(); AutoBean<AppDataObject> appDataObject(); AutoBean<DataObject> dataObject(); AutoBean<AppList> appList(); AutoBean<AppGroup> appGroup(); AutoBean<AppGroupList> appGroups(); AutoBean<AppRefLink> appRefLink(); }
true
ddbd7bb304fdedd13737d785a13d3f665c4fe704
Java
jarrodthibodeau/CodeEval
/EvenNumbers/src/Main.java
UTF-8
574
3.09375
3
[]
no_license
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; public class Main { public static void main(String[] args) throws NumberFormatException, IOException { // TODO Auto-generated method stub File file = new File(args[0]); BufferedReader in = new BufferedReader(new FileReader(file)); String line; while ((line = in.readLine()) != null) { int count = Integer.parseInt(line); if(count % 2 == 0){ System.out.println(1); } else{ System.out.println(0); } } in.close(); } }
true
2bb6efe0f902443f20e1b68c3779ca305c2e374d
Java
fommax/java-for-testers
/addressbook-web-tests/src/test/java/ru/stqa/pft/addressbook/tests/AddressCreationTests.java
UTF-8
2,064
2.296875
2
[]
no_license
package ru.stqa.pft.addressbook.tests; import com.thoughtworks.xstream.XStream; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import ru.stqa.pft.addressbook.model.AddressData; import ru.stqa.pft.addressbook.model.Addresses; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Iterator; import java.util.List; import java.util.stream.Collectors; import static org.hamcrest.CoreMatchers.*; import static org.hamcrest.MatcherAssert.*; import static org.testng.Assert.*; public class AddressCreationTests extends TestBase{ @DataProvider public Iterator<Object[]> validAddresses() throws IOException { try (BufferedReader reader = new BufferedReader(new FileReader(new File("src/test/resources/addresses.xml")))) { String xml = ""; String line = reader.readLine(); while (line != null) { xml += line; line = reader.readLine(); } XStream xstream = new XStream(); xstream.processAnnotations(AddressData.class); List<AddressData> addresses = (List<AddressData>) xstream.fromXML(xml); return addresses.stream().map((a) -> new Object[] {a}).collect(Collectors.toList()).iterator(); } } @Test(dataProvider = "validAddresses") public void testAddressCreation(AddressData address) { app.goTo().homePage(); Addresses before = app.db().addresses(); /*File photo = new File("src/test/resources/che.jpg"); AddressData address = new AddressData().withFirstname("Alexander").withLastname("Brooks") .withPhoto(photo);*/ app.contact().create(address, true); assertThat(app.contact().count(), equalTo(before.size() + 1)); Addresses after = app.db().addresses(); assertThat(after, equalTo(before.withAdded(address.withId(after.stream().mapToInt((a) -> a.getId()).max().getAsInt())))); verifyAddressListInUI(); } }
true
31dc54e08e6a54b1572021dd31052ca10bdd227b
Java
dprodanov/pixlib
/ijaux/hypergeom/index/BaseIndex2D.java
UTF-8
2,056
2.640625
3
[]
no_license
package ijaux.hypergeom.index; import ijaux.Util; import java.io.Serializable; public class BaseIndex2D extends GridIndex implements Serializable { /** * */ private static final long serialVersionUID = 1305435124658595433L; public BaseIndex2D(int[] dims ) { n=dims.length; dim=dims; if (n>2) reshape(dims); if (n!=2) throw new IllegalArgumentException("dimensions != 2"); coords=new int[n]; int prod=1; for (int c:dims) prod*=c; maxind=prod; updated=true; warp(); } public BaseIndex2D(int[] dims, int idx) { n=dims.length; dim=dims; if (n>2) reshape(dims); if (n!=2) throw new IllegalArgumentException("dimensions != 2"); index=idx; coords=new int[n]; int prod=1; for (int c:dims) prod*=c; maxind=prod; updated=true; warp(); } @Override public void setIndex(int idx) { index=idx; updated=true; } public void setIndexAndUpdate(int idx) { index=idx; warp(); } public void warp() { coords[1]=index/dim[0]; coords[0]=index%dim[0]; updated=false; } @Override public int indexOf(int[] x) { return x[1]*dim[0]+x[0]; } @Override public boolean isValid() { boolean valid=true; valid= (coords [0] >=0) && (coords [1] >=0); valid= valid && (coords [0] < dim[0]) && (coords [1] <dim[1]); /*if (!valid) { System.out.print("nv2: "); Util.printIntArray(coords); }*/ isvalid=valid; return isvalid; } @Override public int dec(int k, int step) { if ((k>n) || (k<0)) return index; coords[k]-=step; updated=true; //Util.printIntArray(coords); index= indexOf(coords); //System.out.println("2D: "+ index); return index; } @Override public int inc(int k, int step) { if ((k>n) || (k<0)) return index; coords[k]+=step; updated=true; index= indexOf(coords); return index; } @Override public void inc() { index++; /*coords[0]++; if (coords[0]==dim[0]) { coords[0]=0; coords[1]++; } updated=false;*/ warp(); } @Override public void dec() { index--; warp(); } }
true
82953e051a96709eec724f52285595d0ba8e48b2
Java
Tijol-Wang/contacts-manager-CLI
/src/Contact.java
UTF-8
514
3.046875
3
[]
no_license
public class Contact { private String name; private long number; // Constructor public Contact (String name, long number) { this.name = name; this.number = number; } // Getters public String getName() { return this.name; } public long getNum() { return this.number; } // Setters public void setName(String name) { this.name = name; } public void setNumber(long number) { this.number = number; } }
true
cdea8c088718d750a65d151a50a901b6da083ebf
Java
influence160/spring-cerification-samples-2
/spring-core-test/src/main/java/com/othmen/testspring/springcore/events/test2/AnnotationEventListener.java
WINDOWS-1250
352
2.015625
2
[]
no_license
package com.othmen.testspring.springcore.events.test2; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Component; @Component public class AnnotationEventListener { @EventListener public void l1(Event1 e1) { System.out.println("Event1 detect en utilisant @EventListener " + e1.message); } }
true
3c359b154364c21a60ac96e92cd31877caf33764
Java
0xlsca/GrowthAPI
/src/main/java/tomconn/growthapi/interfaces/event/helper/BaseEventHelper.java
UTF-8
533
1.742188
2
[ "BSD-3-Clause" ]
permissive
package tomconn.growthapi.interfaces.event.helper; import net.minecraftforge.fml.common.eventhandler.Event; import tomconn.growthapi.interfaces.event.helper.base_information.*; /** * A <code>BaseEventHelper</code> helps with retrieving basic information from any {@link Event}. * * @since 0.0.6 */ public interface BaseEventHelper extends BiomeProvider, BlockClassProvider, BlockPosProvider, CanSeeSkyProvider, LightLevelProvider, TemperatureProvider, WorldProvider { }
true
4e1d80dc06caf2db3d95bf4d25ece017366f1f4d
Java
tmegh82/tellurimeghana82
/PDP/Sendactivity.java
UTF-8
3,454
2.203125
2
[]
no_license
package ru.driim.bluetoothterminal; import android.os.AsyncTask; import android.os.Bundle; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.telephony.gsm.SmsManager; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; public class Sendactivity extends Activity { TextView tempra,press; EditText mobile; Button sendd; ProgressBar pbar; String temprature,pressure=null; String username; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_sendactivity); mobile=(EditText)findViewById(R.id.editText1); //pass=(EditText)findViewById(R.id.editText2); tempra=(TextView)findViewById(R.id.textView1); press=(TextView)findViewById(R.id.textView2); sendd=(Button)findViewById(R.id.button1); pbar = (ProgressBar)findViewById(R.id.progressBar1); temprature = getIntent().getStringExtra("temprature"); pressure=getIntent().getStringExtra("pressure"); username=getIntent().getStringExtra("uname"); tempra.setText("Temprature:" +temprature); press.setText("Pressure :" +pressure); sendd.setOnClickListener(new OnClickListener(){ @SuppressWarnings("deprecation") @Override public void onClick(View arg0) { // TODO Auto-generated method stub String phone=mobile.getText().toString(); SmsManager sms=SmsManager.getDefault(); sms.sendTextMessage(phone, null, "temprature: "+temprature +"and"+"pressure: "+ pressure, null, null); Toast.makeText(getApplicationContext(), "Sms sent successfully", Toast.LENGTH_LONG).show(); SendToServer senddata = new SendToServer(); senddata.execute(); } }); } private class SendToServer extends AsyncTask<Void, String, Void> { /*String username=user.getText().toString(); String password=pass.getText().toString();*/ String res=""; @Override protected void onPreExecute() { pbar.setVisibility(View.VISIBLE); } @Override protected Void doInBackground(Void... unused) { res = CallService.sendPHR(username, temprature, pressure, "monitorphr"); return null; } @Override protected void onProgressUpdate(String... data) { } @Override protected void onPostExecute(Void unused) { AlertDialog.Builder dia=new AlertDialog.Builder(Sendactivity.this); dia.setTitle("Trust Agent"); dia.setMessage(res); dia.setCancelable(false); dia.setPositiveButton("OK", new DialogInterface.OnClickListener(){ @Override public void onClick(DialogInterface dialog, int which) { Intent intent=new Intent(getBaseContext(),MainActivity.class); startActivity(intent); dialog.cancel(); } }); AlertDialog dialo=dia.create(); dialo.show(); pbar.setVisibility(View.INVISIBLE); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.sendactivity, menu); return true; } }
true
22d90509d53f1f273df6e8f652c9c06fccd5dc38
Java
Rebeccazmf/FoodBank
/src/business/Food/FoodCatalog.java
UTF-8
1,457
3.015625
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 business.Food; import business.Food.Food.FoodType; import java.util.ArrayList; /** * * @author 梦菲 */ public class FoodCatalog { private ArrayList<Food> foodList; public FoodCatalog() { foodList = new ArrayList<>(); } public ArrayList<Food> getFoodList() { return foodList; } public void setFoodList(ArrayList<Food> foodList) { this.foodList = foodList; } public boolean hasFood(String foodName, FoodType foodType) { for (Food food : foodList) { if (food.getFoodName().toLowerCase().contains(foodName.toLowerCase()) && food.getFoodType() == foodType) { return true; } } return false; } public void addFood(Food f) { for (Food food : foodList) { if (food.getFoodName().equals(f.getFoodName()) && food.getFoodType() == f.getFoodType()) { food.setQuantity(food.getQuantity() + f.getQuantity()); return; } } foodList.add(f); } public void createFood(String foodName, FoodType ft, int q) { Food f = new Food(); f.setFoodName(foodName); f.setFoodType(ft); f.setQuantity(q); foodList.add(f); } }
true
2deda4d05dc92f182c1726bf87865a01f1282eab
Java
igorjsantos2015/turning
/estudo/src/br/com/igtec/estudo/modelo/Aviao.java
UTF-8
184
1.53125
2
[]
no_license
package br.com.igtec.estudo.modelo; public class Aviao { public Pessoa piloto; public Pessoa aeromoca; public Pessoa passageiro; public String destino; }
true
7df880e19b6abd6ade1ead1bfa5948df0604452c
Java
deepshukla/EcommerceApplication
/app/src/main/java/com/lex/ecommerceapplication/domain/categorylist/adapter/CategoryListAdapter.java
UTF-8
2,636
2.390625
2
[]
no_license
package com.lex.ecommerceapplication.domain.categorylist.adapter; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.lex.ecommerceapplication.R; import com.lex.ecommerceapplication.domain.categorylist.Contracts; import com.lex.ecommerceapplication.model.response.CategoryDTO; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; /** * Category list adapter * * @author DeepS */ public class CategoryListAdapter extends RecyclerView.Adapter<CategoryListAdapter.CategoryViewHolder> { private Context context; private List<CategoryDTO> productDetailsList; private LayoutInflater layoutInflater; private Contracts.View categoryView; public CategoryListAdapter(Context context, List<CategoryDTO> results, Contracts.View categoryView) { this.context = context; productDetailsList = results; layoutInflater = LayoutInflater.from(context); this.categoryView = categoryView; } public void addAll(List<CategoryDTO> results) { productDetailsList.addAll(results); notifyDataSetChanged(); } public List<CategoryDTO> getList() { return productDetailsList; } public void clear() { if (productDetailsList != null) { productDetailsList.clear(); } } @Override public CategoryViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new CategoryViewHolder(layoutInflater.inflate(R.layout.item_category, parent, false)); } @Override public void onBindViewHolder(CategoryViewHolder holder, int position) { holder.bindViews(productDetailsList.get(position)); } @Override public int getItemCount() { return productDetailsList.size(); } class CategoryViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { @BindView(R.id.tv_category_name) TextView tvProductName; CategoryViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); itemView.setOnClickListener(this); } void bindViews(CategoryDTO result) { tvProductName.setText(result.getName()); } @Override public void onClick(View v) { categoryView.onCategoryItemSelected(productDetailsList.get(getAdapterPosition())); } } }
true
fda59ad3f96f6f050e79cc6ef78c87bf4c798b4e
Java
docker-client/docker-engine
/engine/src/main/java/de/gesellix/docker/engine/OkDockerClient.java
UTF-8
22,290
1.679688
2
[ "MIT" ]
permissive
package de.gesellix.docker.engine; import com.squareup.moshi.Moshi; import de.gesellix.docker.client.filesocket.FileSocketFactory; import de.gesellix.docker.client.filesocket.HostnameEncoder; import de.gesellix.docker.client.filesocket.NamedPipeSocketFactory; import de.gesellix.docker.client.filesocket.UnixSocketFactory; import de.gesellix.docker.client.filesocket.UnixSocketFactorySupport; import de.gesellix.docker.hijack.HijackingInterceptor; import de.gesellix.docker.hijack.OkResponseCallback; import de.gesellix.docker.json.CustomObjectAdapterFactory; import de.gesellix.docker.rawstream.RawInputStream; import de.gesellix.docker.response.JsonContentHandler; import de.gesellix.docker.ssl.DockerSslSocket; import de.gesellix.docker.ssl.SslSocketConfigFactory; import de.gesellix.util.IOUtils; import okhttp3.CacheControl; import okhttp3.Call; import okhttp3.Headers; import okhttp3.HttpUrl; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; import okhttp3.ResponseBody; import okhttp3.WebSocket; import okhttp3.WebSocketListener; import okhttp3.internal.http.HttpMethod; import okio.BufferedSource; import okio.Okio; import okio.Source; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.Proxy; import java.net.URLEncoder; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import static de.gesellix.docker.client.filesocket.FileSocket.SOCKET_MARKER; import static de.gesellix.docker.engine.RequestMethod.DELETE; import static de.gesellix.docker.engine.RequestMethod.GET; import static de.gesellix.docker.engine.RequestMethod.HEAD; import static de.gesellix.docker.engine.RequestMethod.POST; import static de.gesellix.docker.engine.RequestMethod.PUT; import static java.util.concurrent.TimeUnit.MILLISECONDS; /** * Will be replaced with the implementation from <a href="https://github.com/docker-client/docker-remote-api-client">github.com/docker-client/docker-remote-api-client</a>. * * @deprecated */ @Deprecated public class OkDockerClient implements EngineClient { private static final Logger log = LoggerFactory.getLogger(OkDockerClient.class); private final Map<String, Object> socketFactories = new LinkedHashMap<>(); private final DockerClientConfig dockerClientConfig; private Proxy proxy; private final Moshi moshi; public OkDockerClient() { this(new DockerClientConfig()); } public OkDockerClient(String dockerHost) { this(new DockerClientConfig(dockerHost)); } public OkDockerClient(DockerClientConfig dockerClientConfig) { this(dockerClientConfig, Proxy.NO_PROXY); } public OkDockerClient(DockerClientConfig dockerClientConfig, Proxy proxy) { if (new UnixSocketFactorySupport().isSupported()) { socketFactories.put("unix", new UnixSocketFactory()); } socketFactories.put("npipe", new NamedPipeSocketFactory()); socketFactories.put("https", new SslSocketConfigFactory()); this.dockerClientConfig = dockerClientConfig; this.proxy = proxy; this.moshi = new Moshi.Builder() .add(new CustomObjectAdapterFactory()) .build(); } @Override public EngineResponse head(Map<String, Object> requestConfig) { EngineRequest engineRequest = ensureValidRequestConfig(requestConfig, HEAD); return request(engineRequest); } @Override public EngineResponse get(Map<String, Object> requestConfig) { EngineRequest engineRequest = ensureValidRequestConfig(requestConfig, GET); return request(engineRequest); } @Override public EngineResponse put(Map<String, Object> requestConfig) { EngineRequest engineRequest = ensureValidRequestConfig(requestConfig, PUT); return request(engineRequest); } @Override public EngineResponse post(Map<String, Object> requestConfig) { EngineRequest engineRequest = ensureValidRequestConfig(requestConfig, POST); return request(engineRequest); } @Override public EngineResponse delete(Map<String, Object> requestConfig) { EngineRequest engineRequest = ensureValidRequestConfig(requestConfig, DELETE); return request(engineRequest); } @Override public WebSocket webSocket(Map<String, Object> requestConfig, WebSocketListener listener) { EngineRequest engineRequest = ensureValidRequestConfig(requestConfig, GET); Request.Builder requestBuilder = prepareRequest(new Request.Builder(), engineRequest); Request request = requestBuilder.build(); OkHttpClient.Builder clientBuilder = prepareClient(new OkHttpClient.Builder(), engineRequest.getTimeout()); OkHttpClient client = newClient(clientBuilder); return client.newWebSocket(request, listener); } @Override public EngineResponse request(EngineRequest requestConfig) { EngineRequest config = ensureValidRequestConfig(requestConfig); AttachConfig attachConfig = null; if (config.getAttach() != null) { Map<String, String> headers = config.getHeaders(); if (headers == null) { headers = new HashMap<>(); } config.setHeaders(headers); // https://docs.docker.com/engine/api/v1.41/#operation/ContainerAttach // To hint potential proxies about connection hijacking, the Docker client sends connection upgrade headers. headers.put("Upgrade", "tcp"); headers.put("Connection", "Upgrade"); attachConfig = config.getAttach(); } // boolean multiplexStreams = config.multiplexStreams Request.Builder requestBuilder = prepareRequest(new Request.Builder(), config); final Request request = requestBuilder.build(); OkHttpClient.Builder clientBuilder = prepareClient(new OkHttpClient.Builder(), config.getTimeout()); OkResponseCallback responseCallback = null; if (attachConfig != null) { clientBuilder.addNetworkInterceptor(new HijackingInterceptor( attachConfig, attachConfig.getStreams().getStdin() == null ? null : Okio.source(attachConfig.getStreams().getStdin()), attachConfig.getStreams().getStdout() == null ? null : Okio.sink(attachConfig.getStreams().getStdout()))); responseCallback = new OkResponseCallback(attachConfig); } final OkHttpClient client = newClient(clientBuilder); log.debug(request.method() + " " + request.url() + " using proxy: " + client.proxy()); Call call = client.newCall(request); if (responseCallback != null) { call.enqueue(responseCallback); log.debug("request enqueued"); return new EngineResponse<Void>(); } else { EngineResponse dockerResponse; try { Response response = call.execute(); log.debug("response: " + response); dockerResponse = handleResponse(response, config); if (dockerResponse.getStream() == null) { // log.warn("closing response..."); response.close(); } } catch (Exception e) { log.error("Request failed", e); throw new RuntimeException("Request failed", e); } return dockerResponse; } } private Request.Builder prepareRequest(final Request.Builder builder, final EngineRequest config) { String method = config.getMethod().name(); String contentType = config.getContentType(); Map<String, String> additionalHeaders = config.getHeaders(); Object body = config.getBody(); String protocol = dockerClientConfig.getScheme(); String host = dockerClientConfig.getHost(); int port = dockerClientConfig.getPort(); String path = config.getPath(); if (config.getApiVersion() != null) { path = config.getApiVersion() + "/" + path; } String queryAsString; if (config.getQuery() != null) { queryAsString = queryToString(config.getQuery()); } else { queryAsString = ""; } HttpUrl.Builder urlBuilder = new HttpUrl.Builder().addPathSegments(path); if (queryAsString != null && !queryAsString.isEmpty()) { urlBuilder = urlBuilder.encodedQuery(queryAsString); // } else { // urlBuilder = urlBuilder.encodedQuery(null); } HttpUrl httpUrl = createUrl(urlBuilder, protocol, host, port); RequestBody requestBody = createRequestBody(method, contentType, body); builder.method(method, requestBody).url(httpUrl).cacheControl(CacheControl.FORCE_NETWORK); if (additionalHeaders != null) { additionalHeaders.forEach(builder::header); } return builder; } private OkHttpClient.Builder prepareClient(OkHttpClient.Builder builder, int currentTimeout) { String protocol = dockerClientConfig.getScheme(); switch (protocol) { case "unix": if (!socketFactories.containsKey(protocol)) { log.error("Unix domain socket not supported, but configured (using defaults?). Please consider changing the DOCKER_HOST environment setting to use tcp."); throw new IllegalStateException("Unix domain socket not supported."); } FileSocketFactory unixSocketFactory = (FileSocketFactory) socketFactories.get(protocol); builder .socketFactory(unixSocketFactory) .dns(unixSocketFactory) .build(); break; case "npipe": FileSocketFactory npipeSocketFactory = (FileSocketFactory) socketFactories.get(protocol); builder .socketFactory(npipeSocketFactory) .dns(npipeSocketFactory) .build(); break; case "https": String certPath = dockerClientConfig.getCertPath(); SslSocketConfigFactory sslSocketFactory = (SslSocketConfigFactory) socketFactories.get(protocol); DockerSslSocket dockerSslSocket = sslSocketFactory.createDockerSslSocket(certPath); if (dockerSslSocket != null) { builder .sslSocketFactory(dockerSslSocket.getSslSocketFactory(), dockerSslSocket.getTrustManager()) .build(); } break; } builder.proxy(proxy); // do we need to disable the timeout for streaming? builder .connectTimeout(currentTimeout, MILLISECONDS) .readTimeout(currentTimeout, MILLISECONDS); return builder; } public OkHttpClient newClient(OkHttpClient.Builder clientBuilder) { return clientBuilder.build(); } private HttpUrl createUrl(HttpUrl.Builder urlBuilder, String protocol, String host, int port) { HttpUrl httpUrl; switch (protocol) { case "unix": case "npipe": httpUrl = urlBuilder .scheme("http") .host(new HostnameEncoder().encode(host) + SOCKET_MARKER) .build(); break; default: httpUrl = urlBuilder .scheme(protocol) .host(host) .port(port) .build(); break; } return httpUrl; } private RequestBody createRequestBody(String method, String contentType, Object body) { if (body == null && HttpMethod.requiresRequestBody(method)) { return RequestBody.create("", MediaType.parse("application/json")); } RequestBody requestBody = null; if (body != null) { switch (contentType) { case "application/json": requestBody = RequestBody.create(moshi.adapter(Map.class).toJson((Map) body), MediaType.parse(contentType)); break; case "application/octet-stream": default: Source source = Okio.source((InputStream) body); BufferedSource buffer = Okio.buffer(source); requestBody = new StreamingRequestBody(MediaType.parse(contentType), buffer); break; } } return requestBody; } public EngineResponse handleResponse(Response httpResponse, EngineRequest config) throws IOException { final EngineResponse response = readHeaders(httpResponse); if (response.getStatus().getCode() == 204) { if (response.getStream() != null) { // redirect the response body to /dev/null, since it's expected to be empty IOUtils.consumeToDevNull(response.getStream()); } return response; } ResponseBody body = httpResponse.body(); String mimeType = response.getMimeType(); if (mimeType == null) { mimeType = ""; } switch (mimeType) { case "application/vnd.docker.multiplexed-stream": case "application/vnd.docker.raw-stream": InputStream rawStream = new RawInputStream(body.byteStream()); if (config.getStdout() != null) { log.debug("redirecting to stdout."); IOUtils.copy(rawStream, config.getStdout()); response.setStream(null); } else { response.setStream(rawStream); } break; case "application/json": if (config.isAsync()) { consumeResponseBody(response, body.source(), config); } else { Object content = new JsonContentHandler().getContent(body.source()); consumeResponseBody(response, content, config); } break; case "text/html": case "text/plain": InputStream text = body.byteStream(); consumeResponseBody(response, text, config); break; case "application/octet-stream": InputStream octet = body.byteStream(); if (config.getStdout() != null) { log.debug("redirecting to stdout."); IOUtils.copy(octet, config.getStdout()); response.setStream(null); } else { log.debug("passing through via `response.stream`."); response.setStream(octet); } break; case "application/x-tar": if (response.getStream() != null) { if (config.getStdout() != null) { log.debug("redirecting to stdout."); IOUtils.copy(response.getStream(), config.getStdout()); response.setStream(null); } else { log.info(response.getMimeType() + " stream won't be consumed, but is available in the response."); } } break; default: if (body == null || body.contentLength() == 0) { response.setContent(body == null ? null : body.string()); response.setStream(null); return response; } log.debug("unexpected mime type '" + response.getMimeType() + "'."); if (body.contentLength() == -1) { InputStream stream = body.byteStream(); if (config.getStdout() != null) { log.debug("redirecting to stdout."); IOUtils.copy(stream, config.getStdout()); response.setStream(null); } else { log.debug("passing through via `response.stream`."); response.setStream(stream); } } else { log.debug("passing through via `response.content`."); response.setContent(body.string()); response.setStream(null); } break; } return response; } private EngineResponse readHeaders(Response httpResponse) { final EngineResponse dockerResponse = new EngineResponse(); EngineResponseStatus status = new EngineResponseStatus(); status.setText(httpResponse.message()); status.setCode(httpResponse.code()); status.setSuccess(httpResponse.isSuccessful()); dockerResponse.setStatus(status); log.trace("status: " + dockerResponse.getStatus()); final Headers headers = httpResponse.headers(); log.trace("headers: \n" + headers); dockerResponse.setHeaders(headers); String contentType = headers.get("content-type"); dockerResponse.setContentType(contentType); String contentLength = headers.get("content-length"); if (contentLength == null) { contentLength = "-1"; } dockerResponse.setContentLength(contentLength); String mimeType = getMimeType(contentType); dockerResponse.setMimeType(mimeType); if (dockerResponse.getStatus().getSuccess()) { dockerResponse.setStream(httpResponse.body().byteStream()); } else { dockerResponse.setStream(null); } return dockerResponse; } private void consumeResponseBody(EngineResponse response, Object content, EngineRequest config) throws IOException { if (content instanceof Source) { if (config.isAsync()) { response.setStream(Okio.buffer((Source) content).inputStream()); } else if (config.getStdout() != null) { response.setStream(null); Okio.buffer(Okio.sink(config.getStdout())).writeAll((Source) content); } else if (response.getContentLength() != null && Integer.parseInt(response.getContentLength()) >= 0) { response.setStream(null); response.setContent(Okio.buffer((Source) content).readUtf8()); } else { response.setStream(Okio.buffer((Source) content).inputStream()); } } else if (content instanceof InputStream) { if (config.isAsync()) { response.setStream((InputStream) content); } else if (config.getStdout() != null) { IOUtils.copy((InputStream) content, config.getStdout()); response.setStream(null); } else if (response.getContentLength() != null && Integer.parseInt(response.getContentLength()) >= 0) { response.setContent(IOUtils.toString((InputStream) content)); response.setStream(null); } else { response.setStream((InputStream) content); } } else { response.setContent(content); response.setStream(null); } } /** * @see #ensureValidRequestConfig(EngineRequest) * @deprecated use ensureValidRequestConfig(EngineRequest) */ @Deprecated private EngineRequest ensureValidRequestConfig(final Map<String, Object> config, RequestMethod method) { if (config == null || config.get("path") == null) { log.error("bad request config: " + config); throw new IllegalArgumentException("bad request config"); } if (((String) config.get("path")).startsWith("/")) { config.put("path", ((String) config.get("path")).substring("/".length())); } config.put("method", method.name()); EngineRequest engineRequest = new EngineRequest(method, (String) config.get("path")); engineRequest.setTimeout(config.get("timeout") == null ? 0 : (Integer) config.get("timeout")); engineRequest.setHeaders((Map<String, String>) config.get("headers")); Map<String, Object> query = (Map<String, Object>) config.get("query"); engineRequest.setQuery(coerceValuesToListOfString(query)); engineRequest.setContentType((String) config.get("requestContentType")); engineRequest.setBody(config.get("body")); engineRequest.setAsync(config.get("async") != null && (Boolean) config.get("async")); engineRequest.setAttach((AttachConfig) config.get("attach")); engineRequest.setStdout((OutputStream) config.get("stdout")); engineRequest.setApiVersion((String) config.get("apiVersion")); return engineRequest; } private EngineRequest ensureValidRequestConfig(final EngineRequest config) { if (config == null || config.getPath() == null) { log.error("bad request config: " + config); throw new IllegalArgumentException("bad request config"); } if ((config.getPath()).startsWith("/")) { config.setPath(config.getPath().substring("/".length())); } return config; } private Map<String, List<String>> coerceValuesToListOfString(Map<String, Object> queryParameters) { if (queryParameters == null || queryParameters.isEmpty()) { return new HashMap<>(); } return queryParameters.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, ((Map.Entry<String, Object> e) -> convert(e.getValue())))); } private List<String> convert(Object value) { if (value instanceof String[]) { return Arrays.stream((String[]) value).collect(Collectors.toList()); } else if (value instanceof Collection) { return ((Collection<Object>) value).stream() .map(Object::toString) .collect(Collectors.toList()); } else if (value != null) { return Collections.singletonList(value.toString()); } else { return Collections.singletonList(""); } } public String queryToString(Map<String, List<String>> queryParameters) { if (queryParameters == null || queryParameters.isEmpty()) { return ""; } return queryParameters.entrySet().stream() .map((Map.Entry<String, List<String>> e) -> { String key = e.getKey(); List<String> value = e.getValue(); if (value != null) { return value.stream() .map((s) -> asUrlEncodedQuery(key, s)) .collect(Collectors.joining("&")); } else { return asUrlEncodedQuery(key, ""); } }) .collect(Collectors.joining("&")); } private String asUrlEncodedQuery(String key, String value) { try { return URLEncoder.encode(key, "UTF-8") + "=" + URLEncoder.encode(value, "UTF-8"); } catch (UnsupportedEncodingException e) { log.error("Url encoding failed for key=" + key + ",value=" + value, e); throw new RuntimeException("Url encoding failed", e); } } public String getMimeType(String contentTypeHeader) { if (contentTypeHeader == null) { return null; } return contentTypeHeader.replace(" ", "").split(";")[0]; } public String getCharset(String contentTypeHeader) { String charset = "utf-8"; Matcher matcher = Pattern.compile("[^;]+;\\s*charset=([^;]+)(;[^;]*)*").matcher(contentTypeHeader); if (matcher.find()) { charset = matcher.group(1); } return charset; } Map<String, Object> getSocketFactories() { return socketFactories; } DockerClientConfig getDockerClientConfig() { return dockerClientConfig; } void setProxy(Proxy proxy) { this.proxy = proxy; } }
true
befabfa07c510b79d400b584948a8d644afecd84
Java
dropwizard/dropwizard
/dropwizard-jackson/src/test/java/io/dropwizard/jackson/JacksonTest.java
UTF-8
2,371
2.3125
2
[ "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
permissive
package io.dropwizard.jackson; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.checkerframework.checker.nullness.qual.Nullable; import org.junit.jupiter.api.Test; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import static org.assertj.core.api.Assertions.assertThat; class JacksonTest { @Test void objectMapperUsesGivenCustomJsonFactory() { JsonFactory factory = new JsonFactory(); ObjectMapper mapper = Jackson.newObjectMapper(factory); assertThat(mapper.getFactory()).isSameAs(factory); } @Test void objectMapperCanHandleNullInsteadOfCustomJsonFactory() { ObjectMapper mapper = Jackson.newObjectMapper(null); assertThat(mapper.getFactory()).isNotNull(); } @Test void objectMapperCanDeserializeJdk7Types() throws IOException { final LogMetadata metadata = Jackson.newObjectMapper() .readValue("{\"path\": \"/var/log/app/server.log\"}", LogMetadata.class); assertThat(metadata).isNotNull(); assertThat(metadata.path).isEqualTo(Paths.get("/var/log/app/server.log")); } @Test void objectMapperSerializesNullValues() throws IOException { final ObjectMapper mapper = Jackson.newObjectMapper(); final Issue1627 pojo = new Issue1627(null, null); final String json = "{\"string\":null,\"uuid\":null}"; assertThat(mapper.writeValueAsString(pojo)).isEqualTo(json); } @Test void objectMapperIgnoresUnknownProperties() throws JsonProcessingException { assertThat(Jackson.newObjectMapper() .readValue("{\"unknown\": 4711, \"path\": \"/var/log/app/objectMapperIgnoresUnknownProperties.log\"}", LogMetadata.class) .path) .hasFileName("objectMapperIgnoresUnknownProperties.log"); } @Test void objectMapperRegistersAfterburnerButNotBlackbird() { assertThat(Jackson.newObjectMapper().getRegisteredModuleIds()) .contains("com.fasterxml.jackson.module.afterburner.AfterburnerModule") .doesNotContain("com.fasterxml.jackson.module.blackbird.BlackbirdModule"); } static class LogMetadata { @Nullable public Path path; } }
true
09b178cec15ce521b1d89a995efcb81461cd93a6
Java
Reynault/ACL_2019_Zelpop
/src/model/dungeon/scoring/Scoring.java
UTF-8
632
2.78125
3
[]
no_license
package model.dungeon.scoring; import model.dungeon.entity.Entity; import model.dungeon.tile.Tile; import java.io.Serializable; public class Scoring implements Serializable { private int score; private int multiplier; Scoring(int multiplier, int score) { this.score = score; this.multiplier = multiplier; } public double killMonster(Entity entity) { return entity.getValue() * entity.getMultiplier() * multiplier; } public int leaveMaze() { return score * multiplier; } public int findChest(Tile tile) { return tile.getGold() * multiplier; } }
true
cf4bfbad4c01743474e1593b014499e5bffdf91f
Java
heming2018/daily-practice
/algorithm-practice/src/main/java/leetcode/LC23_mergeKLists.java
UTF-8
2,810
3.8125
4
[]
no_license
package leetcode; /** * @author heming1 * @date 2021/7/24 2:02 下午 * @description 23. 合并K个升序链表 * 给你一个链表数组,每个链表都已经按升序排列。 * 请你将所有链表合并到一个升序链表中,返回合并后的链表。 */ public class LC23_mergeKLists { static class ListNode { int val; ListNode next; ListNode() { } ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val; this.next = next; } } /** * 分治思想 */ public ListNode mergeKLists0(ListNode[] lists) { if (lists == null || lists.length == 0) { return null; } return merge(lists, 0, lists.length - 1); } public ListNode merge(ListNode[] lists, int left, int right) { if (left == right) { return lists[left]; } int mid = left + (right - left) / 2; ListNode l1 = merge(lists, left, mid); ListNode l2 = merge(lists, mid + 1, right); return mergeTwoList(l1, l2); } /** * 转化为TwoMerge思想 */ public ListNode mergeKLists1(ListNode[] lists) { if (lists == null || lists.length == 0) { return null; } ListNode res = lists[0]; for (int i = 1; i < lists.length; i++) { res = mergeTwoList(res, lists[i]); } return res; } ListNode mergeTwoList(ListNode list1, ListNode list2) { ListNode head = new ListNode(); ListNode curr = head; while (list1 != null && list2 != null) { if (list1.val < list2.val) { curr.next = list1; list1 = list1.next; } else { curr.next = list2; list2 = list2.next; } curr = curr.next; } if (list1 != null) { curr.next = list1; } if (list2 != null) { curr.next = list2; } return head.next; } public static void main(String[] args) { ListNode[] input = new ListNode[3]; ListNode head1 = new ListNode(1); head1.next = new ListNode(2); head1.next.next = new ListNode(3); input[0] = head1; ListNode head2 = new ListNode(4); head2.next = new ListNode(5); head2.next.next = new ListNode(6); head2.next.next.next = new ListNode(7); input[1] = head2; ListNode head3 = new ListNode(6); head3.next = new ListNode(7); head3.next.next = new ListNode(8); head3.next.next.next = new ListNode(9); input[2] = head3; new LC23_mergeKLists().mergeKLists0(input); } }
true
c3af95bdc6a273a7ef0da8b129ae98cbdddeca14
Java
Cloud4SOA/Cloud4SOA
/cli/trunk/cli-roo/src/main/java/eu/cloud4soa/cli/roo/addon/commands/GitManager.java
UTF-8
10,376
1.75
2
[]
no_license
/* * Copyright 2013 Cloud4SOA, www.cloud4soa.eu * * 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. */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package eu.cloud4soa.cli.roo.addon.commands; import com.jcraft.jsch.JSch; import com.jcraft.jsch.JSchException; import com.jcraft.jsch.Session; import eu.cloud4soa.cli.roo.addon.Cloud4SoaSessionDeveloper; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URISyntaxException; import java.util.Iterator; import java.util.Map; import org.eclipse.jgit.api.AddCommand; import org.eclipse.jgit.api.CommitCommand; import org.eclipse.jgit.api.FetchCommand; import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.PullCommand; import org.eclipse.jgit.api.PullResult; import org.eclipse.jgit.api.PushCommand; import org.eclipse.jgit.api.Status; import org.eclipse.jgit.api.errors.GitAPIException; import org.eclipse.jgit.lib.BranchConfig; import org.eclipse.jgit.lib.Ref; import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.lib.StoredConfig; import org.eclipse.jgit.merge.Merger; import org.eclipse.jgit.merge.ResolveMerger; import org.eclipse.jgit.merge.ThreeWayMerger; import org.eclipse.jgit.storage.file.FileRepository; import org.eclipse.jgit.storage.file.FileRepositoryBuilder; import org.eclipse.jgit.transport.JschConfigSessionFactory; import org.eclipse.jgit.transport.OpenSshConfig.Host; import org.eclipse.jgit.transport.PushResult; import org.eclipse.jgit.transport.RefSpec; import org.eclipse.jgit.transport.RemoteConfig; import org.eclipse.jgit.transport.SshSessionFactory; import org.eclipse.jgit.transport.URIish; import org.eclipse.jgit.util.FS; import java.util.logging.Logger; /** * * @author frarav */ public class GitManager { private static final Logger logger = Logger.getLogger(GitManager.class.getName()); protected Cloud4SoaSessionDeveloper session; protected String repoName; protected String localPath; private Git git; private PushCommand pushCommand; private PullCommand pullCommand; private AddCommand addCommand; private CommitCommand commitCommand; private Repository gitRepository; private final String sshKeyDir; private final String passphrase; private final String gitProxyUrl; public GitManager(String gitProxyUrl, String repoName, String localPath, String sshKeyDir, String passphrase) { this.repoName = repoName; this.localPath = localPath; this.sshKeyDir = sshKeyDir; this.passphrase = passphrase; this.gitProxyUrl = gitProxyUrl; } public void testStatus() throws IOException, GitAPIException { Status status = git.status().call(); logger.info( "Local Git Repository status"); logger.info( "- "+ (status.isClean() ? "Clean" : "Not clean") ); logger.info( "- "+ (status.getAdded().isEmpty() ? "No files added" : "Files added: " + status.getAdded())); logger.info( "- "+ (status.getChanged().isEmpty() ? "No files changed" : "Files added: " + status.getChanged() )); logger.info( "- "+ (status.getUntracked().isEmpty() ? "All files are tracked" : "Files untracked: " + status.getUntracked() )); } public void init() throws Exception { FileRepositoryBuilder builder; gitRepository = new FileRepository(localPath + "/" + ".git"); builder = new FileRepositoryBuilder(); gitRepository = builder.setGitDir(new File( localPath + "/.git")).readEnvironment().findGitDir().build(); git = new Git( gitRepository ); GithubSshSessionFactory factory = new GithubSshSessionFactory(); factory.setKeyLocation(sshKeyDir); factory.setPassphrase(passphrase); SshSessionFactory.setInstance(factory); } public void setConfig() throws URISyntaxException, IOException, GitAPIException{ StoredConfig config = gitRepository.getConfig(); if(config.getString("remote", repoName, "url") == null || config.getString("remote", repoName, "url")!=gitProxyUrl){ config.unset("remote", repoName, "url"); RemoteConfig remoteConfig = new RemoteConfig(config, repoName); //cloud@94.75.243.141/proxyname.git //proxy<userid><applicationid>.git” // String gitUrl = gitUser+"@"+gitProxyUrl+"/proxy"+this.userId+this.applicationId+".git"; URIish uri = new URIish(gitProxyUrl); remoteConfig.addURI(uri); config.unset("remote", repoName, "fetch"); RefSpec spec = new RefSpec("+refs/heads/*:refs/remotes/"+repoName+"/*"); remoteConfig.addFetchRefSpec(spec); remoteConfig.update(config); } if(config.getString("branch", "master", "remote")==null || config.getString("branch", "master", "remote")!=repoName){ config.unset("branch", "master", "remote"); config.setString("branch", "master", "remote", repoName); } if(config.getString("branch", "master", "merge")==null || config.getString("branch", "master", "merge")!="refs/heads/master"){ config.unset("branch", "master", "merge"); config.setString("branch", "master", "merge", "refs/heads/master"); } config.save(); } public void removeAll() throws GitAPIException{ addCommand = git.add(); addCommand.addFilepattern("."); //Needed to track all the removed files addCommand.setUpdate(true); addCommand.call(); } public void addAll() throws GitAPIException{ addCommand = git.add(); addCommand.addFilepattern("."); addCommand.call(); } public void commit() throws GitAPIException{ commitCommand = git.commit(); //git commit -m "commit for deploy to heroku" commitCommand.setMessage("commit for deploy through cloud4soa"); commitCommand.call(); } public void push() throws GitAPIException{ pushCommand = git.push(); pushCommand.setRemote( repoName ); logger.info("Performing the git push command"); Iterable<PushResult> call = pushCommand.call(); // for (PushResult pushResult : call) { // logger.info("push result:"+pushResult.getMessages()); // } } public void fetch() throws GitAPIException{ FetchCommand fetchCommand = git.fetch(); fetchCommand.setRemote( repoName ); fetchCommand.call(); } public void pull() throws GitAPIException, IOException{ pullCommand = git.pull(); logger.info("Performing the git pull/merge command"); PullResult pullResult = pullCommand.call(); logger.info("Fetched From: "+pullResult.getFetchedFrom()); logger.info("Fetch Result: "+pullResult.getFetchResult().getMessages()); logger.info("Merge Result:"+pullResult.getMergeResult()); logger.info("Rebase Result:"+pullResult.getRebaseResult()); logger.info(pullResult.isSuccessful() ? "Pull/Merge success" : "Failed to Pull/Merge"); } public static class GithubSshSessionFactory extends JschConfigSessionFactory { private String passphrase; private String key; public void setPassphrase(String passphrase) { this.passphrase = passphrase; } public void setKeyLocation(String key) { this.key = key; } @Override protected void configure(Host hc, Session session) { // do nothing session.setConfig("StrictHostKeyChecking", "no"); } @Override protected JSch createDefaultJSch(FS fs) throws JSchException { final JSch jsch = new JSch(); knownHosts(jsch, fs); if (key != null) { jsch.addIdentity(new File(key).getAbsolutePath(), passphrase); logger.info(".ssh directory used: "+new File(key).getAbsolutePath()); } else { final File home = fs.userHome(); if (home == null) { return jsch; } final File sshdir = new File(home, ".ssh"); if (sshdir.isDirectory()) { jsch.addIdentity(new File(sshdir, "id_rsa").getAbsolutePath(), passphrase); logger.info(".ssh directory used: "+sshdir.getAbsolutePath()); } } return jsch; } private static void knownHosts(final JSch sch, FS fs) throws JSchException { final File home = fs.userHome(); if (home == null) { return; } final File known_hosts = new File(new File(home, ".ssh"), "known_hosts"); try { final FileInputStream in = new FileInputStream(known_hosts); try { logger.info("Try to read the ssh known_hosts file: "+known_hosts.getAbsolutePath()); sch.setKnownHosts(in); } finally { in.close(); } } catch (FileNotFoundException none) { // Oh well. They don't have a known hosts in home. logger.severe("known_hosts file not found: "+known_hosts.getAbsolutePath()); } catch (IOException err) { // Oh well. They don't have a known hosts in home. logger.severe("Error while reading the known_hosts file: "+err.getMessage()); } } } }
true
763ea06cc7dce6729d44bb71a27e38371b70f0c6
Java
chan21252/SpringDemo
/SpringTransaction/src/com/chan/spring/tx/service/Cashier.java
UTF-8
239
1.835938
2
[]
no_license
package com.chan.spring.tx.service; import java.util.List; /** * 收银服务接口 * * @author Chan */ public interface Cashier { /** * 结账方法 */ public void checkOut(String username, List<String> isbns); }
true
a73b5e5507abc774be511ed4ab4c82c9f6bc14d6
Java
angshumanbhattacharjee/mongodbdemo
/src/main/java/com/example/demo/service/UserService.java
UTF-8
525
2.21875
2
[]
no_license
package com.example.demo.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.example.demo.model.User; import com.example.demo.repository.UserRepository; @Service public class UserService { @Autowired private UserRepository repo; public User create(String name, String password, String address) { return repo.save(new User(name,password,address)); } public User findByFirstName(String name) { return repo.findByName(name); } }
true
dd2e26f5bbdf669b30e0ca879a4d2cd0b1dae0c4
Java
SNeginMortazavi/Practice-Code
/Array/src/shortestWordDistance/ShortestWordDistance.java
UTF-8
1,579
3.90625
4
[]
no_license
package shortestWordDistance; public class ShortestWordDistance { /** * brute force method * Time complexity: O(n^2) * space complexity: O(1) * @param words * @param word1 * @param word2 * @return */ public int shortestDistance(String[] words, String word1, String word2) { int minDsitance = words.length; for(int i = 0; i < words.length; i++){ if(words[i].equals(word1)){ for(int j = 0; j < words.length; j++){ if(words[j].equals(word2)){ minDsitance = Math.min(minDsitance, Math.abs(i - j)); } } } } return minDsitance; } /** * The faster method * Time complexity: O(n) * Space Complexity: O(1) * @param words * @param word1 * @param word2 * @return */ public int shortestDistance2(String[] words, String word1, String word2) { int minDsitance = words.length; int i = -1; int j = -1; for(int m = 0; m < words.length; m++){ if(words[m].equals(word1)) i = m; else if(words[m].equals(word2)) j = m; if(i != -1 && j != -1) { minDsitance = Math.min(minDsitance, Math.abs(i - j)); } } return minDsitance; } public static void main(String[] args){ ShortestWordDistance appDistance = new ShortestWordDistance(); String[] wordsStrings = {"practice", "makes", "perfect", "coding", "makes"}; String word1 = "coding"; String word2 = "makes"; int result = appDistance.shortestDistance2(wordsStrings, word1, word2); System.out.println(result); } }
true
1a9a3c0a365fc162cbf57701b64d798ea149d06d
Java
FabianMeiswinkel/azure-sdk-for-java
/sdk/datamigration/mgmt-v2018_07_15_preview/src/main/java/com/microsoft/azure/management/datamigration/v2018_07_15_preview/GetUserTablesOracleTaskInput.java
UTF-8
2,087
1.984375
2
[ "MIT", "LicenseRef-scancode-generic-cla", "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-or-later", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.datamigration.v2018_07_15_preview; import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; /** * Input for the task that gets the list of tables contained within a provided * list of Oracle schemas. */ public class GetUserTablesOracleTaskInput { /** * Information for connecting to Oracle source. */ @JsonProperty(value = "connectionInfo", required = true) private OracleConnectionInfo connectionInfo; /** * List of Oracle schemas for which to collect tables. */ @JsonProperty(value = "selectedSchemas", required = true) private List<String> selectedSchemas; /** * Get information for connecting to Oracle source. * * @return the connectionInfo value */ public OracleConnectionInfo connectionInfo() { return this.connectionInfo; } /** * Set information for connecting to Oracle source. * * @param connectionInfo the connectionInfo value to set * @return the GetUserTablesOracleTaskInput object itself. */ public GetUserTablesOracleTaskInput withConnectionInfo(OracleConnectionInfo connectionInfo) { this.connectionInfo = connectionInfo; return this; } /** * Get list of Oracle schemas for which to collect tables. * * @return the selectedSchemas value */ public List<String> selectedSchemas() { return this.selectedSchemas; } /** * Set list of Oracle schemas for which to collect tables. * * @param selectedSchemas the selectedSchemas value to set * @return the GetUserTablesOracleTaskInput object itself. */ public GetUserTablesOracleTaskInput withSelectedSchemas(List<String> selectedSchemas) { this.selectedSchemas = selectedSchemas; return this; } }
true
5aa25db414bbe079db8544d7df510745d9be201d
Java
jitianjue666/Dcxt3
/src/main/java/com/vo/ShopExample.java
UTF-8
22,572
2.25
2
[]
no_license
package com.vo; import java.util.ArrayList; import java.util.Date; import java.util.List; public class ShopExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public ShopExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andShopnoIsNull() { addCriterion("shopno is null"); return (Criteria) this; } public Criteria andShopnoIsNotNull() { addCriterion("shopno is not null"); return (Criteria) this; } public Criteria andShopnoEqualTo(Integer value) { addCriterion("shopno =", value, "shopno"); return (Criteria) this; } public Criteria andShopnoNotEqualTo(Integer value) { addCriterion("shopno <>", value, "shopno"); return (Criteria) this; } public Criteria andShopnoGreaterThan(Integer value) { addCriterion("shopno >", value, "shopno"); return (Criteria) this; } public Criteria andShopnoGreaterThanOrEqualTo(Integer value) { addCriterion("shopno >=", value, "shopno"); return (Criteria) this; } public Criteria andShopnoLessThan(Integer value) { addCriterion("shopno <", value, "shopno"); return (Criteria) this; } public Criteria andShopnoLessThanOrEqualTo(Integer value) { addCriterion("shopno <=", value, "shopno"); return (Criteria) this; } public Criteria andShopnoIn(List<Integer> values) { addCriterion("shopno in", values, "shopno"); return (Criteria) this; } public Criteria andShopnoNotIn(List<Integer> values) { addCriterion("shopno not in", values, "shopno"); return (Criteria) this; } public Criteria andShopnoBetween(Integer value1, Integer value2) { addCriterion("shopno between", value1, value2, "shopno"); return (Criteria) this; } public Criteria andShopnoNotBetween(Integer value1, Integer value2) { addCriterion("shopno not between", value1, value2, "shopno"); return (Criteria) this; } public Criteria andOwnernoIsNull() { addCriterion("ownerno is null"); return (Criteria) this; } public Criteria andOwnernoIsNotNull() { addCriterion("ownerno is not null"); return (Criteria) this; } public Criteria andOwnernoEqualTo(Integer value) { addCriterion("ownerno =", value, "ownerno"); return (Criteria) this; } public Criteria andOwnernoNotEqualTo(Integer value) { addCriterion("ownerno <>", value, "ownerno"); return (Criteria) this; } public Criteria andOwnernoGreaterThan(Integer value) { addCriterion("ownerno >", value, "ownerno"); return (Criteria) this; } public Criteria andOwnernoGreaterThanOrEqualTo(Integer value) { addCriterion("ownerno >=", value, "ownerno"); return (Criteria) this; } public Criteria andOwnernoLessThan(Integer value) { addCriterion("ownerno <", value, "ownerno"); return (Criteria) this; } public Criteria andOwnernoLessThanOrEqualTo(Integer value) { addCriterion("ownerno <=", value, "ownerno"); return (Criteria) this; } public Criteria andOwnernoIn(List<Integer> values) { addCriterion("ownerno in", values, "ownerno"); return (Criteria) this; } public Criteria andOwnernoNotIn(List<Integer> values) { addCriterion("ownerno not in", values, "ownerno"); return (Criteria) this; } public Criteria andOwnernoBetween(Integer value1, Integer value2) { addCriterion("ownerno between", value1, value2, "ownerno"); return (Criteria) this; } public Criteria andOwnernoNotBetween(Integer value1, Integer value2) { addCriterion("ownerno not between", value1, value2, "ownerno"); return (Criteria) this; } public Criteria andShopnameIsNull() { addCriterion("shopname is null"); return (Criteria) this; } public Criteria andShopnameIsNotNull() { addCriterion("shopname is not null"); return (Criteria) this; } public Criteria andShopnameEqualTo(String value) { addCriterion("shopname =", value, "shopname"); return (Criteria) this; } public Criteria andShopnameNotEqualTo(String value) { addCriterion("shopname <>", value, "shopname"); return (Criteria) this; } public Criteria andShopnameGreaterThan(String value) { addCriterion("shopname >", value, "shopname"); return (Criteria) this; } public Criteria andShopnameGreaterThanOrEqualTo(String value) { addCriterion("shopname >=", value, "shopname"); return (Criteria) this; } public Criteria andShopnameLessThan(String value) { addCriterion("shopname <", value, "shopname"); return (Criteria) this; } public Criteria andShopnameLessThanOrEqualTo(String value) { addCriterion("shopname <=", value, "shopname"); return (Criteria) this; } public Criteria andShopnameLike(String value) { addCriterion("shopname like", value, "shopname"); return (Criteria) this; } public Criteria andShopnameNotLike(String value) { addCriterion("shopname not like", value, "shopname"); return (Criteria) this; } public Criteria andShopnameIn(List<String> values) { addCriterion("shopname in", values, "shopname"); return (Criteria) this; } public Criteria andShopnameNotIn(List<String> values) { addCriterion("shopname not in", values, "shopname"); return (Criteria) this; } public Criteria andShopnameBetween(String value1, String value2) { addCriterion("shopname between", value1, value2, "shopname"); return (Criteria) this; } public Criteria andShopnameNotBetween(String value1, String value2) { addCriterion("shopname not between", value1, value2, "shopname"); return (Criteria) this; } public Criteria andShopstateIsNull() { addCriterion("shopstate is null"); return (Criteria) this; } public Criteria andShopstateIsNotNull() { addCriterion("shopstate is not null"); return (Criteria) this; } public Criteria andShopstateEqualTo(Integer value) { addCriterion("shopstate =", value, "shopstate"); return (Criteria) this; } public Criteria andShopstateNotEqualTo(Integer value) { addCriterion("shopstate <>", value, "shopstate"); return (Criteria) this; } public Criteria andShopstateGreaterThan(Integer value) { addCriterion("shopstate >", value, "shopstate"); return (Criteria) this; } public Criteria andShopstateGreaterThanOrEqualTo(Integer value) { addCriterion("shopstate >=", value, "shopstate"); return (Criteria) this; } public Criteria andShopstateLessThan(Integer value) { addCriterion("shopstate <", value, "shopstate"); return (Criteria) this; } public Criteria andShopstateLessThanOrEqualTo(Integer value) { addCriterion("shopstate <=", value, "shopstate"); return (Criteria) this; } public Criteria andShopstateIn(List<Integer> values) { addCriterion("shopstate in", values, "shopstate"); return (Criteria) this; } public Criteria andShopstateNotIn(List<Integer> values) { addCriterion("shopstate not in", values, "shopstate"); return (Criteria) this; } public Criteria andShopstateBetween(Integer value1, Integer value2) { addCriterion("shopstate between", value1, value2, "shopstate"); return (Criteria) this; } public Criteria andShopstateNotBetween(Integer value1, Integer value2) { addCriterion("shopstate not between", value1, value2, "shopstate"); return (Criteria) this; } public Criteria andShopapplytimeIsNull() { addCriterion("shopapplytime is null"); return (Criteria) this; } public Criteria andShopapplytimeIsNotNull() { addCriterion("shopapplytime is not null"); return (Criteria) this; } public Criteria andShopapplytimeEqualTo(Date value) { addCriterion("shopapplytime =", value, "shopapplytime"); return (Criteria) this; } public Criteria andShopapplytimeNotEqualTo(Date value) { addCriterion("shopapplytime <>", value, "shopapplytime"); return (Criteria) this; } public Criteria andShopapplytimeGreaterThan(Date value) { addCriterion("shopapplytime >", value, "shopapplytime"); return (Criteria) this; } public Criteria andShopapplytimeGreaterThanOrEqualTo(Date value) { addCriterion("shopapplytime >=", value, "shopapplytime"); return (Criteria) this; } public Criteria andShopapplytimeLessThan(Date value) { addCriterion("shopapplytime <", value, "shopapplytime"); return (Criteria) this; } public Criteria andShopapplytimeLessThanOrEqualTo(Date value) { addCriterion("shopapplytime <=", value, "shopapplytime"); return (Criteria) this; } public Criteria andShopapplytimeIn(List<Date> values) { addCriterion("shopapplytime in", values, "shopapplytime"); return (Criteria) this; } public Criteria andShopapplytimeNotIn(List<Date> values) { addCriterion("shopapplytime not in", values, "shopapplytime"); return (Criteria) this; } public Criteria andShopapplytimeBetween(Date value1, Date value2) { addCriterion("shopapplytime between", value1, value2, "shopapplytime"); return (Criteria) this; } public Criteria andShopapplytimeNotBetween(Date value1, Date value2) { addCriterion("shopapplytime not between", value1, value2, "shopapplytime"); return (Criteria) this; } public Criteria andShopadopttimeIsNull() { addCriterion("shopadopttime is null"); return (Criteria) this; } public Criteria andShopadopttimeIsNotNull() { addCriterion("shopadopttime is not null"); return (Criteria) this; } public Criteria andShopadopttimeEqualTo(Date value) { addCriterion("shopadopttime =", value, "shopadopttime"); return (Criteria) this; } public Criteria andShopadopttimeNotEqualTo(Date value) { addCriterion("shopadopttime <>", value, "shopadopttime"); return (Criteria) this; } public Criteria andShopadopttimeGreaterThan(Date value) { addCriterion("shopadopttime >", value, "shopadopttime"); return (Criteria) this; } public Criteria andShopadopttimeGreaterThanOrEqualTo(Date value) { addCriterion("shopadopttime >=", value, "shopadopttime"); return (Criteria) this; } public Criteria andShopadopttimeLessThan(Date value) { addCriterion("shopadopttime <", value, "shopadopttime"); return (Criteria) this; } public Criteria andShopadopttimeLessThanOrEqualTo(Date value) { addCriterion("shopadopttime <=", value, "shopadopttime"); return (Criteria) this; } public Criteria andShopadopttimeIn(List<Date> values) { addCriterion("shopadopttime in", values, "shopadopttime"); return (Criteria) this; } public Criteria andShopadopttimeNotIn(List<Date> values) { addCriterion("shopadopttime not in", values, "shopadopttime"); return (Criteria) this; } public Criteria andShopadopttimeBetween(Date value1, Date value2) { addCriterion("shopadopttime between", value1, value2, "shopadopttime"); return (Criteria) this; } public Criteria andShopadopttimeNotBetween(Date value1, Date value2) { addCriterion("shopadopttime not between", value1, value2, "shopadopttime"); return (Criteria) this; } public Criteria andShopvolumeIsNull() { addCriterion("shopvolume is null"); return (Criteria) this; } public Criteria andShopvolumeIsNotNull() { addCriterion("shopvolume is not null"); return (Criteria) this; } public Criteria andShopvolumeEqualTo(Integer value) { addCriterion("shopvolume =", value, "shopvolume"); return (Criteria) this; } public Criteria andShopvolumeNotEqualTo(Integer value) { addCriterion("shopvolume <>", value, "shopvolume"); return (Criteria) this; } public Criteria andShopvolumeGreaterThan(Integer value) { addCriterion("shopvolume >", value, "shopvolume"); return (Criteria) this; } public Criteria andShopvolumeGreaterThanOrEqualTo(Integer value) { addCriterion("shopvolume >=", value, "shopvolume"); return (Criteria) this; } public Criteria andShopvolumeLessThan(Integer value) { addCriterion("shopvolume <", value, "shopvolume"); return (Criteria) this; } public Criteria andShopvolumeLessThanOrEqualTo(Integer value) { addCriterion("shopvolume <=", value, "shopvolume"); return (Criteria) this; } public Criteria andShopvolumeIn(List<Integer> values) { addCriterion("shopvolume in", values, "shopvolume"); return (Criteria) this; } public Criteria andShopvolumeNotIn(List<Integer> values) { addCriterion("shopvolume not in", values, "shopvolume"); return (Criteria) this; } public Criteria andShopvolumeBetween(Integer value1, Integer value2) { addCriterion("shopvolume between", value1, value2, "shopvolume"); return (Criteria) this; } public Criteria andShopvolumeNotBetween(Integer value1, Integer value2) { addCriterion("shopvolume not between", value1, value2, "shopvolume"); return (Criteria) this; } public Criteria andDcategoryIsNull() { addCriterion("dcategory is null"); return (Criteria) this; } public Criteria andDcategoryIsNotNull() { addCriterion("dcategory is not null"); return (Criteria) this; } public Criteria andDcategoryEqualTo(String value) { addCriterion("dcategory =", value, "dcategory"); return (Criteria) this; } public Criteria andDcategoryNotEqualTo(String value) { addCriterion("dcategory <>", value, "dcategory"); return (Criteria) this; } public Criteria andDcategoryGreaterThan(String value) { addCriterion("dcategory >", value, "dcategory"); return (Criteria) this; } public Criteria andDcategoryGreaterThanOrEqualTo(String value) { addCriterion("dcategory >=", value, "dcategory"); return (Criteria) this; } public Criteria andDcategoryLessThan(String value) { addCriterion("dcategory <", value, "dcategory"); return (Criteria) this; } public Criteria andDcategoryLessThanOrEqualTo(String value) { addCriterion("dcategory <=", value, "dcategory"); return (Criteria) this; } public Criteria andDcategoryLike(String value) { addCriterion("dcategory like", value, "dcategory"); return (Criteria) this; } public Criteria andDcategoryNotLike(String value) { addCriterion("dcategory not like", value, "dcategory"); return (Criteria) this; } public Criteria andDcategoryIn(List<String> values) { addCriterion("dcategory in", values, "dcategory"); return (Criteria) this; } public Criteria andDcategoryNotIn(List<String> values) { addCriterion("dcategory not in", values, "dcategory"); return (Criteria) this; } public Criteria andDcategoryBetween(String value1, String value2) { addCriterion("dcategory between", value1, value2, "dcategory"); return (Criteria) this; } public Criteria andDcategoryNotBetween(String value1, String value2) { addCriterion("dcategory not between", value1, value2, "dcategory"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
true
24fdbf0c73c02f603f8e7d8a991f314b89eb0970
Java
ioanarusaldas/Programare-Orientata-pe-Obiecte
/Termostat inteligent-tema2/Interval.java
UTF-8
714
3.1875
3
[]
no_license
import java.util.SortedSet; import java.util.TreeSet; /** * @author Savu Ioana Rusalda - 325CB * */ public class Interval { SortedSet <Double> set; SortedSet <Double> setH; /** * constructor default */ Interval(){ this.set = new TreeSet <Double>(); this.setH = new TreeSet <Double>(); } /** * Metoda adauga temperatura inregistrata in intervalul corespunzator * @param temp - temperatura inregistrata */ public void adaugT(Double temp) { set.add(temp); } /** * Metoda adauga umiditatea inregistrata in intervalul corespunzator * @param humidity - umiditatea inregistrata */ public void adaugH(Double humidity) { setH.add(humidity); } }
true
9588a4307ac728a62a71195255317914ebe25774
Java
jackyu86/sourceLib
/link-to-world/.svn/pristine/95/9588a4307ac728a62a71195255317914ebe25774.svn-base
UTF-8
2,624
2.203125
2
[]
no_license
package io.sited.file.service; import com.google.common.base.Strings; import com.google.common.io.Files; import io.sited.db.FindView; import io.sited.db.MongoRepository; import io.sited.file.api.file.BatchDeleteFileRequest; import io.sited.file.api.file.FileQuery; import io.sited.file.api.file.FileRequest; import io.sited.file.domain.Directory; import io.sited.file.domain.File; import org.bson.Document; import org.bson.types.ObjectId; import javax.inject.Inject; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; import java.util.regex.Pattern; import java.util.stream.Collectors; /** * @author chi */ public class FileService { @Inject MongoRepository<File> repository; @Inject DirectoryService directoryService; public File get(ObjectId id) { return repository.get(id); } public Optional<File> findByPath(String path) { return repository.query("path", path).findOne(); } public FindView<File> find(FileQuery query) { Document filter = new Document(); if (!Strings.isNullOrEmpty(query.title)) { filter.append("title", new Document("$regex", Pattern.compile(Pattern.quote(query.title)))); } if (query.directoryId != null) { List<Directory> directories = directoryService.allChildren(query.directoryId); filter.append("directory_id", new Document("$in", directories.stream().map(directory -> directory.id).collect(Collectors.toList()))); } else { filter.append("directory_id", null); } return repository.query(filter) .page(query.page).limit(query.limit) .sort("updated_time", true).find(); } public void create(File file) { repository.insert(file); } public File update(ObjectId id, FileRequest request) { File file = get(id); file.title = request.title; file.description = request.description; file.directoryId = request.directoryId; file.path = request.path; file.tags = request.tags; file.extension = Files.getFileExtension(request.path); file.length = request.length; file.updatedBy = request.requestBy; file.updatedTime = LocalDateTime.now(); repository.update(id, file); return file; } public boolean delete(ObjectId id) { return repository.delete(id); } public void batchDelete(BatchDeleteFileRequest request) { repository.batchDelete(request.ids); } public long count() { return repository.query().count(); } }
true
a945ca3746e3e21978abcff37ecc74e33aae5ac5
Java
freissmann/SolrPostFilter
/1_Basic/ModuloQuery.java
UTF-8
1,473
2.265625
2
[]
no_license
package de.qaware.blog.solr; import java.io.IOException; import org.apache.lucene.document.Document; import org.apache.lucene.index.AtomicReader; import org.apache.lucene.search.IndexSearcher; import org.apache.solr.search.DelegatingCollector; import org.apache.solr.search.ExtendedQueryBase; import org.apache.solr.search.PostFilter; public class ModuloQuery extends ExtendedQueryBase implements PostFilter { @Override public int getCost() { // We make sure that the cost is at least 100 to be a post filter return Math.max(super.getCost(), 100); } @Override public boolean getCache() { return false; } @Override public DelegatingCollector getFilterCollector(IndexSearcher idxS) { return new DelegatingCollector() { @Override public void collect(int docNumber) throws IOException { // To be able to get documents, we need the reader AtomicReader reader = context.reader(); // From the reader we get the current document by the docNumber Document currentDoc = reader.document(docNumber); // We get the id field from our document Number currentDocId = currentDoc.getField("id").numericValue(); // Filter magic if (currentDocId.intValue() % 42 == 0) { super.collect(docNumber); } } }; } }
true
4e35b6274ab2c2366fb3567f2469b2b3d6550734
Java
art-orient/orion
/src/main/java/com/art/orion/model/dao/impl/AccessoryJdbc.java
UTF-8
10,353
1.945313
2
[]
no_license
package com.art.orion.model.dao.impl; import com.art.orion.exception.OrionDatabaseException; import com.art.orion.model.entity.Accessory; import com.art.orion.model.entity.ProductDetails; import com.art.orion.model.pool.ConnectionPool; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import static com.art.orion.model.dao.column.AccessoriesColumn.ACCESSORIES_ID; import static com.art.orion.model.dao.column.AccessoriesColumn.ACCESSORIES_ID_INDEX; import static com.art.orion.model.dao.column.AccessoriesColumn.ACTIVE; import static com.art.orion.model.dao.column.AccessoriesColumn.ACTIVE_INDEX; import static com.art.orion.model.dao.column.AccessoriesColumn.AVAILABILITY; import static com.art.orion.model.dao.column.AccessoriesColumn.AVAILABILITY_INDEX; import static com.art.orion.model.dao.column.AccessoriesColumn.BRAND; import static com.art.orion.model.dao.column.AccessoriesColumn.BRAND_INDEX; import static com.art.orion.model.dao.column.AccessoriesColumn.COST; import static com.art.orion.model.dao.column.AccessoriesColumn.COST_INDEX; import static com.art.orion.model.dao.column.AccessoriesColumn.DESCRIPTION_EN; import static com.art.orion.model.dao.column.AccessoriesColumn.DESCRIPTION_EN_INDEX; import static com.art.orion.model.dao.column.AccessoriesColumn.DESCRIPTION_RU; import static com.art.orion.model.dao.column.AccessoriesColumn.DESCRIPTION_RU_INDEX; import static com.art.orion.model.dao.column.AccessoriesColumn.IMAGE_PATH; import static com.art.orion.model.dao.column.AccessoriesColumn.IMAGE_PATH_INDEX; import static com.art.orion.model.dao.column.AccessoriesColumn.MODEL_NAME; import static com.art.orion.model.dao.column.AccessoriesColumn.MODEL_NAME_INDEX; import static com.art.orion.model.dao.column.AccessoriesColumn.TYPE_EN; import static com.art.orion.model.dao.column.AccessoriesColumn.TYPE_EN_INDEX; import static com.art.orion.model.dao.column.AccessoriesColumn.TYPE_RU; import static com.art.orion.model.dao.column.AccessoriesColumn.TYPE_RU_INDEX; import static com.art.orion.util.Constant.DATABASE_EXCEPTION; /** * The {@code ProductDaoJdbc} class works with database table accessories * * @author Aliaksandr Artsikhovich * @version 1.0 */ public class AccessoryJdbc { private static final Logger logger = LogManager.getLogger(); private static final AccessoryJdbc INSTANCE = new AccessoryJdbc(); private static final String INSERT_ACCESSORY = "INSERT INTO accessories " + "(type_Ru, type_En, brand, model_name, description_RU, description_EN, image_path, cost, availability, active) " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; private static final String FIND_ACCESSORY_BY_ID = "SELECT accessories_id, type_Ru, type_En, brand, model_name, " + "description_RU, description_EN, image_path, cost, availability, active " + "FROM accessories WHERE accessories_id = ?"; private static final String SELECT = "SELECT accessories_id, type_Ru, type_En, brand, model_name, " + "description_RU, description_EN, image_path, cost, availability, active FROM accessories "; private static final String SELECT_ACTIVE_ACCESSORIES = SELECT + "WHERE active = 1 LIMIT ? OFFSET ?"; private static final String SELECT_ALL_ACCESSORIES = SELECT + "LIMIT ? OFFSET ?"; private static final String UPDATE_ACCESSORY = "UPDATE accessories SET type_Ru = ?, type_En = ?," + " brand = ?, model_name = ?, description_RU = ?, description_EN = ?, image_path = ?, cost = ?, " + "availability = ?, active = ? WHERE accessories_id = ?"; private static final int UPDATE_ID_INDEX = 11; private static final Map<String, Integer> indices; static { indices = new HashMap<>(); indices.put(BRAND, BRAND_INDEX); indices.put(MODEL_NAME, MODEL_NAME_INDEX); indices.put(DESCRIPTION_RU, DESCRIPTION_RU_INDEX); indices.put(DESCRIPTION_EN, DESCRIPTION_EN_INDEX); indices.put(IMAGE_PATH, IMAGE_PATH_INDEX); indices.put(COST, COST_INDEX); indices.put(ACTIVE, ACTIVE_INDEX); } private AccessoryJdbc() { } public static AccessoryJdbc getInstance() { return INSTANCE; } /** * Saves the accessory * * @param accessory {@link Accessory} the accessory * @throws OrionDatabaseException the OrionDatabaseException exception */ public void addAccessoryToDatabase(Accessory accessory) throws OrionDatabaseException { try (Connection connection = ConnectionPool.INSTANCE.getConnection(); PreparedStatement statement = connection.prepareStatement(INSERT_ACCESSORY)){ fillStatement(statement, accessory); statement.executeUpdate(); logger.log(Level.INFO, () -> "The accessory is saved in the database"); } catch (SQLException e) { throw new OrionDatabaseException(DATABASE_EXCEPTION, e); } } /** * Finds only active accessories or all accessories if the user role is an admin * * @param limit number of products per page * @param offset index of the first product on the page * @param isAdmin is the user role an admin * @return {@link List} of {@link Accessory} the list of found accessories * @throws OrionDatabaseException the OrionDatabaseException exception */ public List<Accessory> searchAccessories(int limit, int offset, boolean isAdmin) throws OrionDatabaseException { List<Accessory> accessories = new ArrayList<>(); String query = SELECT_ACTIVE_ACCESSORIES; if (isAdmin) { query = SELECT_ALL_ACCESSORIES; } try (Connection connection = ConnectionPool.INSTANCE.getConnection(); PreparedStatement statement = connection.prepareStatement(query)) { statement.setInt(1, limit); statement.setInt(2, offset); try (ResultSet resultSet = statement.executeQuery()) { while (resultSet.next()) { Accessory accessory = createAccessory(resultSet); accessories.add(accessory); } } logger.log(Level.INFO, () -> "Accessory search completed successfully"); } catch (SQLException e) { throw new OrionDatabaseException(DATABASE_EXCEPTION, e); } return accessories; } /** * Finds the accessory by id * * @param id the accessory id * @return {@link Optional} of {@link Accessory} the Optional of found accessory * @throws OrionDatabaseException the OrionDatabaseException exception */ public Optional<Accessory> findAccessoryById(int id) throws OrionDatabaseException { Optional<Accessory> optionalAccessory; try (Connection connection = ConnectionPool.INSTANCE.getConnection(); PreparedStatement statement = connection.prepareStatement(FIND_ACCESSORY_BY_ID)) { statement.setInt(ACCESSORIES_ID_INDEX, id); try (ResultSet resultSet = statement.executeQuery()) { if (resultSet.next()) { Accessory accessory = createAccessory(resultSet); optionalAccessory = Optional.of(accessory); } else { throw new OrionDatabaseException(String.format("Accessory with id = %s is not found", id)); } } logger.log(Level.DEBUG, () -> String.format("Accessory with id = %s got from the database", id)); } catch (SQLException e) { throw new OrionDatabaseException(DATABASE_EXCEPTION, e); } return optionalAccessory; } /** * Updates the accessory * * @param accessory {@link Accessory} the accessory * @throws OrionDatabaseException the OrionDatabaseException exception */ public void updateProduct(Accessory accessory) throws OrionDatabaseException { try (Connection connection = ConnectionPool.INSTANCE.getConnection(); PreparedStatement statement = connection.prepareStatement(UPDATE_ACCESSORY)){ fillStatement(statement, accessory); statement.setInt(UPDATE_ID_INDEX, accessory.getAccessoryId()); statement.executeUpdate(); logger.log(Level.INFO, () -> "The accessory is updated in the database"); } catch (SQLException e) { throw new OrionDatabaseException(DATABASE_EXCEPTION, e); } } /** * Creates the accessory * * @param resultSet {@link ResultSet} the accessory * @return {@link Accessory} the accessory * @throws SQLException, OrionDatabaseException the SQLException and OrionDatabaseException exceptions */ private Accessory createAccessory(ResultSet resultSet) throws SQLException, OrionDatabaseException { int accessoryId = resultSet.getInt(ACCESSORIES_ID); String typeRu = resultSet.getString(TYPE_RU); String typeEn = resultSet.getString(TYPE_EN); ProductDetails productDetails = ProductDaoJdbc.createProductDetails(resultSet); int availability = resultSet.getInt(AVAILABILITY); logger.log(Level.DEBUG, () -> "Accessory creation completed successfully"); return new Accessory(accessoryId, typeRu, typeEn, productDetails, availability); } /** * Fills the statement * * @param statement {@link PreparedStatement} the preparedStatement * @param accessory {@link Accessory} the accessory * @throws SQLException the SQLException exception */ private void fillStatement(PreparedStatement statement, Accessory accessory) throws SQLException { statement.setString(TYPE_RU_INDEX - 1, accessory.getTypeRu()); statement.setString(TYPE_EN_INDEX - 1, accessory.getTypeEn()); ProductDetails productDetails = accessory.getProductDetails(); ProductDaoJdbc.setProductDetailsInStatement(statement, productDetails, indices); statement.setInt(AVAILABILITY_INDEX - 1, accessory.getAvailability()); } }
true
f19c49a5a6f2f5c345f97b6d9a3a8f983500299a
Java
taniatritean/kevinProj
/src/main/java/com/kevin/dto/PerformanceDTO.java
UTF-8
1,355
2.703125
3
[]
no_license
package com.kevin.dto; import com.kevin.domain.History; import com.kevin.domain.RunnedGame; import java.util.ArrayList; import java.util.List; public class PerformanceDTO { private long ID; public long getID() { return ID; } public void setID(long ID) { this.ID = ID; } private List<HistoryDTO> resultList =new ArrayList<>(); public List<HistoryDTO> getResultList() { return resultList; } public void setResultList(List<HistoryDTO> resultList) { this.resultList = resultList; } public void printMap(List<History> list, RunnedGame runnedGame){ for(int i=0;i<list.size();i++){ System.out.println(list.get(i).getResult(runnedGame)); } } public boolean deleteResult(int index){ if(resultList.get(index)!=null) { resultList.remove(index); return true; } return false; } public boolean addPerformance(HistoryDTO historyDTO){ if(resultList.contains(historyDTO)==true){ resultList.add(historyDTO); return true; }else{ return false; } } @Override public String toString() { return "PerformanceDTO{" + "ID=" + ID + ", resultList=" + resultList + '}'; } }
true
db25328f8ca1c4e136a36c48f9066b70d8d5e6c1
Java
zhangzihao0777/XuePai
/app/src/main/java/com/wangyi/UIview/activity/DownloadActivity.java
UTF-8
3,084
1.890625
2
[]
no_license
package com.wangyi.UIview.activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.widget.Button; import android.widget.ListView; import android.widget.RelativeLayout; import com.wangyi.UIview.BaseActivity; import com.wangyi.UIview.adapter.DownloadListAdapter; import com.wangyi.reader.R; import org.xutils.view.annotation.ContentView; import org.xutils.view.annotation.Event; import org.xutils.view.annotation.ViewInject; @ContentView(R.layout.download_me) public class DownloadActivity extends BaseActivity { @ViewInject(R.id.control) private RelativeLayout control; @ViewInject(R.id.downloadlist) private ListView downloadList; private RefreshDownLoad refreshDownLoad; private DownloadListAdapter dla; private int editTag = 0; private Handler handler = new Handler(); protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //接收广播 refreshDownLoad = new RefreshDownLoad(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction("refresh"); registerReceiver(refreshDownLoad, intentFilter); dla = new DownloadListAdapter(this); downloadList.setAdapter(dla); run.run(); control.setVisibility(View.GONE); } private Runnable run = new Runnable() { @Override public void run() { dla.notifyDataSetChanged(); handler.postDelayed(this, 1000); } }; @Event(R.id.back) private void onBackClick(View view) { handler.removeCallbacks(run); DownloadActivity.this.finish(); } @Override public void onBackPressed() { super.onBackPressed(); handler.removeCallbacks(run); } @Event(R.id.edit) private void onEditClick(View view) { if (editTag == 0) { ((Button) view).setText("完成"); control.setVisibility(View.VISIBLE); dla.setEditMode(); dla.notifyDataSetChanged(); editTag = 1; } else { ((Button) view).setText("编辑"); control.setVisibility(View.GONE); dla.setEditMode(); dla.clearSelect(); dla.notifyDataSetChanged(); editTag = 0; } } @Event(R.id.allselect) private void onAllSelectClick(View view) { dla.allSelect(); dla.notifyDataSetChanged(); } @Event(R.id.delete) private void onDeleteClick(View view) { dla.delect(); dla.notifyDataSetChanged(); } class RefreshDownLoad extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { downloadList.setAdapter(dla); } } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(refreshDownLoad); } }
true
5007a18d257f2a64551a9873c6fb747af9bb8502
Java
inkyu/TIL_JTAPI
/src/main/java/com/avaya/jtapi/tsapi/csta1/LucentV5QueryDeviceInfoConfEvent.java
UTF-8
1,870
2.3125
2
[]
no_license
package com.avaya.jtapi.tsapi.csta1; import java.io.InputStream; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; public final class LucentV5QueryDeviceInfoConfEvent extends LucentQueryDeviceInfoConfEvent { short associatedClass; String associatedDevice; static final int PDU = 98; public static LucentQueryDeviceInfoConfEvent decode(InputStream in) { LucentV5QueryDeviceInfoConfEvent _this = new LucentV5QueryDeviceInfoConfEvent(); _this.doDecode(in); return _this; } public void decodeMembers(InputStream memberStream) { super.decodeMembers(memberStream); this.associatedClass = LucentExtensionClass.decode(memberStream); this.associatedDevice = DeviceID.decode(memberStream); } public void encodeMembers(OutputStream memberStream) { super.encodeMembers(memberStream); LucentExtensionClass.encode(this.associatedClass, memberStream); DeviceID.encode(this.associatedDevice, memberStream); } public Collection<String> print() { Collection<String> lines = new ArrayList<String>(); lines.add("LucentV5QueryDeviceInfoConfEvent ::="); lines.add("{"); String indent = " "; lines.addAll(LucentExtensionClass.print(this.extensionClass, "extensionClass", indent)); lines.addAll(LucentExtensionClass.print(this.associatedClass, "associatedClass", indent)); lines.addAll(DeviceID.print(this.associatedDevice, "associatedDevice", indent)); lines.add("}"); return lines; } public int getPDU() { return 98; } public short getAssociatedClass() { return this.associatedClass; } public String getAssociatedDevice() { return this.associatedDevice; } public void setAssociatedClass(short associatedClass) { this.associatedClass = associatedClass; } public void setAssociatedDevice(String associatedDevice) { this.associatedDevice = associatedDevice; } }
true
7711231073694202b014bf01bf68d2a47f0c2691
Java
event-manager-com/users-service
/src/main/java/gregad/eventmanager/usersservice/rest/UserController.java
UTF-8
1,060
2.078125
2
[]
no_license
package gregad.eventmanager.usersservice.rest; import gregad.eventmanager.usersservice.dto.UserDto; import gregad.eventmanager.usersservice.services.user_service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import static gregad.eventmanager.usersservice.api.ApiConstants.USERS; /** * @author Greg Adler */ @RestController @RequestMapping(USERS) public class UserController { @Autowired UserService userService; @GetMapping(value = "/{id}") UserDto getUser(@PathVariable int id){ return userService.getUser(id); } @PostMapping UserDto addUser(@RequestParam int telegramId,@RequestParam String name){ return userService.addUser(telegramId,name); } @PatchMapping UserDto updateUser(@RequestBody UserDto userDto){ return userService.updateUser(userDto); } @DeleteMapping(value = "/{id}") UserDto deleteUser(@PathVariable int id){ return userService.deleteUser(id); } }
true
dbe25b8f8aa10ce75266491c67152369f4e950f6
Java
eamonnmag/BioEye
/src/uk/ac/ox/oerc/bioeye/phonegap/CamPreview.java
UTF-8
7,386
2.140625
2
[]
no_license
/* * * Copyright (C) 2010 GSyC/LibreSoft, Universidad Rey Juan Carlos. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see http://www.gnu.org/licenses/. * * Author : Raúl Román López <rroman@gsyc.es> * */ package uk.ac.ox.oerc.bioeye.phonegap; import android.content.Context; import android.graphics.PixelFormat; import android.hardware.Camera; import android.hardware.Camera.PictureCallback; import android.hardware.Camera.PreviewCallback; import android.hardware.Camera.Size; import android.util.AttributeSet; import android.util.Log; import android.view.SurfaceHolder; import android.view.SurfaceView; import java.io.IOException; import java.util.List; public class CamPreview extends SurfaceView implements SurfaceHolder.Callback { public int THRESHOLD = 60; private OnFrameReadyListener onFrameReadyListener = null; private SurfaceHolder mHolder; private Camera mCamera; private int WIDTH, HEIGHT; private PreviewCallback frameReadyListener = new PreviewCallback() { public void onPreviewFrame(byte[] data, Camera camera) { setPreviewCallback(null); if (onFrameReadyListener == null) return; int[] edges = new int[camera.getParameters().getPreviewSize().width * camera.getParameters().getPreviewSize().height]; decodeYUV420SP(edges, data, camera.getParameters().getPreviewSize().width, camera.getParameters().getPreviewSize().height); onFrameReadyListener.onFrame(edges); clearOnFrameReadyListener(); } }; public CamPreview(Context context) { super(context); mHolder = getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } public CamPreview(Context context, AttributeSet attribs) { super(context, attribs); // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed. mHolder = getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); } public void setPreviewCallback(PreviewCallback pc) { mCamera.setPreviewCallback(pc); } public void takePicture(PictureCallback pic) { mCamera.takePicture(null, null, pic); } public void resumePreview() { mCamera.startPreview(); } public void pausePreview() { mCamera.stopPreview(); } public void surfaceCreated(SurfaceHolder holder) { // The Surface has been created, acquire the camera and tell it where // to draw. try { mCamera = Camera.open(); mCamera.setPreviewDisplay(holder); } catch (IOException e) { mCamera.release(); Log.e("CamPreview", e.toString()); } } public void surfaceDestroyed(SurfaceHolder holder) { // Surface will be destroyed when we return, so stop the preview. // Because the CameraDevice object is not a shared resource, it's very // important to release it when the activity is paused. mCamera.stopPreview(); mCamera.release(); mCamera = null; } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // Now that the size is known, set up the camera parameters and begin // the preview. Camera.Parameters parameters = mCamera.getParameters(); if ((WIDTH == 0) || (HEIGHT == 0)) { try { List<Camera.Size> supportedSizes; supportedSizes = parameters.getSupportedPreviewSizes(); //preview form factor Log.e("CamPreview", "wxh = " + Integer.toString(w) + "X" + Integer.toString(h)); float ff = ((float) w) / ((float) h); //holder for the best form factor and size float bff = 0; int bestw = 0; int besth = 0; for (Size element : supportedSizes) { //current form factor Log.e("CamPreview", "Size = " + Integer.toString(element.width) + "X" + Integer.toString(element.height)); float cff = ((float) element.width) / ((float) element.height); if ((ff - cff <= ff - bff) && (element.width <= w) && (element.width >= bestw)) { bff = cff; bestw = element.width; besth = element.height; } } WIDTH = bestw; HEIGHT = besth; } catch (Exception ex) { Log.e("CamPreview", "", ex); } } if ((WIDTH == 0) || (HEIGHT == 0)) { WIDTH = 480; HEIGHT = 320; } parameters.setPreviewSize(WIDTH, HEIGHT); parameters.setPictureFormat(PixelFormat.JPEG); mCamera.setParameters(parameters); try { mCamera.startPreview(); } catch (Exception e) { Log.e("CamPreview", "", e); } } public Size getCameraPreviewSize() { if (mCamera == null) return null; return mCamera.getParameters().getPreviewSize(); } private void decodeYUV420SP(int[] rgb, byte[] yuv420sp, int width, int height) { final int frameSize = width * height; for (int j = 0, yp = 0; j < height; j++) { int uvp = frameSize + (j >> 1) * width, u = 0, v = 0; for (int i = 0; i < width; i++, yp++) { int y = (0xff & ((int) yuv420sp[yp])) - 16; if (y < 0) y = 0; if ((i & 1) == 0) { v = (0xff & yuv420sp[uvp++]) - 128; u = (0xff & yuv420sp[uvp++]) - 128; } int y1192 = 1192 * y; int r = (y1192 + 1634 * v); int g = (y1192 - 833 * v - 400 * u); int b = (y1192 + 2066 * u); if (r < 0) r = 0; else if (r > 262143) r = 262143; if (g < 0) g = 0; else if (g > 262143) g = 262143; if (b < 0) b = 0; else if (b > 262143) b = 262143; rgb[yp] = 0xff000000 | ((r << 6) & 0xff0000) | ((g >> 2) & 0xff00) | ((b >> 10) & 0xff); } } } public void setOnFrameReadyListener(OnFrameReadyListener listener) { this.onFrameReadyListener = listener; setPreviewCallback(frameReadyListener); } public void clearOnFrameReadyListener() { setPreviewCallback(null); onFrameReadyListener = null; } public interface OnFrameReadyListener { public abstract void onFrame(int[] pixels); } }
true
c5410e1c09a10068a33550f616aed09ebefe566f
Java
projetoswga/SISFIE
/src-arq/br/com/arquitetura/util/RelatorioUtil.java
UTF-8
11,499
2.3125
2
[]
no_license
package br.com.arquitetura.util; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; import javax.faces.context.FacesContext; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import net.sf.jasperreports.engine.JRDataSource; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JRExporter; import net.sf.jasperreports.engine.JRExporterParameter; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource; import net.sf.jasperreports.engine.export.JRHtmlExporter; import net.sf.jasperreports.engine.export.JRHtmlExporterParameter; import net.sf.jasperreports.engine.export.JRPdfExporter; import net.sf.jasperreports.engine.export.JRXlsExporter; import net.sf.jasperreports.engine.export.JRXlsExporterParameter; import br.com.sisfie.util.Constantes; /** * @author Igor Galv�o <br/> * Class Util para gerar Relatorios.<br/> * Pode ser exibido no browser * @version 1.0 * @date 23/09/2011 */ public class RelatorioUtil { /** * * @param lista * @param parametros * @param caminho * @param nomePDF * @param formato * - Excel, PDF e HTML * @throws JRException * @throws IOException * @funcionalidade: Gerar relatorio com lista e parametos */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static void gerarRelatorio(Collection lista, Map parametros, String caminho, String nome, String formato) throws JRException, IOException { FacesContext context = FacesContext.getCurrentInstance(); /* Cria o response */ HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse(); /* Coloca o nome do arquivo e o Tipo que o browser deve interpretar */ response.setHeader("Content-Disposition", "attachment; filename=" + nome + "." + formato); /* Cria o Stream com o caminho */ InputStream stream = context.getExternalContext().getResourceAsStream(caminho); /* Cria a lista do relatorio */ JRDataSource colecao = new JRBeanCollectionDataSource(lista == null ? new ArrayList() : lista); JasperPrint jasperPrint = JasperFillManager.fillReport(stream, parametros, colecao); ServletOutputStream outputStream = response.getOutputStream(); JRExporter jrExporter = getExporter(formato, response); jrExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); jrExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outputStream); jrExporter.exportReport(); outputStream.flush(); outputStream.close(); context.renderResponse(); context.responseComplete(); } /** * * @param parametros * @param caminho * @param nome * - Sem extensão. ex: NomePDF * @param formato * - Excel, PDF e HTML * @throws JRException * @throws IOException */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static void gerarRelatorio(Map parametros, String caminho, String nome, String formato) throws JRException, IOException { FacesContext context = FacesContext.getCurrentInstance(); /* Cria o response */ HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse(); /* Coloca o nome do arquivo e o Tipo que o browser deve interpretar */ response.setHeader("Content-Disposition", "attachment; filename=" + nome + "." + formato); /* Cria o Stream com o caminho */ InputStream stream = context.getExternalContext().getResourceAsStream(caminho); /* Quando nao passa a lista da erro */ /* Para resolver vou criar uma lista sem nada */ Collection lista = new ArrayList(); lista.add(new Object()); JRDataSource colecao = new JRBeanCollectionDataSource(lista); JasperPrint jasperPrint = JasperFillManager.fillReport(stream, parametros, colecao); ServletOutputStream outputStream = response.getOutputStream(); JRExporter jrExporter = getExporter(formato, response); jrExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); jrExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outputStream); jrExporter.exportReport(); outputStream.flush(); outputStream.close(); context.renderResponse(); context.responseComplete(); } /** * * @param lista * @param parametros * @param caminho * @param nomePDF * @throws JRException * @throws IOException * @funcionalidade: Gerar relatorio com Lista */ @SuppressWarnings("rawtypes") public static void gerarRelatorio(Collection lista, String caminho, String nome,String formato) throws JRException, IOException { FacesContext context = FacesContext.getCurrentInstance(); /* Cria o response */ HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse(); /* Coloca o nome do arquivo e o Tipo que o browser deve interpretar */ response.setHeader("Content-Disposition", "attachment; filename=" + nome + "." + formato); /* Cria o Stream com o caminho */ InputStream stream = context.getExternalContext().getResourceAsStream(caminho); /* Cria a lista do relatorio */ JRDataSource dataSource = new JRBeanCollectionDataSource(lista == null ? new ArrayList() : lista); JasperPrint jasperPrint = JasperFillManager.fillReport(stream, new HashMap<String, Object>(), dataSource); ServletOutputStream outputStream = response.getOutputStream(); JRExporter jrExporter = getExporter(formato, response); jrExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); jrExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outputStream); jrExporter.exportReport(); outputStream.flush(); outputStream.close(); context.renderResponse(); context.responseComplete(); } /** * * @param lista * @param parametros * @param caminho * @param nomePDF * @throws JRException * @throws IOException * @funcionalidade: Gerar relatorio */ @SuppressWarnings({ "rawtypes", "unchecked" }) public static void gerarRelatorio(String caminho, String nome,String formato) throws JRException, IOException { FacesContext context = FacesContext.getCurrentInstance(); /* Cria o response */ HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse(); /* Coloca o nome do arquivo e o Tipo que o browser deve interpretar */ response.setHeader("Content-Disposition", "attachment; filename=" + nome + "." + formato); /* Cria o Stream com o caminho */ InputStream stream = context.getExternalContext().getResourceAsStream(caminho); /* Quando nao passa a lista da erro */ /* Para resolver vou criar uma lista sem nada */ Collection lista = new ArrayList(); lista.add(new Object()); JRDataSource colecao = new JRBeanCollectionDataSource(lista); JasperPrint jasperPrint = JasperFillManager.fillReport(stream, new HashMap<String, Object>(), colecao); ServletOutputStream outputStream = response.getOutputStream(); JRExporter jrExporter = getExporter(formato, response); jrExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); jrExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outputStream); jrExporter.exportReport(); outputStream.flush(); outputStream.close(); context.renderResponse(); context.responseComplete(); } /** * @param lista * @param caminho * @param nomeXLS * @throws JRException * @throws IOException * @funcionalidade: Gerar relatorio */ @SuppressWarnings("rawtypes") public static void gerarRelatorioExcel(Collection lista, String caminho, String nomeXLS) throws JRException, IOException { FacesContext context = FacesContext.getCurrentInstance(); /* Cria o response */ HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse(); /* Coloca o nome do XLS e o Tipo que o browser deve interpretar */ response.setHeader("Content-Disposition", "attachment; filename=" + nomeXLS); response.setContentType("application/vnd.ms-excel"); /* Cria o Stream com o caminho */ InputStream stream = context.getExternalContext().getResourceAsStream(caminho); /* Cria a lista do relatorio */ JRDataSource dataSource = new JRBeanCollectionDataSource(lista == null ? new ArrayList() : lista); JasperPrint jasperPrint = JasperFillManager.fillReport(stream, new HashMap<String, Object>(), dataSource); ServletOutputStream outputStream = response.getOutputStream(); JRExporter jrExporter = new JRXlsExporter(); jrExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint); jrExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, outputStream); jrExporter.exportReport(); outputStream.flush(); outputStream.close(); context.renderResponse(); context.responseComplete(); } /** * Definir o Tipo do relatorio. HTML, PDF, EXCEL * * @param formato * @return */ private static JRExporter getExporter(String formato, HttpServletResponse response) { JRExporter exporter = null; if (Constantes.HTML.toString().trim().equalsIgnoreCase(formato.toString().trim())) { exporter = new JRHtmlExporter(); complementaHtmlExport(exporter); response.setContentType("text/html; charset=UTF-8"); } if (formato == null || formato.isEmpty() || Constantes.PDF.toString().trim().equalsIgnoreCase(formato.toString().trim())) { exporter = new JRPdfExporter(); response.setContentType("application/pdf"); } if (Constantes.EXCEL.toString().trim().equalsIgnoreCase(formato.toString().trim())) { exporter = new JRXlsExporter(); complementaExcelExport(exporter); response.setContentType("application/vnd.ms-excel"); } return exporter; } private static void complementaExcelExport(JRExporter exporter) { exporter.setParameter(JRXlsExporterParameter.IGNORE_PAGE_MARGINS, Boolean.TRUE); exporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.TRUE); exporter.setParameter(JRXlsExporterParameter.IS_FONT_SIZE_FIX_ENABLED, Boolean.TRUE); exporter.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, Boolean.TRUE); exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_COLUMNS, Boolean.TRUE); exporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE); exporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE); exporter.setParameter(JRXlsExporterParameter.IS_COLLAPSE_ROW_SPAN, Boolean.FALSE); } private static void complementaHtmlExport(JRExporter exporter) { exporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, "imagemServlet?image="); exporter.setParameter(JRHtmlExporterParameter.IGNORE_PAGE_MARGINS, Boolean.TRUE); exporter.setParameter(JRHtmlExporterParameter.IS_WRAP_BREAK_WORD, Boolean.TRUE); exporter.setParameter(JRHtmlExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.TRUE); exporter.setParameter(JRHtmlExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE); exporter.setParameter(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN, Boolean.FALSE); exporter.setParameter(JRHtmlExporterParameter.SIZE_UNIT, JRHtmlExporterParameter.SIZE_UNIT_POINT); } }
true
52b5bc4559cf6ee78bd5ca8b5003fc2dda50c615
Java
SER516-S18/projectfour_teamZ
/src/main/java/test/TestEmostatePacket.java
UTF-8
1,296
2.6875
3
[]
no_license
package test; import org.junit.Test; import teamZ.project4.model.EmostatePacket; import teamZ.project4.model.Emotion; import teamZ.project4.model.Expression; import java.util.HashMap; public class TestEmostatePacket { private static HashMap<Expression, Float> expressions = new HashMap<>(); private static HashMap<Emotion, Float> emotions = new HashMap<>(); static { for (Expression expression : Expression.values()) expressions.put(expression,0.0f); for (Emotion emotion : Emotion.values()) emotions.put(emotion,0.0f); } @Test(expected = IllegalArgumentException.class) public void TestNullExpressionException(){ EmostatePacket emostatePacket = new EmostatePacket(expressions,emotions); emostatePacket.getExpression(null); } @Test(expected = IllegalArgumentException.class) public void TestNullEmotionException(){ EmostatePacket emostatePacket = new EmostatePacket(expressions,emotions); emostatePacket.getEmotion(null); } @Test(expected = IllegalStateException.class) public void TestSetTickException(){ EmostatePacket emostatePacket = new EmostatePacket(expressions,emotions); emostatePacket.setTick(1f); emostatePacket.setTick(1f); } }
true
bdcfed02b4306ce84b853b804a3f94ff202fcf6b
Java
mihirkamat012/SimplePhysicsEngine2D
/SimplePhysics2D/src/SimplePhysics/World/World.java
UTF-8
4,124
2.921875
3
[]
no_license
package SimplePhysics.World; import java.util.ArrayList; import java.util.Iterator; import SimplePhysics.Collision.AABBCollider; import SimplePhysics.Collision.CircleCollider; import SimplePhysics.Collision.Collision; import SimplePhysics.Collision.PlaneCollider; import SimplePhysics.Dynamics.RBType; import SimplePhysics.Dynamics.Rigidbody; import SimplePhysics.Dynamics.Solvers.ImpulseSolver; import SimplePhysics.Dynamics.Solvers.PositionSolver; import SimplePhysics.Dynamics.Solvers.Solver; public class World { float gravity; ArrayList<Rigidbody> Rigidbodies; ArrayList<Solver> Solvers; public World() { Rigidbodies=new ArrayList<Rigidbody>(); Solvers=new ArrayList<Solver>(); } public void addSolvers() { Solvers.add(new PositionSolver((.1f))); Solvers.add(new ImpulseSolver()); } public ArrayList<Rigidbody> getRigidbodies() { return Rigidbodies; } public void AddRigidbodyToWorld(Rigidbody rb) { Rigidbodies.add(rb); } void RemoveRigidbodyFromWorld(Rigidbody rb) { } public void start(float dt) { while(true) { step(dt); try { Thread.sleep((long)(dt*1000)); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void step(float dt) { for(Rigidbody rb: Rigidbodies) { rb.ApplyNetForce(dt); } } public void resolveCollisions(float dt) { //Object a; ArrayList<Collision> cols=new ArrayList<Collision>(); for(Rigidbody rb1:Rigidbodies) { for(Rigidbody rb2:Rigidbodies) { if(rb1.equals(rb2)||rb2.equals(rb1)) break; cols.add(rb1.collider.test(rb2.collider)); } } /**else if(Rigidbodies.get(i).getType()==RBType.AABB) { if(Rigidbodies.get(j).getType()==RBType.AABB) { //System.out.println("aabb aabb"); cols.add(Rigidbodies.get(i).collider.getAsAABBCollider().test((AABBCollider)Rigidbodies.get(j).collider)); } }*/ //else // continue; for(Solver s:Solvers) { s.solve(cols,dt);//solve collisions } cols.clear(); } } /*for(int i=0;i<Rigidbodies.size();i++) { for(int j=i+1 ;j<Rigidbodies.size();j++) { //detect collision //fill collision list //c p aabb // p aabb // aabb if(Rigidbodies.get(i).equals(Rigidbodies.get(j))) break; if(Rigidbodies.get(i).getType()==RBType.CIRCLE) { if(Rigidbodies.get(j).getType()==RBType.CIRCLE) { //System.out.println("c c"); cols.add(Rigidbodies.get(i).collider.test((CircleCollider)Rigidbodies.get(j).collider)); } else if(Rigidbodies.get(j).getType()==RBType.PLANE) { //System.out.println("c p"); cols.add(Rigidbodies.get(i).collider.test((PlaneCollider)Rigidbodies.get(j).collider)); } else if(Rigidbodies.get(j).getType()==RBType.AABB) { //System.out.println("c aabb"); cols.add(Rigidbodies.get(i).collider.test((AABBCollider)Rigidbodies.get(j).collider)); } } else if(Rigidbodies.get(i).getType()==RBType.PLANE) { if(Rigidbodies.get(j).getType()==RBType.AABB) { //System.out.println("p aabb"); cols.add(Rigidbodies.get(i).collider.getAsPlaneCollider().test((AABBCollider)Rigidbodies.get(j).collider)); } else if(Rigidbodies.get(j).getType()==RBType.CIRCLE) { //System.out.println("c c"); cols.add(Rigidbodies.get(i).collider.test((CircleCollider)Rigidbodies.get(j).collider)); } } else if(Rigidbodies.get(i).getType()==RBType.AABB) { if(Rigidbodies.get(j).getType()==RBType.PLANE) { //System.out.println("aabb p"); cols.add(Rigidbodies.get(i).collider.getAsAABBCollider().test((PlaneCollider)Rigidbodies.get(j).collider)); } if(Rigidbodies.get(j).getType()==RBType.AABB) { //System.out.println("aabb aabb"); cols.add(Rigidbodies.get(i).collider.getAsAABBCollider().test((AABBCollider)Rigidbodies.get(j).collider)); } if(Rigidbodies.get(j).getType()==RBType.CIRCLE) { //System.out.println("aabb aabb"); cols.add(Rigidbodies.get(i).collider.getAsAABBCollider().test((CircleCollider)Rigidbodies.get(j).collider)); } }*/ /* * */
true
af55d62fce221be98e1bfa92c8eedd16905083e6
Java
HugoSecteur4/SaladeTomateOignons
/zxing-sample/src/main/java/me/dm7/barcodescanner/zxing/sample/LetsCookActivity.java
UTF-8
3,398
2.265625
2
[ "Apache-2.0" ]
permissive
package me.dm7.barcodescanner.zxing.sample; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import java.util.ArrayList; import java.util.Vector; public class LetsCookActivity extends AppCompatActivity { private Class<?> mClss; private RecyclerView recyclerView; private MyAdapterRecette adapter; Vector<Recette> recettes = new Vector<Recette>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_lets_cook); ArrayList<Etape> etapes = new ArrayList<Etape>(); Etape etape1 = new Etape("Etape 1", "Faire bouillir l’eau dans une casserole. Mettre le riz et le laisser bouillir 2 à 3 minutes.", R.drawable.etape1r); Etape etape2 = new Etape("Etape 2", "Égoutter le riz. ", R.drawable.etape2r); Etape etape3 = new Etape("Etape 3", "Faire chauffer le lait avec le zeste râpé du citron, et les sucres. ", R.drawable.etape3r); Etape etape4 = new Etape("Etape 4", "Verser le riz.", R.drawable.etape4r); Etape etape5 = new Etape("Etape 5", "Faire bouillir, puis laisser cuire à feu doux sans remuer. ", R.drawable.etape5r); Etape etape6 = new Etape("Etape 6", "Le riz est cuit lorsqu’il a absorbé tout le lait. ", R.drawable.etape6r); Etape etape7 = new Etape("Etape 7", "Servir froid ou tiède.", R.drawable.etape7r); etapes.add(etape1); etapes.add(etape2); etapes.add(etape3); etapes.add(etape4); etapes.add(etape5); etapes.add(etape6); etapes.add(etape7); Recette RizAuLait = new Recette(etapes, "Riz au lait", 1, 65, 60, "https://image.afcdn.com/recipe/20171124/75539_w600cxt0cyt0cxb5520cyb3773.jpg"); ArrayList<Etape> recetteEau = new ArrayList<Etape>(); Etape etape1_eau = new Etape("Etape 1", "Prenez le verre avec le numéro deux dans votre main gauche.", R.drawable.etape1); Etape etape2_eau = new Etape("Etape 2", "Prenez la bouteille d'eau dans votre main droite.", R.drawable.etape2); Etape etape3_eau = new Etape("Etape 3", "Remplir le verre numéro deux jusqu'au trait bleu.", R.drawable.etape3); Etape etape4_eau = new Etape("Etape 4", "Répétez l'opération précédente avec le verre numéro trois.", R.drawable.etape4); Etape etape5_eau = new Etape("Etape 5", "Remplir le verre numéro un avec les contenus des verres numéros deux et trois. Ce cocktail est à boire très frais !", R.drawable.etape5); recetteEau.add(etape1_eau); recetteEau.add(etape2_eau); recetteEau.add(etape3_eau); recetteEau.add(etape4_eau); recetteEau.add(etape5_eau); Recette EauDesAlpes = new Recette(recetteEau, "Cocktail Aquatique", 1, 5, 0, "http://img.over-blog-kiwi.com/1/49/01/89/20160621/ob_38cde5_eaurenverse.jpg"); recettes.add(EauDesAlpes); recettes.add(RizAuLait); recyclerView = (RecyclerView) findViewById(R.id.liste); recyclerView.setLayoutManager(new LinearLayoutManager(this)); adapter = new MyAdapterRecette(recettes); recyclerView.setAdapter(adapter); } }
true
33d0104c8381e7d7fa2e284cac0aa95ae294cdbc
Java
Dragomitch/OCR_RemiseCh2
/TestBoisson.java
UTF-8
351
3
3
[]
no_license
public class TestBoisson{ public static void main(String[] args){ try{ Boisson drink1= new Boisson("Cola", 0.75, Boisson.SOFT); drink1.ajouter(44); Boisson drink2= new Boisson("Hoegarden", 0.75, Boisson.BIERE, 24); System.out.println(drink1+"\n"+drink2); }catch(ArgumentInvalideException e){ System.out.println(e.getMessage());} } }
true
0d09d11089cf2af89c1d1b69c9eafa483adb8d03
Java
simphax/CodenameG
/CodenameG/src/edu/chl/codenameg/model/Position.java
UTF-8
1,160
3.453125
3
[]
no_license
package edu.chl.codenameg.model; /** * This class is used to give an object a position or coordinates * @author ??? * */ public class Position { private float x; private float y; public Position(){ this(0,0); } public Position(float x, float y){ this.setX(x); this.setY(y); } public Position(Position ps){ this.setX(ps.getX()); this.setY(ps.getY()); } public float getX() { return x; } public void setX(float x) { this.x = x; } public float getY() { return y; } public void setY(float y) { this.y = y; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Float.floatToIntBits(x); result = prime * result + Float.floatToIntBits(y); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Position other = (Position) obj; if (Float.floatToIntBits(x) != Float.floatToIntBits(other.x)) return false; if (Float.floatToIntBits(y) != Float.floatToIntBits(other.y)) return false; return true; } }
true
ebe61107205557b9de897a0f140fde7dcfa714fc
Java
aikolesnikov/jv-blinov
/basics/src/introduction/Intro_1_4.java
UTF-8
805
3.34375
3
[]
no_license
package introduction; import java.io.Console; import java.util.Arrays; import java.util.Scanner; public class Intro_1_4 { // 1. 4. Ввести пароль из командной строки и сравнить его со строкой-образцом. public static void main(String[] args) throws Exception { try { Scanner sc = new Scanner(System.in); Console console = System.console(); System.out.println("String:"); String s = sc.nextLine(); char[] pass = console.readPassword("Password:"); if (Arrays.equals(s.toCharArray(), pass)) System.out.println("yes"); Arrays.fill(pass, ' '); } catch (Exception e) { e.printStackTrace(); } } }
true
6367e3ff0a09a356c58567ba7f5d4121e30ac3d1
Java
JustTeRoR/Auto-Kit-backend
/src/main/java/com/justterror/auto_kit/part_provider/boundary/PartProviderService.java
UTF-8
1,273
2.265625
2
[]
no_license
package com.justterror.auto_kit.part_provider.boundary; import com.justterror.auto_kit.part_provider.entity.PartProvider; import javax.ejb.Stateless; import javax.inject.Inject; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.TypedQuery; import java.util.List; import java.util.logging.Logger; @Stateless public class PartProviderService { @Inject Logger logger; @PersistenceContext(name = "Auto-Kit") private EntityManager entityManager; public PartProvider getById(Long id) { String rawQuery = String.format("FROM PartProvider WHERE id = %d", id); TypedQuery<PartProvider> query = entityManager.createQuery(rawQuery, PartProvider.class); return query.getSingleResult(); } public List<PartProvider> getByName(String name) { String rawQuery = String.format("FROM PartProvider WHERE name = '%s'", name); TypedQuery<PartProvider> query = entityManager.createQuery(rawQuery, PartProvider.class); return query.getResultList(); } public List<PartProvider> getAll() { TypedQuery<PartProvider> query = entityManager.createQuery("FROM PartProvider p", PartProvider.class); return query.getResultList(); } }
true
96a1a428ad7c4e5070a9991d9c2dd6371306d20b
Java
moeandre/housecare
/HouseCareService/src/main/java/br/com/wamais/houseCare/report/service/impl/FinanceiroReportServiceImpl.java
UTF-8
760
1.875
2
[]
no_license
package br.com.wamais.houseCare.report.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import br.com.wamais.houseCare.report.domain.DashFinanceiro; import br.com.wamais.houseCare.report.service.IFinanceiroReportService; import br.com.wamais.houseCare.repository.report.IFinanceiroReport; @Service @Transactional(readOnly = true) public class FinanceiroReportServiceImpl implements IFinanceiroReportService { @Autowired IFinanceiroReport report; @Override public DashFinanceiro obterPorIdEmpresa(final Integer idEmpresa, final Integer mesano) { return this.report.obterPorIdEmpresa(idEmpresa, mesano); } }
true
288372150f8522985715068e36047ce6ae543f32
Java
tyokyo/SeleniumWeb
/src/cn/testcase/AccountCase.java
UTF-8
2,919
2.078125
2
[]
no_license
package cn.testcase; import org.openqa.selenium.By; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Parameters; import org.testng.annotations.Test; import cn.page.AccountPage; import util.Property; import model.VP; import model.WaitCondition; /** * @ClassName: AccountCase * @Description: https://live.sioeye.cn/account * @author qiang.zhang@ck-telecom.com * @date 2017年10月18日 下午3:25:26 * */ public class AccountCase extends VP{ By by = By.xpath("//span[text()=\"用户名或密码错误\"]"); @Parameters({"browser","username","password"}) @BeforeMethod public void beforeTest(String browser,String username,String password){ initialize(browser,username,password); startSioeye(); } /** * @Title: testLogonSuccessBySioeyeId * @Date:2017年9月13日 * @author qiang.zhang@ck-telecom.com * @Description: 采用 sioeye id 登录Web */ @Test public void testLoginSuccessBySioeyeId(){ String username = Property.getValueByKey(accountPath, "sioeye_id"); String password = Property.getValueByKey(accountPath, "sioeye_password"); initialize(getBean().getBrowser(),username,password); startSioeye(); AccountPage.loginAccount(); } @Test public void testLoginErrorSioeyeId(){ String username = Property.getValueByKey(accountPath, "sioeye_id"); String password = Property.getValueByKey(accountPath, "sioeye_password"); initialize(getBean().getBrowser(),username+"a",password); startSioeye(); AccountPage.loginAccount(); WaitCondition.waitPresenceOfElementLocated(by, 20); } @Test public void testLoginErrorPassword(){ String username = Property.getValueByKey(accountPath, "sioeye_id"); String password = Property.getValueByKey(accountPath, "sioeye_password"); initialize(getBean().getBrowser(),username,password+"a"); startSioeye(); AccountPage.loginAccount(); WaitCondition.waitPresenceOfElementLocated(by, 20); } @Test public void testLoginEmail(){ String username = Property.getValueByKey(accountPath, "email"); String password = Property.getValueByKey(accountPath, "email_password"); initialize(getBean().getBrowser(),username,password); startSioeye(); AccountPage.loginAccount(); } @Test public void testLoginPhone(){ String username = Property.getValueByKey(accountPath, "phone_number"); String password = Property.getValueByKey(accountPath, "phone_password"); initialize(getBean().getBrowser(),username,password); startSioeye(); AccountPage.loginAccount(); new WebDriverWait(getDriver(), 20).until(ExpectedConditions.not(ExpectedConditions.presenceOfAllElementsLocatedBy(By.id("login-btn")))); } @AfterTest public void afterTest(){ quiteSelenium(); } }
true
f4c816707a7b7bb8946814648e6ac88eab482ba8
Java
GRIIMLY/projectControlHoras
/ControlAccesos/src/main/java/co/com/samtel/ControlAccesos/repository/ICodigoUsuario.java
UTF-8
1,031
1.921875
2
[]
no_license
package co.com.samtel.ControlAccesos.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.transaction.annotation.Transactional; import co.com.samtel.ControlAccesos.entities.CodigoUsuario; public interface ICodigoUsuario extends JpaRepository<CodigoUsuario, Integer> { @Query (value="SELECT * FROM tblcodigo_usuarios WHERE codigo = :codigo", nativeQuery=true) @Transactional CodigoUsuario findByCode(@Param("codigo") Integer codigo); @Modifying @Query (value="INSERT INTO controlacceso.tblcodigo_usuarios (codigo, cedula) VALUES(:cod, 999999999)", nativeQuery=true) @Transactional void insertCodigo(@Param("cod") Integer codigo); @Query ("FROM CodigoUsuario c inner join fetch c.tblusuario WHERE c.codigo = :codigo") @Transactional CodigoUsuario findByCod(@Param("codigo") Integer codigo); }
true
b7ba6cd66a91ff8c8c65392060657f17476d284d
Java
juvation/vectorsurgeon
/src/com/prophetvs/editor/PatchValueTransform.java
UTF-8
1,136
2.765625
3
[]
no_license
// PatchValueTransform.java // sets the value to the value of the given parameter name in the *current* patch // so if you wanted WaveA to be random, and WaveB to be what you just set WaveA to // you do it like this // SUPER ghetto at the moment as the relevant information isn't available // so you have to copy the name from the parameter popup (eyeroll) // PACKAGE package com.prophetvs.editor; // IMPORTS import java.util.List; // CLASS public class PatchValueTransform implements Transform { public String[] getTransformParameterNames () { String[] names = new String [1]; names [0] = "Parameter Name"; return names; } public int transformParameter (Patch inPatch, String inParameterName, List<String> inTransformParameters, int inPatchNumber, int inParameterSize) throws VSException { String parameterName = inTransformParameters.get (0); if (parameterName == null || parameterName.length () == 0) { throw new VSException ("no parameter name for PatchValueTransform"); } // this throws if we get the parameter name wrong return inPatch.getParameterValue (parameterName); } }
true
c8e5f186a557cb7ef2f2894f2bea2d7ec4721afe
Java
starmastar1126/Taxi_Android_Swift
/android/PassengerApp/app/src/main/java/com/general/files/AddDrawer.java
UTF-8
18,610
1.546875
2
[]
no_license
package com.general.files; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.view.Gravity; import android.view.View; import android.widget.AdapterView; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import com.adapter.files.DrawerAdapter; import com.fastcabtaxi.passenger.CardPaymentActivity; import com.fastcabtaxi.passenger.ContactUsActivity; import com.fastcabtaxi.passenger.EmergencyContactActivity; import com.fastcabtaxi.passenger.HelpActivity; import com.fastcabtaxi.passenger.HistoryActivity; import com.fastcabtaxi.passenger.InviteFriendsActivity; import com.fastcabtaxi.passenger.MainActivity; import com.fastcabtaxi.passenger.MyBookingsActivity; import com.fastcabtaxi.passenger.MyProfileActivity; import com.fastcabtaxi.passenger.MyWalletActivity; import com.fastcabtaxi.passenger.R; import com.fastcabtaxi.passenger.StaticPageActivity; import com.fastcabtaxi.passenger.SupportActivity; import com.fastcabtaxi.passenger.VerifyInfoActivity; import com.utils.CommonUtilities; import com.utils.Utils; import com.view.GenerateAlertBox; import com.view.MTextView; import com.view.SelectableRoundedImageView; import org.json.JSONObject; import java.util.ArrayList; public class AddDrawer implements AdapterView.OnItemClickListener { public String userProfileJson; public MTextView walletbalncetxt; Context mContext; View view; DrawerLayout mDrawerLayout; ListView menuListView; DrawerAdapter drawerAdapter; ArrayList<String[]> list_menu_items; GeneralFunctions generalFunc; DrawerClickListener drawerClickListener; boolean isMenuState = true; boolean isDriverAssigned = false; LinearLayout logoutarea; ImageView logoutimage; MTextView logoutTxt; ImageView imgSetting; LinearLayout left_linear; MainActivity mainActivity; public JSONObject obj_userProfile; public AddDrawer(Context mContext, String userProfileJson) { this.mContext = mContext; this.userProfileJson = userProfileJson; view = ((Activity) mContext).findViewById(android.R.id.content); mDrawerLayout = (DrawerLayout) view.findViewById(R.id.drawer_layout); menuListView = (ListView) view.findViewById(R.id.menuListView); logoutarea = (LinearLayout) view.findViewById(R.id.logoutarea); logoutimage = (ImageView) view.findViewById(R.id.logoutimage); logoutTxt = (MTextView) view.findViewById(R.id.logoutTxt); imgSetting = (ImageView) view.findViewById(R.id.imgSetting); left_linear = (LinearLayout) view.findViewById(R.id.left_linear); imgSetting.setOnClickListener(new setOnClickLst()); logoutarea.setOnClickListener(new setOnClickLst()); generalFunc = new GeneralFunctions(mContext); logoutimage.setImageDrawable(mContext.getResources().getDrawable(R.mipmap.ic_menu_logout)); logoutTxt.setText(generalFunc.retrieveLangLBl("", "LBL_SIGNOUT_TXT")); walletbalncetxt = (MTextView) view.findViewById(R.id.walletbalncetxt); android.view.Display display = ((android.view.WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); left_linear.getLayoutParams().width = display.getWidth() * 75 / 100; left_linear.requestLayout(); if (mContext instanceof MainActivity) { mainActivity = (MainActivity) mContext; } obj_userProfile = generalFunc.getJsonObject(userProfileJson); buildDrawer(); setUserInfo(); } public void setwalletText(String msg) { walletbalncetxt = (MTextView) view.findViewById(R.id.walletbalncetxt); walletbalncetxt.setText(msg); } public void setMenuImgClick(View view, boolean isDriverAssigned) { // isMenuState = true; if (isDriverAssigned) { (view.findViewById(R.id.backImgView)).setOnClickListener(new setOnClickLst()); } else { (view.findViewById(R.id.menuImgView)).setOnClickListener(new setOnClickLst()); } } public void changeUserProfileJson(String userProfileJson) { this.userProfileJson = userProfileJson; setUserInfo(); } public void configDrawer(boolean isHide) { (view.findViewById(R.id.left_linear)).setVisibility(View.GONE); DrawerLayout.LayoutParams params = (DrawerLayout.LayoutParams) (view.findViewById(R.id.left_linear)).getLayoutParams(); params.gravity = isHide == true ? Gravity.NO_GRAVITY : GravityCompat.START; (view.findViewById(R.id.left_linear)).setLayoutParams(params); } public void setMenuState(boolean isMenuState) { this.isMenuState = isMenuState; if (this.isMenuState == false) { ((ImageView) view.findViewById(R.id.menuImgView)).setImageResource(R.mipmap.ic_back_arrow); configDrawer(true); } else { ((ImageView) view.findViewById(R.id.menuImgView)).setImageResource(R.mipmap.ic_drawer_menu); configDrawer(false); } } public void setIsDriverAssigned(boolean isDriverAssigned) { Utils.printLog("driver", "setIsDriverAssigned::" + isDriverAssigned); this.isDriverAssigned = isDriverAssigned; } public void buildDrawer() { list_menu_items = new ArrayList(); drawerAdapter = new DrawerAdapter(list_menu_items, mContext); menuListView.setAdapter(drawerAdapter); menuListView.setOnItemClickListener(this); list_menu_items.add(new String[]{"" + R.mipmap.ic_menu_profile, generalFunc.retrieveLangLBl("", "LBL_MY_PROFILE_HEADER_TXT"), "" + Utils.MENU_PROFILE}); // list_menu_items.add(new String[]{"" + R.mipmap.ic_menu_profile, generalFunc.retrieveLangLBl("Add vehicles", "LBL_ADD_VEHICLE"), "" + Utils.MENU_VEHICLE}); list_menu_items.add(new String[]{"" + R.mipmap.ic_menu_yourtrip, generalFunc.retrieveLangLBl("", "LBL_YOUR_TRIPS"), "" + Utils.MENU_YOUR_TRIPS}); if (!generalFunc.getJsonValueStr("APP_PAYMENT_MODE", obj_userProfile).equalsIgnoreCase("Cash")) { list_menu_items.add(new String[]{"" + R.mipmap.ic_menu_card, generalFunc.retrieveLangLBl("Payment", "LBL_PAYMENT"), "" + Utils.MENU_PAYMENT}); } if (!generalFunc.getJsonValueStr(CommonUtilities.WALLET_ENABLE, obj_userProfile).equals("") && generalFunc.getJsonValueStr(CommonUtilities.WALLET_ENABLE, obj_userProfile).equalsIgnoreCase("Yes")) { list_menu_items.add(new String[]{"" + R.mipmap.ic_menu_wallet, generalFunc.retrieveLangLBl("", "LBL_LEFT_MENU_WALLET"), "" + Utils.MENU_WALLET}); } if (generalFunc.getJsonValueStr("APP_TYPE", obj_userProfile).equals(Utils.CabGeneralType_UberX)) { list_menu_items.add(new String[]{"" + R.mipmap.ic_menu_trip, generalFunc.retrieveLangLBl("On Going trip", "LBL_LEFT_MENU_ONGOING_TRIPS"), "" + Utils.MENU_ONGOING_TRIPS}); } if (generalFunc.getJsonValueStr("APP_TYPE", obj_userProfile).equals(Utils.CabGeneralTypeRide_Delivery_UberX)) { list_menu_items.add(new String[]{"" + R.mipmap.ic_menu_trip, generalFunc.retrieveLangLBl("On Going trip", "LBL_LEFT_MENU_ONGOING_TRIPS"), "" + Utils.MENU_ONGOING_TRIPS}); } if (!generalFunc.getJsonValueStr("eEmailVerified", obj_userProfile).equalsIgnoreCase("YES") || !generalFunc.getJsonValueStr("ePhoneVerified", obj_userProfile).equalsIgnoreCase("YES")) { list_menu_items.add(new String[]{"" + R.mipmap.ic_menu_privacy, generalFunc.retrieveLangLBl("", "LBL_ACCOUNT_VERIFY_TXT"), "" + Utils.MENU_ACCOUNT_VERIFY}); } //list_menu_items.add(new String[]{"" + R.mipmap.ic_menu_history, generalFunc.retrieveLangLBl("", "LBL_RIDE_HISTORY"), "" + Utils.MENU_RIDE_HISTORY}); // if (generalFunc.getJsonValue("RIIDE_LATER", userProfileJson).equalsIgnoreCase("YES")) { // list_menu_items.add(new String[]{"" + R.mipmap.ic_menu_bookings, generalFunc.retrieveLangLBl("My Bookings", "LBL_MY_BOOKINGS"), "" + Utils.MENU_BOOKINGS}); // } list_menu_items.add(new String[]{"" + R.mipmap.ic_menu_emergency, generalFunc.retrieveLangLBl("Emergency Contact", "LBL_EMERGENCY_CONTACT"), "" + Utils.MENU_EMERGENCY_CONTACT}); if (!generalFunc.getJsonValueStr(CommonUtilities.REFERRAL_SCHEME_ENABLE, obj_userProfile).equals("") && generalFunc.getJsonValueStr(CommonUtilities.REFERRAL_SCHEME_ENABLE, obj_userProfile).equalsIgnoreCase("Yes")) { list_menu_items.add(new String[]{"" + R.mipmap.ic_menu_invite, generalFunc.retrieveLangLBl("Invite Friends", "LBL_INVITE_FRIEND_TXT"), "" + Utils.MENU_INVITE_FRIEND}); } list_menu_items.add(new String[]{"" + R.mipmap.ic_menu_support, generalFunc.retrieveLangLBl("Support", "LBL_SUPPORT_HEADER_TXT"), "" + Utils.MENU_SUPPORT}); // list_menu_items.add(new String[]{"" + R.mipmap.ic_menu_about_us, generalFunc.retrieveLangLBl("", "LBL_ABOUT_US_TXT"), "" + Utils.MENU_ABOUT_US}); // list_menu_items.add(new String[]{"" + R.mipmap.ic_menu_privacy, generalFunc.retrieveLangLBl("", "LBL_PRIVACY_POLICY_TEXT"), "" + Utils.MENU_POLICY}); // list_menu_items.add(new String[]{"" + R.mipmap.ic_menu_contact_us, generalFunc.retrieveLangLBl("", "LBL_CONTACT_US_TXT"), "" + Utils.MENU_CONTACT_US}); // list_menu_items.add(new String[]{"" + R.mipmap.ic_menu_help, generalFunc.retrieveLangLBl("", "LBL_HELP_TXT"), "" + Utils.MENU_HELP}); // list_menu_items.add(new String[]{"" + R.mipmap.ic_menu_logout, generalFunc.retrieveLangLBl("", "LBL_SIGNOUT_TXT"), "" + Utils.MENU_SIGN_OUT}); drawerAdapter.notifyDataSetChanged(); } public void setUserInfo() { ((MTextView) view.findViewById(R.id.userNameTxt)).setText(generalFunc.getJsonValueStr("vName", obj_userProfile) + " " + generalFunc.getJsonValueStr("vLastName", obj_userProfile)); ((MTextView) view.findViewById(R.id.walletbalncetxt)).setText(generalFunc.retrieveLangLBl("", "LBL_WALLET_BALANCE") + ": " + generalFunc.convertNumberWithRTL(generalFunc.getJsonValueStr("user_available_balance", obj_userProfile))); generalFunc.checkProfileImage((SelectableRoundedImageView) view.findViewById(R.id.userImgView), userProfileJson, "vImgName"); } public void openMenuProfile() { Bundle bn = new Bundle(); Utils.printLog("isDriverAssigned", "isDriverAssigned:" + isDriverAssigned); // bn.putString("UserProfileJson", userProfileJson); bn.putString("isDriverAssigned", "" + isDriverAssigned); new StartActProcess(mContext).startActForResult(MyProfileActivity.class, bn, Utils.MY_PROFILE_REQ_CODE); } @Override public void onItemClick(AdapterView<?> parent, final View view, int position, long id) { int itemId = generalFunc.parseIntegerValue(0, list_menu_items.get(position)[2]); Bundle bn = new Bundle(); switch (itemId) { case Utils.MENU_PROFILE: openMenuProfile(); break; case Utils.MENU_VEHICLE: break; case Utils.MENU_RIDE_HISTORY: new StartActProcess(mContext).startActWithData(HistoryActivity.class, bn); break; case Utils.MENU_BOOKINGS: new StartActProcess(mContext).startActWithData(MyBookingsActivity.class, bn); break; case Utils.MENU_ABOUT_US: new StartActProcess(mContext).startAct(StaticPageActivity.class); break; case Utils.MENU_POLICY: (new StartActProcess(mContext)).openURL(CommonUtilities.SERVER_URL + "privacy-policy"); break; case Utils.MENU_PAYMENT: bn.putBoolean("fromcabselection", false); new StartActProcess(mContext).startActForResult(CardPaymentActivity.class, bn, Utils.CARD_PAYMENT_REQ_CODE); break; case Utils.MENU_CONTACT_US: new StartActProcess(mContext).startAct(ContactUsActivity.class); break; case Utils.MENU_HELP: new StartActProcess(mContext).startAct(HelpActivity.class); break; case Utils.MENU_EMERGENCY_CONTACT: new StartActProcess(mContext).startAct(EmergencyContactActivity.class); break; case Utils.MENU_SUPPORT: new StartActProcess(mContext).startAct(SupportActivity.class); break; case Utils.MENU_WALLET: new StartActProcess(mContext).startActWithData(MyWalletActivity.class, bn); break; case Utils.MENU_ACCOUNT_VERIFY: if (!generalFunc.getJsonValue("eEmailVerified", userProfileJson).equalsIgnoreCase("YES") || !generalFunc.getJsonValue("ePhoneVerified", userProfileJson).equalsIgnoreCase("YES")) { Bundle bn1 = new Bundle(); if (!generalFunc.getJsonValue("eEmailVerified", userProfileJson).equalsIgnoreCase("YES") && !generalFunc.getJsonValue("ePhoneVerified", userProfileJson).equalsIgnoreCase("YES")) { bn1.putString("msg", "DO_EMAIL_PHONE_VERIFY"); } else if (!generalFunc.getJsonValue("eEmailVerified", userProfileJson).equalsIgnoreCase("YES")) { bn1.putString("msg", "DO_EMAIL_VERIFY"); } else if (!generalFunc.getJsonValue("ePhoneVerified", userProfileJson).equalsIgnoreCase("YES")) { bn1.putString("msg", "DO_PHONE_VERIFY"); } // bn1.putString("UserProfileJson", userProfileJson); new StartActProcess(mContext).startActForResult(VerifyInfoActivity.class, bn1, Utils.VERIFY_INFO_REQ_CODE); } break; case Utils.MENU_YOUR_TRIPS: bn.putBoolean("isrestart", false); new StartActProcess(mContext).startActWithData(HistoryActivity.class, bn); break; case Utils.MENU_INVITE_FRIEND: new StartActProcess(mContext).startActWithData(InviteFriendsActivity.class, bn); break; case Utils.MENU_SIGN_OUT: final GenerateAlertBox generateAlert = new GenerateAlertBox(mContext); generateAlert.setCancelable(false); generateAlert.setBtnClickList(new GenerateAlertBox.HandleAlertBtnClick() { @Override public void handleBtnClick(int btn_id) { if (btn_id == 0) { generateAlert.closeAlertBox(); } else { generalFunc.logoutFromDevice(mContext, "AddDrawer", generalFunc); } } }); generateAlert.setContentMessage(generalFunc.retrieveLangLBl("Logout", "LBL_LOGOUT"), generalFunc.retrieveLangLBl("Are you sure you want to logout?", "LBL_WANT_LOGOUT_APP_TXT")); generateAlert.setPositiveBtn(generalFunc.retrieveLangLBl("", "LBL_YES")); generateAlert.setNegativeBtn(generalFunc.retrieveLangLBl("", "LBL_NO")); generateAlert.showAlertBox(); break; } closeDrawer(); } public void closeDrawer() { (view.findViewById(R.id.left_linear)).setVisibility(View.GONE); mDrawerLayout.closeDrawer(GravityCompat.START); } public boolean checkDrawerState(boolean isOpenDrawer) { Utils.printLog("Api", "Gravity" + mDrawerLayout.isDrawerOpen(GravityCompat.START) + "isOpenDrawer ::" + isOpenDrawer); if (mDrawerLayout.isDrawerOpen(GravityCompat.START) == true) { closeDrawer(); return true; } else if (isOpenDrawer == true) { openDrawer(); } return false; } public void openDrawer() { (view.findViewById(R.id.left_linear)).setVisibility(View.VISIBLE); mDrawerLayout.openDrawer(GravityCompat.START); } private void setMenuAction() { Utils.printLog("Api", "isMenuState" + isMenuState); if (isMenuState) { openDrawer(); } else { setMenuState(true); if (drawerClickListener != null) { drawerClickListener.onClick(); } } } public void setItemClickList(DrawerClickListener itemClickList) { this.drawerClickListener = itemClickList; } public interface DrawerClickListener { void onClick(); } public class setOnClickLst implements View.OnClickListener { @Override public void onClick(View v) { switch (v.getId()) { case R.id.menuImgView: setMenuAction(); break; case R.id.backImgView: setMenuAction(); break; case R.id.imgSetting: menuListView.performItemClick(view, 0, Utils.MENU_PROFILE); break; case R.id.logoutarea: final GenerateAlertBox generateAlert = new GenerateAlertBox(mContext); generateAlert.setCancelable(false); generateAlert.setBtnClickList(new GenerateAlertBox.HandleAlertBtnClick() { @Override public void handleBtnClick(int btn_id) { if (btn_id == 0) { generateAlert.closeAlertBox(); } else { generalFunc.logoutFromDevice(mContext, "AddDrawer", generalFunc); } } }); generateAlert.setContentMessage(generalFunc.retrieveLangLBl("Logout", "LBL_LOGOUT"), generalFunc.retrieveLangLBl("Are you sure you want to logout?", "LBL_WANT_LOGOUT_APP_TXT")); generateAlert.setPositiveBtn(generalFunc.retrieveLangLBl("", "LBL_YES")); generateAlert.setNegativeBtn(generalFunc.retrieveLangLBl("", "LBL_NO")); generateAlert.showAlertBox(); break; } } } }
true
f4585d6e84b366ae5672ef62e33f12e38dd49d0d
Java
wangjulien/proxi_banque_spring_jw
/src/main/java/org/formation/proxibanque/entity/Conseiller.java
UTF-8
1,818
2.46875
2
[]
no_license
package org.formation.proxibanque.entity; import java.util.ArrayList; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; /** * Entity Conseiller herite de Employee (strategy TABLE PER CLASS) * Il possede une liste de Client * * @author JW * */ @XmlRootElement @Entity @NamedQueries({ @NamedQuery(name = "findAllConseiller", query = "select m from Conseiller m"), @NamedQuery(name = "findConseillersByGerandId", query = "select m from Conseiller m join m.gerant c where c.id = :gerid") }) @Table(name = "conseiller") public class Conseiller extends Employee { public static final String ROLE_CONSEILLER = "ROLE_CONSEILLER"; @ManyToOne private Gerant gerant; @OneToMany(mappedBy = "conseiller", cascade = { CascadeType.PERSIST, CascadeType.MERGE }) private List<Client> clientsList = new ArrayList<>(); public Conseiller() { super(); super.addRole(new UserRole(ROLE_CONSEILLER)); } public Conseiller(String nom, String prenom, String refEmployee, Adresse adresse) { super(nom, prenom, refEmployee, adresse); super.addRole(new UserRole(ROLE_CONSEILLER)); } public void addClient(Client c) { c.setConseiller(this); clientsList.add(c); } public void deleteClient(Client c) { c.setConseiller(null); clientsList.remove(c); } public Gerant getGerant() { return gerant; } public void setGerant(Gerant gerant) { this.gerant = gerant; } public List<Client> getClientsList() { return clientsList; } public void setClientsList(List<Client> clientsList) { this.clientsList = clientsList; } }
true
ce3798b1ab658e5745903da16bf98abc86b76895
Java
LuanLouis/java-meditations
/concurrent-meditations/src/main/java/com/luanlouis/meditations/concurrent/v3/package-info.java
UTF-8
393
1.875
2
[]
no_license
/** * * 该实例展示了 在方法上添加synchronized 标记,表明在调用这个方法时,要先获得当前方法所属对象上的锁,由于这个对象上的锁只要调用这个方法的时候,都会显式要求获取 * 所以这个比较有一般性. 这个控制的力度比较细, * * * * Created by LuanLouis on 16/4/5. */ package com.luanlouis.meditations.concurrent.v3;
true
ab6ac7962ae6ab141c6be98dfd2bd9b87e150ef0
Java
tensorics/tensorics-core
/src/java/org/tensorics/core/tensorbacked/dimtyped/Tensorbacked1d.java
UTF-8
281
1.96875
2
[ "Apache-2.0" ]
permissive
package org.tensorics.core.tensorbacked.dimtyped; public interface Tensorbacked1d<C1, V> extends DimtypedTensorbacked<V> { default V get(C1 c1) { return tensor().get(c1); } default boolean contains(C1 c1) { return tensor().contains(c1); } }
true
73a53903f69eceb7a0b9c4f4d0bac4216dcbbe90
Java
FastRunningSnail/JSD1801
/20180414/src/test7.java
UTF-8
167
2.125
2
[]
no_license
public class test7 { public String transfer(String cash){ long money = Long.valueOf(cash); String rmb = ""; return rmb; } }
true
e83a16ee3167c24711e20258b4f12e3680145e85
Java
P79N6A/icse_20_user_study
/methods/Method_21154.java
UTF-8
189
1.6875
2
[]
no_license
private boolean handleProjectUpdateCommentsUriRequest(final @NonNull Request request,final @NonNull WebView webView){ this.viewModel.inputs.goToCommentsRequest(request); return true; }
true
a18dfcbbfb98fdb348c45c102a4bc5b1a59f5551
Java
pf5512/fish-platform
/src/main/java/com/ippteam/fish/controller/AdviceController.java
UTF-8
4,020
2.21875
2
[]
no_license
package com.ippteam.fish.controller; import com.ippteam.fish.util.api.pojo.*; import com.ippteam.fish.util.api.exception.*; import org.apache.log4j.Logger; import org.springframework.http.HttpStatus; import org.springframework.http.converter.HttpMessageNotReadableException; import org.springframework.web.HttpRequestMethodNotSupportedException; import org.springframework.web.bind.MissingServletRequestParameterException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException; import static com.ippteam.fish.util.Final.*; /** * Created by pactera on 16/10/26. */ @ControllerAdvice public class AdviceController { private static Logger logger = Logger.getLogger(AdviceController.class); /** * 业务错误 * * @param e * @return */ @ExceptionHandler(BusinessException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public Result businessException(BusinessException e) { return new Result(e.getCode(), e.getReason(), null); } /** * 签名错误 * * @param e * @return */ @ExceptionHandler(CertificationException.class) @ResponseStatus(HttpStatus.UNAUTHORIZED) @ResponseBody public Result certificationException(CertificationException e) { return new Result(401, e.getMessage(), null); } /** * 参数无效 * * @param e * @return */ @ExceptionHandler(ParameterException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public Result bodyException(ParameterException e) { return new Result(400, e.getMessage(), null); } /** * url请求参数错误 * * @param e * @return */ @ExceptionHandler(MissingServletRequestParameterException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public Result paramerException(MissingServletRequestParameterException e) { return new Result(400, EXCEPTION_REQUEST_URL_PARAMER_ERROE, null); } @ExceptionHandler(MethodArgumentTypeMismatchException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public Result paramerException(MethodArgumentTypeMismatchException e) { return new Result(400, EXCEPTION_REQUEST_URL_PARAMER_ERROE, null); } /** * body参数错误 * * @param e * @return */ @ExceptionHandler(HttpMessageNotReadableException.class) @ResponseStatus(HttpStatus.BAD_REQUEST) @ResponseBody public Result httpMessageNotReadableException(HttpMessageNotReadableException e) { return new Result(400, EXCEPTION_REQUEST_BODY_PARAMER_ERROE, null); } /** * 请求mothod不支持 * * @param e * @return */ @ExceptionHandler(HttpRequestMethodNotSupportedException.class) @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED) @ResponseBody public Result notSupportedHandler(Exception e) { return new Result(405, EXCEPTION_REQUEST_METHOD_NOTSUPPORTED, null); } @ExceptionHandler @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) @ResponseBody public Result exceptionHandler(Exception e) { StringBuffer sb = new StringBuffer(); sb.append("==================================================\n"); sb.append(e.getClass().getName() + "\n"); sb.append(e.getMessage() + "\n"); for (StackTraceElement item : e.getStackTrace()) { String className = item.getClassName(); int lineNumber = item.getLineNumber(); sb.append("at\t" + className + "(" + lineNumber + ")" + "\n"); } logger.error(sb.toString()); return new Result(500, EXCEPTION_UNKNOWN_EXCEPTION, null); } }
true
95837ac35de0b3888c6de7b53e52c79d82c73656
Java
madhujeetTomar/DataLogger
/app/src/main/java/com/embitel/datalogger/ui/adapter/DeviceLeAdapter.java
UTF-8
4,123
2.015625
2
[]
no_license
package com.embitel.datalogger.ui.adapter; import android.content.Context; 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.core.content.ContextCompat; import androidx.recyclerview.widget.RecyclerView; import com.embitel.datalogger.R; import com.embitel.datalogger.blemodule.data.BleDevice; import com.embitel.datalogger.ui.configuration.DeviceListConfigurationScreen; import java.util.ArrayList; import java.util.List; public class DeviceLeAdapter extends RecyclerView.Adapter<DeviceLeAdapter.ViewHolder> { //private MyListData[] listdata; List<BleDevice> deviceData; onDevicesItemClick onDevicesItemClick; private Context context; public DeviceLeAdapter(Context context) { this.context = context; deviceData = new ArrayList<>(); } // RecyclerView recyclerView; @Override public DeviceLeAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext()); View listItem = layoutInflater.inflate(R.layout.item_scan_devices, parent, false); DeviceLeAdapter.ViewHolder viewHolder = new ViewHolder(listItem); return viewHolder; } @Override public void onBindViewHolder(DeviceLeAdapter.ViewHolder holder, final int position) { if (holder != null && !deviceData.isEmpty()) { if (deviceData.get(position).getName() != null) { if(deviceData.get(position).isConfigured()) { holder.txName.setTextColor(ContextCompat.getColor(context,R.color.colorAccent)); holder.txtStatus.setText(R.string.configured); holder.txtStatus.setTextColor(ContextCompat.getColor(context,R.color.colorAccent)); holder.imgBle.setBackground(ContextCompat.getDrawable(context,R.drawable.conf_ble)); holder.txtStatus.setVisibility(View.VISIBLE); } else { holder.txName.setTextColor(ContextCompat.getColor(context,R.color.colorBlack)); holder.imgBle.setBackground(ContextCompat.getDrawable(context,R.drawable.not_conf_ble)); holder.txtStatus.setVisibility(View.GONE); } holder.txName.setText(deviceData.get(position).getName()); } else { holder.txName.setText("Unknown Device"); } holder.txAddress.setText(deviceData.get(position).getMac()); holder.linearLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onDevicesItemClick.onDevicesItemClick(deviceData.get(position)); } }); } } public void setOnDevicesItemClick(onDevicesItemClick onDevicesItemClick) { this.onDevicesItemClick = onDevicesItemClick; } @Override public int getItemCount() { return deviceData.size(); } public static class ViewHolder extends RecyclerView.ViewHolder { public TextView txName; public TextView txAddress, txtStatus; public LinearLayout linearLayout; private ImageView imgBle; public ViewHolder(View itemView) { super(itemView); this.txName = (TextView) itemView.findViewById(R.id.tx_name); this.txAddress = (TextView) itemView.findViewById(R.id.tx_address); this.imgBle=itemView.findViewById(R.id.img_ble); this.txtStatus = (TextView) itemView.findViewById(R.id.txt_configured_status); this.linearLayout = itemView.findViewById(R.id.ll_device); } } public void addDevice(BleDevice device) { if (!deviceData.contains(device)) { deviceData.add(device); } } public interface onDevicesItemClick { void onDevicesItemClick(BleDevice device); } }
true
8bc3629be9560259765b5f135218d1094305fc7c
Java
RaniereRamos/feast
/ingestion/src/test/java/feast/ingestion/transform/specs/WriteFeatureSetSpecAckTest.java
UTF-8
2,873
1.632813
2
[ "Apache-2.0" ]
permissive
/* * SPDX-License-Identifier: Apache-2.0 * Copyright 2018-2020 The Feast 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 feast.ingestion.transform.specs; import com.google.common.collect.ImmutableList; import feast.common.models.FeatureSetReference; import org.apache.beam.sdk.coders.AvroCoder; import org.apache.beam.sdk.testing.PAssert; import org.apache.beam.sdk.testing.TestPipeline; import org.apache.beam.sdk.testing.TestStream; import org.apache.beam.sdk.transforms.Flatten; import org.apache.beam.sdk.transforms.windowing.GlobalWindow; import org.apache.beam.sdk.values.PCollection; import org.apache.beam.sdk.values.PCollectionList; import org.joda.time.Duration; import org.junit.Rule; import org.junit.Test; public class WriteFeatureSetSpecAckTest { @Rule public transient TestPipeline p = TestPipeline.create(); @Test public void shouldSendAckWhenAllSinksReady() { TestStream<FeatureSetReference> sink1 = TestStream.create(AvroCoder.of(FeatureSetReference.class)) .addElements(FeatureSetReference.of("project", "fs", 1)) .addElements(FeatureSetReference.of("project", "fs", 2)) .addElements(FeatureSetReference.of("project", "fs", 3)) .advanceWatermarkToInfinity(); TestStream<FeatureSetReference> sink2 = TestStream.create(AvroCoder.of(FeatureSetReference.class)) .addElements(FeatureSetReference.of("project", "fs_2", 1)) .addElements(FeatureSetReference.of("project", "fs", 3)) .advanceWatermarkToInfinity(); TestStream<FeatureSetReference> sink3 = TestStream.create(AvroCoder.of(FeatureSetReference.class)) .advanceProcessingTime(Duration.standardSeconds(10)) .addElements(FeatureSetReference.of("project", "fs", 3)) .advanceWatermarkToInfinity(); PCollectionList<FeatureSetReference> sinks = PCollectionList.of( ImmutableList.of( p.apply("sink1", sink1), p.apply("sink2", sink2), p.apply("sink3", sink3))); PCollection<FeatureSetReference> grouped = sinks.apply(Flatten.pCollections()).apply(new WriteFeatureSetSpecAck.PrepareWrite(3)); PAssert.that(grouped) .inOnTimePane(GlobalWindow.INSTANCE) .containsInAnyOrder(FeatureSetReference.of("project", "fs", 3)); p.run(); } }
true
eec0535a9a07011c08d877d684291e93904c9069
Java
Double-Slash/playground-android
/app/src/main/java/com/doubleslash/playground/GroupList/GroupListFragment1.java
UTF-8
6,953
2.0625
2
[]
no_license
package com.doubleslash.playground.GroupList; import android.content.Intent; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.doubleslash.playground.CreateGroupActivity; import com.doubleslash.playground.FindGroupActivity; import com.doubleslash.playground.R; import com.doubleslash.playground.databinding.FragmentGroupList1Binding; import com.doubleslash.playground.retrofit.RetrofitClient; import com.doubleslash.playground.retrofit.dto.response.Total_group_responseDTO; import com.doubleslash.playground.infoGroup.InfoGroupActivity; public class GroupListFragment1 extends Fragment { private FragmentGroupList1Binding binding; private RetrofitClient retrofitClient; @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = FragmentGroupList1Binding.inflate(inflater, container, false); retrofitClient = RetrofitClient.getInstance(); initUI(); addItems("전체"); return binding.getRoot(); } private void initUI() { // 필터 버튼 binding.layoutFilter.setOnClickListener(view -> { if (binding.layoutFilterCategory.getVisibility() == View.GONE) { binding.tvFilter.setTextColor(getResources().getColor(R.color.white)); binding.imageFilter.setImageResource(R.drawable.ic_filter_white); binding.btnFilter.setBackgroundResource(R.drawable.ic_down_white); binding.layoutFilter.setBackgroundResource(R.drawable.ic_black_rounded_rectangle); binding.layoutFilterCategory.setVisibility(View.VISIBLE); } else { binding.tvFilter.setTextColor(getResources().getColor(R.color.sub_black)); binding.imageFilter.setImageResource(R.drawable.ic_filter); binding.btnFilter.setBackgroundResource(R.drawable.ic_down_sub_gray); binding.layoutFilter.setBackground(null); binding.layoutFilterCategory.setVisibility(View.GONE); } }); // 필터 항목 선택 binding.tvAll.setOnClickListener(view -> { binding.tvFilter.setText("전체"); binding.tvAll.setTextColor(getResources().getColor(R.color.sub_black)); binding.tvStudy.setTextColor(getResources().getColor(R.color.sub_gray)); binding.tvDiet.setTextColor(getResources().getColor(R.color.sub_gray)); binding.tvCultural.setTextColor(getResources().getColor(R.color.sub_gray)); binding.tvGame.setTextColor(getResources().getColor(R.color.sub_gray)); addItems("전체"); }); binding.tvStudy.setOnClickListener(view -> { binding.tvFilter.setText("스터디"); binding.tvAll.setTextColor(getResources().getColor(R.color.sub_gray)); binding.tvStudy.setTextColor(getResources().getColor(R.color.sub_black)); binding.tvDiet.setTextColor(getResources().getColor(R.color.sub_gray)); binding.tvCultural.setTextColor(getResources().getColor(R.color.sub_gray)); binding.tvGame.setTextColor(getResources().getColor(R.color.sub_gray)); addItems("스터디"); }); binding.tvDiet.setOnClickListener(view -> { binding.tvFilter.setText("운동/다이어트"); binding.tvAll.setTextColor(getResources().getColor(R.color.sub_gray)); binding.tvStudy.setTextColor(getResources().getColor(R.color.sub_gray)); binding.tvDiet.setTextColor(getResources().getColor(R.color.sub_black)); binding.tvCultural.setTextColor(getResources().getColor(R.color.sub_gray)); binding.tvGame.setTextColor(getResources().getColor(R.color.sub_gray)); addItems("운동/다이어트"); }); binding.tvCultural.setOnClickListener(view -> { binding.tvFilter.setText("문화생활"); binding.tvAll.setTextColor(getResources().getColor(R.color.sub_gray)); binding.tvStudy.setTextColor(getResources().getColor(R.color.sub_gray)); binding.tvDiet.setTextColor(getResources().getColor(R.color.sub_gray)); binding.tvCultural.setTextColor(getResources().getColor(R.color.sub_black)); binding.tvGame.setTextColor(getResources().getColor(R.color.sub_gray)); addItems("문화생활"); }); binding.tvGame.setOnClickListener(view -> { binding.tvFilter.setText("게임"); binding.tvAll.setTextColor(getResources().getColor(R.color.sub_gray)); binding.tvStudy.setTextColor(getResources().getColor(R.color.sub_gray)); binding.tvDiet.setTextColor(getResources().getColor(R.color.sub_gray)); binding.tvCultural.setTextColor(getResources().getColor(R.color.sub_gray)); binding.tvGame.setTextColor(getResources().getColor(R.color.sub_black)); addItems("게임"); }); // 소모임 생성 버튼 binding.addBtn.setOnClickListener(v -> { Intent intent = new Intent(getActivity(), CreateGroupActivity.class); startActivity(intent); }); // 소모임 검색 버튼 binding.searchBtn.setOnClickListener(v -> { Intent intent = new Intent(getActivity(), FindGroupActivity.class); startActivity(intent); }); } private void addItems(String category){ binding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); GroupAdapter adapter = new GroupAdapter(getContext()); Total_group_responseDTO body = retrofitClient.get_grouplist(); for (int i = 0; i < body.getData().size(); i++) { if (category.equals("전체") || body.getData().get(i).getCategory().equals(category)) { adapter.addItem(new Group( body.getData().get(i).getLocation(), body.getData().get(i).getCategory(), body.getData().get(i).getCurrentMemberCount(), body.getData().get(i).getMaxMemberCount(), body.getData().get(i).getName(), body.getData().get(i).getContent(), body.getData().get(i).getImageUri())); } } binding.recyclerView.setAdapter(adapter); adapter.setOnItemClickListener((holder, view, position) -> { Intent intent = new Intent(getActivity(), InfoGroupActivity.class); intent.putExtra("teamId", body.getData().get(position).getTeamId()); startActivity(intent); }); } }
true
8ccc6274eee59935840cc96c3fb5aebef4bfacb1
Java
hari1234512/proj
/src/com/harish/LoginJava.java
UTF-8
197
2.046875
2
[]
no_license
package com.harish; public class LoginJava { public boolean authenticate(String userId, String password){ if(password==null || password.trim()==""){ return false; } return true; } }
true
6ad32b75623cc1f0bb7f6b79f92093437cfe1d59
Java
ByteInSpace/MangaAnimeCollector
/src/main/java/de/byteinspace/mangaanime/entity/Manga.java
UTF-8
2,084
2.25
2
[]
no_license
package de.byteinspace.mangaanime.entity; import java.util.List; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; @Entity public class Manga { @Id @GeneratedValue private Long id; @ManyToOne private Serie serie; private int bandNummer; @ManyToOne private Autor autor; private int mangaCondition; @ManyToOne private Language language; private boolean hardCover; // True if Hard, False if Soft private int rating; @ManyToOne private Publisher publisher; private int ISBN; @OneToMany(mappedBy = "manga") private List<Goodies> goodies; private String fileName; public String getFileName() { return fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public Manga() { } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Serie getSerie() { return serie; } public void setSerie(Serie serie) { this.serie = serie; } public int getBandNummer() { return bandNummer; } public void setBandNummer(int bandNummer) { this.bandNummer = bandNummer; } public Autor getAutor() { return autor; } public void setAutor(Autor autor) { this.autor = autor; } public int getMangaCondition() { return mangaCondition; } public void setMangaCondition(int mangaCondition) { this.mangaCondition = mangaCondition; } public Language getLanguage() { return language; } public void setLanguage(Language language) { this.language = language; } public boolean isHardCover() { return hardCover; } public void setHardCover(boolean hardCover) { this.hardCover = hardCover; } public int getRating() { return rating; } public void setRating(int rating) { this.rating = rating; } public Publisher getPublisher() { return publisher; } public void setPublisher(Publisher publisher) { this.publisher = publisher; } public int getISBN() { return ISBN; } public void setISBN(int iSBN) { ISBN = iSBN; } }
true
cad077e33691bbc9efecbc63d001cda4c487c8ad
Java
BizarbotsRobotics/2021CompetitionRobot
/src/main/java/org/frcteam2910/c2020/subsystems/IntakeSubsystem.java
UTF-8
5,588
2.296875
2
[]
no_license
package org.frcteam2910.c2020.subsystems; import com.ctre.phoenix.motorcontrol.ControlMode; import com.ctre.phoenix.motorcontrol.StatusFrame; import com.ctre.phoenix.motorcontrol.can.TalonFX; import com.google.errorprone.annotations.concurrent.GuardedBy; import edu.wpi.first.networktables.NetworkTableEntry; import edu.wpi.first.wpilibj.Solenoid; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.shuffleboard.Shuffleboard; import edu.wpi.first.wpilibj.shuffleboard.ShuffleboardTab; import edu.wpi.first.wpilibj2.command.Subsystem; import org.frcteam2910.c2020.Constants; import org.frcteam2910.common.robot.UpdateManager; public class IntakeSubsystem implements Subsystem, UpdateManager.Updatable { public static final double MIN_INTAKE_MOVEMENT_PRESSURE = 60.0; private TalonFX right_intake_motor = new TalonFX(Constants.INTAKE_MOTOR_PORT); private Solenoid topExtentionSolenoid = new Solenoid(Constants.TOP_INTAKE_EXTENSION_SOLENOID); private Solenoid bottomExtensionSolenoid = new Solenoid(Constants.BOTTOM_INTAKE_EXTENSION_SOLENOID); private final Object stateLock = new Object(); @GuardedBy("stateLock") private double motorOutput = 0.0; @GuardedBy("stateLock") private boolean topExtended = false; @GuardedBy("stateLock") private boolean bottomExtended = false; @GuardedBy("stateLock") private boolean intakeCurrentThreshHoldPassed = false; private final NetworkTableEntry leftMotorSpeedEntry; private final NetworkTableEntry rightMotorSpeedEntry; private final NetworkTableEntry isTopExtendedEntry; private final NetworkTableEntry isBottomExtendedEntry; private final NetworkTableEntry leftMotorCurrent; private Timer fifthBallTimer; private boolean isTimerRunning; public IntakeSubsystem() { fifthBallTimer = new Timer(); this.isTimerRunning = false; ShuffleboardTab tab = Shuffleboard.getTab("Intake"); leftMotorSpeedEntry = tab.add("Left Motor Speed", 0.0) .withPosition(0, 0) .withSize(1, 1) .getEntry(); rightMotorSpeedEntry = tab.add("Right Motor Speed",0.0) .withPosition(1,0) .withSize(1,1) .getEntry(); isTopExtendedEntry = tab.add("Is Top Extended", false) .withPosition(0, 1) .withSize(1, 1) .getEntry(); isBottomExtendedEntry = tab.add("Is Bottom Extended", false) .withPosition(1, 1) .withSize(1, 1) .getEntry(); leftMotorCurrent = tab.add("Left Motor Current",0.0) .withPosition(0,2) .withSize(1,1) .getEntry(); } @Override public void update(double time, double dt) { double localMotorOutput; boolean localTopExtended; boolean localBottomExtended; synchronized (stateLock) { if(right_intake_motor.getStatorCurrent() > 20){ if(!isTimerRunning){ fifthBallTimer.start(); isTimerRunning = true; } } else { fifthBallTimer.stop(); fifthBallTimer.reset(); isTimerRunning = false; intakeCurrentThreshHoldPassed = false; } if(fifthBallTimer.get() > 0.25){ intakeCurrentThreshHoldPassed = true; } localMotorOutput = motorOutput; localTopExtended = topExtended; localBottomExtended = bottomExtended; } right_intake_motor.set(ControlMode.PercentOutput, localMotorOutput); if (localTopExtended != topExtentionSolenoid.get()) { topExtentionSolenoid.set(localTopExtended); } bottomExtensionSolenoid.set(true); } public boolean isTopExtended() { synchronized (stateLock) { return topExtended; } } public void setTopExtended(boolean topExtended) { synchronized (stateLock) { this.topExtended = topExtended; } } public void setMotorOutput(double motorOutput) { synchronized (stateLock) { this.motorOutput = motorOutput; } } public double getLeftMotorOutput() { synchronized (stateLock) { return right_intake_motor.getMotorOutputPercent(); } } public double getRightMotorOutput(){ synchronized (stateLock){ return right_intake_motor.getMotorOutputPercent(); } } public void setBottomExtended(boolean extended){ synchronized (stateLock){ bottomExtended = extended; } } public boolean isBottomExtended(){ synchronized (stateLock){ return bottomExtended; } } public boolean hasIntakeMotorPassedCurrentThreshHold(){ synchronized (stateLock){ return intakeCurrentThreshHoldPassed; } } public double getLeftMotorCurrent(){ synchronized (stateLock){ return right_intake_motor.getStatorCurrent(); } } @Override public void periodic() { leftMotorSpeedEntry.setDouble(getLeftMotorOutput()); rightMotorSpeedEntry.setDouble(getRightMotorOutput()); isTopExtendedEntry.setBoolean(topExtentionSolenoid.get()); isBottomExtendedEntry.setBoolean(bottomExtensionSolenoid.get()); leftMotorCurrent.setDouble(getLeftMotorCurrent()); } }
true
9ff949032c94f8239ddb391a971b8978d8419c0e
Java
hakim12345/dmsmicro
/dmsconsumer/src/main/java/com/dms/recieveClient/service/impl/MailServiceImpl.java
UTF-8
996
2.03125
2
[]
no_license
package com.dms.recieveClient.service.impl; import com.dms.recieveClient.common.MyAbstractOperation; import com.dms.recieveClient.model.TravelOperator; import com.dms.recieveClient.service.MailService; import com.dms.recieveClient.service.TenantService; import org.springframework.stereotype.Component; import org.springframework.stereotype.Service; import javax.inject.Inject; import javax.servlet.http.HttpSession; import javax.transaction.Transactional; import java.util.HashMap; import java.util.Map; @Service public class MailServiceImpl implements MailService { @Inject private TenantService tenantService; @Override public Map<String , Object> sendMail(String tenantId, final HttpSession session) { Map<String, Object> resMap = new HashMap<>(); TravelOperator travelOperator = tenantService.getById(Long.valueOf(tenantId)); resMap.put("travelOperator" ,travelOperator); resMap.put("mailStatus" , "true"); return resMap; } }
true
a532e689328c11c7bc86c028feabd64ddb55b04f
Java
katalan1245/Social-Activity-Android-App
/app/src/main/java/com/example/smartness/Website.java
UTF-8
1,361
1.960938
2
[]
no_license
package com.example.smartness; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.provider.MediaStore; import android.view.View; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ImageView; public class Website extends AppCompatActivity { private WebView webView; private ImageView back; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_website); back = (ImageView) findViewById(R.id.back); back.bringToFront(); webView = (WebView) findViewById(R.id.webView); webView.getSettings().setLoadWithOverviewMode(true); webView.getSettings().setUseWideViewPort(true); webView.setWebViewClient(new WebViewClient()); webView.loadUrl("https://www.nzc.org.il/"); WebSettings webSettings = webView.getSettings(); webSettings.setJavaScriptEnabled(true); } @Override public void onBackPressed() { if (webView.canGoBack()) { webView.goBack(); } else { super.onBackPressed(); } } public void bckToMain(View view) { startActivity(new Intent(this,HomeScreen.class));} }
true
ff46d7c623c16721717fb7ad4df7b5da66798fab
Java
HLWoock/JavaSandbox
/JavaSandbox/Java2/src/de/oose/threads/count/NormCount.java
UTF-8
137
2.171875
2
[]
no_license
package de.oose.threads.count; public class NormCount implements Count { int c = 0; @Override public int next() { return c++; } }
true
0724a16ed19298c012436efc3fddf35f93024209
Java
USTGLOBLE-2020/springassignments
/poojaAssig-143456/09-10-2020- assignment/StudentCRUDDemo/src/main/java/com/service/StudentServiceImpl.java
UTF-8
821
2.046875
2
[]
no_license
package com.service; import java.util.List; import org.jvnet.hk2.annotations.Service; import org.springframework.beans.factory.annotation.Autowired; import com.bean.Student; import com.dao.StudentDao; @Service public class StudentServiceImpl implements StudentService { @Autowired StudentDao studentDao; @Override public List<Student> getStudent() { // TODO Auto-generated method stub return studentDao.getStudent(); } @Override public void createEmployee(String name, String bloodgroup, String email, String mobile_no, String address) { studentDao.createEmployee(name, bloodgroup, email, mobile_no, address); } @Override public void updateStudent(Integer id, String email) { studentDao.updateStudent(id, email); } @Override public void deleteStudent() { studentDao.deleteStudent(); } }
true
d24f4afc3976f1800ff61c7111025b25524338fc
Java
zhouxinlei828/sparkzxl-cloud-learning
/sparkzxl-nacos-learn/sparkzxl-nacos-discovery-provider-env/src/main/java/com/github/sparkzxl/nacos/controller/TestController.java
UTF-8
536
1.859375
2
[]
no_license
package com.github.sparkzxl.nacos.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; /** * description: test * * @author charles.zhou * @date 2021-05-11 10:47:54 */ @RestController @Api(tags = "测试") public class TestController { @ApiOperation("echo") @GetMapping("/echo") public String echo(String name) { return "provider:" + name; } }
true
4a96d6b67625c27204c8ad6418c2742972e1b8d1
Java
Wertao/Trabalho-Interdiciplinar-2
/PrimeiraTelaControlador.java
ISO-8859-1
3,106
2.6875
3
[]
no_license
package telas; import aplicacao.MainApp; import dao.Jogadoresdao; import entidade.Jogadores; import javafx.fxml.FXML; import javafx.scene.control.Label; import javafx.scene.control.Labeled; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.control.Alert; import javafx.scene.control.Alert.AlertType; public class PrimeiraTelaControlador { @FXML private TableView<Jogadores> tabelaJogadores; @FXML private TableColumn<Jogadores, Number> colunaTime; @FXML private TableColumn<Jogadores, String> colunaNome; @FXML private TableColumn<Jogadores, String> colunaIdade; @FXML private Label lblNome; @FXML private Label lblTime; @FXML private Label lblIdade; @FXML private Label lblEmail; private MainApp mainApp; public PrimeiraTelaControlador() { } @FXML private void initialize() { colunaTime.setCellValueFactory(c->c.getValue().timeProperty()); colunaNome.setCellValueFactory(c->c.getValue().nomeProperty()); colunaIdade.setCellValueFactory(c->c.getValue().idadeProperty()); } public void setMainApp(MainApp mainApp) { this.mainApp = mainApp; Jogadoresdao dao = new Jogadoresdao(); tabelaJogadores.setItems(dao.getListaJogadores()); } @FXML private void deletarPessoa() { int indiceSelecionado = tabelaJogadores.getSelectionModel() .getSelectedIndex(); if(indiceSelecionado>=0) { //remove a pessoa do banco de dados Jogadoresdao jdao = new Jogadoresdao(); jdao.excluir( tabelaJogadores.getItems().get(indiceSelecionado)); tabelaJogadores.getItems().remove(indiceSelecionado); }else { Alert alerta = new Alert(AlertType.WARNING); alerta.setTitle("Nenhum registro selecionado"); alerta.setHeaderText("Nenhuma pessoa selecionada"); alerta.setContentText("Voc deve selecionar um registro na tabela"); alerta.showAndWait(); } } public void mostraDetalhes(Jogadores jogadores, Labeled lblTime) { if(jogadores !=null) { lblNome.setText(jogadores.getNome()); lblIdade.setText(jogadores.getIdade()); // foi necessrio converter de int para String lblTime.setText(String.valueOf(jogadores.getTime())); lblEmail.setText(jogadores.getEmail()); }else { lblNome.setText(""); lblIdade.setText(""); lblTime.setText(""); lblEmail.setText(""); lblTime.setText(""); } } @FXML private void cliqueNovaPessoa() { Jogadores jogadores = new Jogadores(""); mainApp.mostrarAdicionarEditarPessoa(jogadores); //mainApp.getLista().add(pessoa); tabelaJogadores.getItems().add(jogadores); //recarrega os dados do BD Jogadoresdao dao = new Jogadoresdao(); tabelaJogadores.setItems(dao.getListaJogadores()); // mostraDetalhes(pessoa); } @FXML private void cliqueEditarPessoa() { Jogadores jogadores = tabelaJogadores.getSelectionModel().getSelectedItem(); if(jogadores!=null) { MainApp.mostrarAdicionarEditarJogadores(); mostraDetalhes(jogadores, lblTime); } } }
true
f89e32826e85291926d0aa7339cc2b3cace38b89
Java
EddieXu123/LeetCodeProblems
/RepeatedSubstringPattern.java
UTF-8
1,270
4.15625
4
[]
no_license
class RepeatedSubstringPattern { public boolean repeatedSubstringPattern(String s) { String result = s + s; return result.substring(1, result.length() - 1).contains(s); /* int len = s.length(); for (int i = len / 2; i >= 1; i--) { // loop for divisor to partition string if (len % i == 0) { // If it divides evenly into my string.length() int m = len / i; // Get how many portions of this substring I'll get String sub = s.substring(0, i); // Build up the substring StringBuilder b = new StringBuilder(); for (int j = 0; j < m; j++) { b.append(sub); // Append the substring "portions" times } if (b.toString().equals(s)) return true; // Check if the appended portion equals the original string } } return false; */ } } /* Find all lengths that can divide by string evenly. Once you find this number, divide the strings length by this length (to get how many portions of the substring I can produce) Afterwards, create the substring. Then, append this substring (portions) time return if this new output string equals s */
true
9947c5612a2a014d1234ddef671b767e4b0d7102
Java
betimbryma/swine
/src/main/java/io/bryma/betim/swine/controllers/NegotiationController.java
UTF-8
1,585
2.28125
2
[ "Apache-2.0" ]
permissive
package io.bryma.betim.swine.controllers; import eu.smartsocietyproject.peermanager.PeerManagerException; import io.bryma.betim.swine.DTO.NegotiationDTO; import io.bryma.betim.swine.exceptions.NegotiationException; import io.bryma.betim.swine.model.Negotiable; import io.bryma.betim.swine.model.Negotiation; import io.bryma.betim.swine.services.NegotiationService; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.security.Principal; @RestController @RequestMapping("/api/negotiation/") public class NegotiationController { private NegotiationService negotiationService; public NegotiationController(NegotiationService negotiationService) { this.negotiationService = negotiationService; } @GetMapping("{id}") public ResponseEntity<?> getNegotiation(@PathVariable Long id, Principal principal){ try { NegotiationDTO negotiationDTO = negotiationService.getNegotiable(id, principal.getName()); return ResponseEntity.ok(negotiationDTO); } catch (NegotiationException e) { return ResponseEntity.notFound().build(); } } @PostMapping("negotiate") public ResponseEntity<?> negotiate(@RequestBody Negotiable negotiable, Principal principal){ try { negotiationService.negotiate(negotiable, principal.getName()); return ResponseEntity.ok(negotiable); } catch (NegotiationException | PeerManagerException e) { return ResponseEntity.notFound().build(); } } }
true
d1599433c2c7da42f360dd3707458035cf13cd3d
Java
Themandunord/SkyRoomTheGame
/src/monster/Strike.java
ISO-8859-1
2,056
3.25
3
[]
no_license
package monster; import org.newdawn.slick.Animation; import org.newdawn.slick.Graphics; import org.newdawn.slick.SlickException; import org.newdawn.slick.SpriteSheet; import org.newdawn.slick.geom.Rectangle; /** * Classe permettant de crer des coups d'pes pour les monstres * * @author Stanislas * */ public class Strike { /** Coordonnes du coup */ private float xStrike, yStrike; /** Image du coup */ private SpriteSheet strikeUpSprite, strikeDownSprite, strikeLeftSprite, strikeRightSprite; /** Animation de l'pe */ private Animation strikeU,strikeD,strikeL,strikeR; /** Rectangle de collision de l'pe */ private Rectangle rec; public Strike(){ try{ strikeUpSprite = new SpriteSheet("res/monster/strikeImageU.png",32,32); strikeDownSprite = new SpriteSheet("res/monster/strikeImageD.png",32,32); strikeLeftSprite = new SpriteSheet("res/monster/strikeImageL.png",32,32); strikeRightSprite = new SpriteSheet("res/monster/strikeImageR.png",32,32); } catch (SlickException e) {e.printStackTrace();} strikeU = new Animation(strikeUpSprite,0,0,4,0,true,100,true); strikeD = new Animation(strikeDownSprite,0,0,4,0,true,100,true); strikeL = new Animation(strikeLeftSprite,0,0,0,4,true,100,true); strikeR = new Animation(strikeRightSprite,0,0,0,4,true,100,true); rec = new Rectangle(0,0,0,0); } public void renderUp(Graphics g, float x, float y){ strikeU.start(); strikeU.draw(x,y); } public void UpdateUp(float x, float y){ rec.setBounds((int) x+15,(int) y+5, 5, 15); } public void renderDown(Graphics g, float x, float y){ strikeD.start(); strikeD.draw(x,y); rec.setBounds((int) x+15,(int) y+5,5,15); } public void renderLeft(Graphics g, float x, float y){ strikeL.start(); strikeL.draw(x, y); rec.setBounds((int) x+15,(int) y+15, 10, 5); } public void renderRight(Graphics g, float x, float y){ strikeR.start(); strikeR.draw(x, y); rec.setBounds((int) x+5,(int) y+15, 10, 5); } public Rectangle getRect(){ return rec; } }
true
8e45e78486efaf23427368de685ac6c28aa6d0c9
Java
hortonworks/cloudbreak
/structuredevent-service-legacy/src/main/java/com/sequenceiq/cloudbreak/structuredevent/auditeventname/rest/RestResourceAuditEventConverter.java
UTF-8
726
1.679688
2
[ "LicenseRef-scancode-warranty-disclaimer", "ANTLR-PD", "CDDL-1.0", "bzip2-1.0.6", "Zlib", "BSD-3-Clause", "MIT", "EPL-1.0", "LicenseRef-scancode-proprietary-license", "LicenseRef-scancode-jdbm-1.00", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
package com.sequenceiq.cloudbreak.structuredevent.auditeventname.rest; import java.util.HashMap; import java.util.Map; import com.sequenceiq.cloudbreak.audit.model.AuditEventName; import com.sequenceiq.cloudbreak.auth.crn.Crn; import com.sequenceiq.cloudbreak.structuredevent.event.StructuredRestCallEvent; public interface RestResourceAuditEventConverter { AuditEventName auditEventName(StructuredRestCallEvent structuredRestCallEvent); boolean shouldAudit(StructuredRestCallEvent structuredRestCallEvent); Crn.Service eventSource(StructuredRestCallEvent structuredEvent); default Map<String, Object> requestParameters(StructuredRestCallEvent structuredEvent) { return new HashMap<>(); } }
true
f50e08f68c43b7efc5d406783f03b960615241cb
Java
QALeapThought/LT.UITests.Fulcrum
/Fulcrum_Trunk/src/com/proj/suiteTRANSMITTALS/FUL_Transmittals_HelpLink.java
UTF-8
2,091
1.796875
2
[]
no_license
package com.proj.suiteTRANSMITTALS; import java.util.Hashtable; import org.testng.annotations.Test; import com.frw.Constants.Constants_FRMWRK; import com.proj.library.commonMethods; import com.proj.navigations.Navigations_Fulcrum; import com.proj.suiteTRANSMITTALS.pages.Transmittals_EntryPage; import com.proj.util.CustomExceptions; import com.proj.util.TestExecutionUtil; public class FUL_Transmittals_HelpLink extends TestSuiteBase{ static Hashtable<String,String>transmittalData=new Hashtable<String,String>(); private static String workflow_l1="Level-1:-Initiation of Transmittal"; private static String workflow_help="Verify Help Link in New Transmittal form "; private static String workflow_end=" || "; @Test(dataProviderClass=com.proj.util.DataProviders.class,dataProvider="getData_Global") public static void TestFUL_Transmittals_HelpLink(Hashtable<String,String>data ) throws Throwable{ System.out.println("In test"); logsObj.log("******************************************************"); logsObj.log("Executing the test case: "+testcaseName); try{ if(isBeforeMethodPass_trans==Constants_FRMWRK.FalseB){ CustomExceptions.Exit(testcaseName, "Before Method-Failure", "Due to above error in the Before Method cannot execute the test.."); } String condition=""; condition=" ["+data.get("TxType")+"]"; workflow_l1=workflow_l1+condition+workflow_end; Navigations_Fulcrum.Transmittals.navigateToNewTransmittal(driver_TRANS,workflow_help); commonMethods.pageLoadWait(driver_TRANS); Transmittals_EntryPage.checkTransmittalHelpEnabled(driver_TRANS, refID, testcaseName, workflow_help); Transmittals_EntryPage.clickTransmittalHelpLink(driver_TRANS, workflow_help, refID, testcaseName); Transmittals_EntryPage.validate_TransmittalhelpWindow(driver_TRANS,refID,testcaseName,workflow_help); logsObj.log(" after test of "+testcaseName+"-testresult"+isTestPass); }catch(Throwable t){ CustomExceptions.final_catch_Reporting(driver_TRANS,refID,t); } TestExecutionUtil.AssertTestStatus(isTestPass); } }
true
a8750f3dee04d1d03b51493edd68fffa593db368
Java
RanQingTian/FastInformerServer
/src/BasicObjects/package-info.java
UTF-8
252
1.726563
2
[]
no_license
/*该java包描述了服务器端涉及到的基本对象类型 * */ package BasicObjects; /*需要在MySQL中建表的类 *Acceptor *Informer *Message *MessageRecord * *需要创建的数据库调用,添加、修改、查找、删除 */
true
93cd946767a98c2881feedbf642fe2ab9e5d191e
Java
raohaha/TuZhuTravle
/src/main/java/com/qf/travel/controller/po/PlayRoute.java
UTF-8
227
1.851563
2
[]
no_license
package com.qf.travel.controller.po; public class PlayRoute { private String route; public String getRoute() { return route; } public void setRoute(String route) { this.route = route; } }
true
ca0543c758f5e7040ec58b46d2600df5a74b81d7
Java
Jeevi21/Arsenal
/src/com/jv/dp/LongestIncreasingSubsequnce.java
UTF-8
2,393
3.390625
3
[]
no_license
package com.jv.dp; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; /** * LIS - Longest Increasing Subseq * @author Jeevi.Natarajan * */ public class LongestIncreasingSubsequnce { private static int LISUtil(int [] arr , int st, int length , List<Integer> choosen) { if(st>=arr.length) return length; else if(!choosen.isEmpty() && choosen.get(choosen.size()-1) >= arr[st]){ return LISUtil(arr, st+1, length, choosen); //Not choosing } else { choosen.add(arr[st]); int lenOnChoosing = LISUtil(arr, st+1, length+1, choosen); choosen.remove(choosen.size()-1); //not choose.. int lenOnNotChoosing = LISUtil(arr, st+1, length, choosen); return Math.max(lenOnChoosing, lenOnNotChoosing); } } private static int LISUtilDP(int [] arr , int st, int lastElem, Map<String,Integer> cache) { String key= st+":"+lastElem; if(st>=arr.length) return 0; else if(!cache.containsKey(key)) { int lenOnChoosing =0 ; if(lastElem< arr[st]) { lenOnChoosing = 1+LISUtilDP(arr, st+1, arr[st],cache); } //not choose.. int lenOnNotChoosing = LISUtilDP(arr, st+1, lastElem,cache); cache.put(key, Math.max(lenOnChoosing, lenOnNotChoosing)); } return cache.get(key); } private static int LISUtilDPArr(int [] arr , int st, int prevIndex, int [] [] cache) { if(st>=arr.length) return 0; else if(cache[st][prevIndex+1]==-1) { int lenOnChoosing =0 ; if(prevIndex<0 || arr[prevIndex]< arr[st]) { lenOnChoosing = 1+LISUtilDPArr(arr, st+1, st,cache); } //not choose.. int lenOnNotChoosing = LISUtilDPArr(arr, st+1, prevIndex,cache); cache[st][prevIndex+1] = Math.max(lenOnChoosing, lenOnNotChoosing); } return cache[st][prevIndex+1]; } public static int LIS(int [] arr) { /* Map<String,Integer> cache = new HashMap<String,Integer>(); int len = LISUtilDP(arr, 0,Integer.MIN_VALUE , cache); System.out.println("--cache : " + cache + "--size : " + cache.size()); return len; */ int [] [] cache = new int[arr.length+1][arr.length+1]; Arrays.fill(cache, -1); return LISUtilDPArr(arr, 0, -1, cache); } public static void main(String[] args) { int [] arr = {10,9,2,5,3,7,101,18}; System.out.println("--length : " + LIS(arr)); } }
true
712b7c859a8a1f3e72613962d16e45edff0ef7ad
Java
NagaBabu146/TxMngrAnnotaion_DataSourceTxMngr
/TxManagement_Annotation(DataSourceTxMngr)/src/main/java/com/nt/service/AccountServiceImpl.java
UTF-8
782
2.546875
3
[]
no_license
package com.nt.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.nt.dao.AccountDAO; @Service("accserv") public class AccountServiceImpl implements AccountService { @Autowired private AccountDAO dao; public AccountServiceImpl(AccountDAO dao) { this.dao = dao; } @Override public String transferMoney(int srcNo, int destNo, int amt) { int count1=dao.withdraw(srcNo, amt); int count2=dao.deposit(destNo, amt); if(count1==0||count2==0) { throw new RuntimeException("Incomplete Details and Invalid account(Tx Rollback)"); }else { System.out.println("MoneyTransfer Succesfully(Tx Commited)"); } return "Money Transfer Successfully"; } }
true
a71d79f48c065160df5e81a4d3c3f1a3f75e04e5
Java
LuisFernando1407/retrofit_rxjava
/app/src/main/java/com/br/retrofit_rxjava/ui/dialog/ConfirmDialogViewModel.java
UTF-8
1,095
2.265625
2
[]
no_license
package com.br.retrofit_rxjava.ui.dialog; import com.br.retrofit_rxjava.ui.dialog.base.BaseDialogViewModel; import com.br.retrofit_rxjava.ui.dialog.listener.ConfirmDialogListener; public class ConfirmDialogViewModel extends BaseDialogViewModel<ConfirmDialogNavigator> { private ConfirmDialogListener listener; private Object payload; public String textTitle; public String textMessage; public String textButtonCancel; public String textButtonSuccess; public void dismissPress(){ this.navigator().onDismiss(); } public void confirmPress(){ this.listener.onConfirm(this.payload); } public void setData( String textTitle, String textMessage, String textButtonCancel, String textButtonSuccess, ConfirmDialogListener listener, Object payload){ this.textTitle = textTitle; this.textMessage = textMessage; this.textButtonCancel = textButtonCancel; this.textButtonSuccess = textButtonSuccess; this.listener = listener; this.payload = payload; } }
true
8e070a55b4c9901e7c2898077c3803db6302e9b4
Java
caams/MyP_Proyecto1
/src/ChocolateConLeche.java
UTF-8
508
3.109375
3
[]
no_license
public class ChocolateConLeche extends Chocolate{ public ChocolateConLeche(){ this.nombre = "Chocolate con Leche"; this.getIngredientes().add(new Ingrediente("Leche", 3, 3200)); } @Override public void prepararBase(){ System.out.println("Preparando base de Chocolate con Leche:"); this.usarIngrediente("Manteca de Cacao"); this.usarIngrediente("Cacao"); this.usarIngrediente("Azúcar"); this.usarIngrediente("Leche"); } @Override public void agregarComplemento(){} }
true