blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
sequencelengths
1
1
author_id
stringlengths
0
313
bd5df0f05b2cd441f8ec48a505b6b916df576c2b
aa97b1475ae6d7d93cfafe64565d0f461d1551b5
/aussie/codechicken/lib/render/IconTransformation.java
9a7b1b8907066e9a0d61997075ec4361872c636c
[]
no_license
ridixcr/AdventureBackpack
bb6e3568a8fdf1df0013de08798c3109f61b689c
fa3aed5ffd5e349d29be9787093089da4eb92911
refs/heads/master
2021-01-17T22:16:54.127940
2013-10-05T07:39:50
2013-10-05T07:39:50
48,337,783
1
0
null
2015-12-20T21:27:20
2015-12-20T21:27:20
null
UTF-8
Java
false
false
436
java
package aussie.codechicken.lib.render; import net.minecraft.util.Icon; public class IconTransformation implements IUVTransformation { public Icon icon; public IconTransformation(Icon icon) { this.icon = icon; } @Override public void transform(UV texcoord) { texcoord.u = icon.getInterpolatedU(texcoord.u%2*16); texcoord.v = icon.getInterpolatedV(texcoord.v%2*16); } }
202e2763cf8b511c9f676be27437ead89e7bbba3
8d1b2718418c46adf099534781dcee048d8e810a
/src/main/java/algorithm/linkedlist/ListNode.java
f9d73113288697620305a99ff2f2498be547d99f
[]
no_license
laigepotato/practice
2e69056f3e7d0fd310d6fbf5e1e0cbd4d3e87337
3d946b2cba4eb8d1cd84fd946b9fe23d62ccecc8
refs/heads/master
2023-09-02T19:25:04.342822
2021-10-26T15:37:18
2021-10-26T15:37:18
410,583,857
0
0
null
null
null
null
UTF-8
Java
false
false
290
java
package algorithm.linkedlist; /** * @program: practice * @description: * @author: Sansanli * @create: 2021-10-03 21:30 */ public class ListNode { ListNode next; Object value; public ListNode(Object value){ this.value = value; this.next = next; } }
f48df47bc2098fd67cfef95974424d80f1b9c534
f630f0fe33f7053de3a2f67dd9856e90bf74570d
/Z_ResumenExamen/src/A4_JaxB/Alumnos.java
c5aac9403048c3c8705a900495df4edf234ef70d
[]
no_license
macpratony/Acceso_Datos
3ee3222af44836a727f5e8dc1f2836595d4fbafc
6676a92be93b9d5737db4695d5e77cbbe585ae19
refs/heads/master
2023-07-17T14:56:59.036016
2021-09-09T08:47:41
2021-09-09T08:47:41
304,580,825
0
0
null
null
null
null
UTF-8
Java
false
false
495
java
package A4_JaxB; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement public class Alumnos { List<Alumno> alumno; public Alumnos() { } public Alumnos(List<Alumno> alumno) { super(); this.alumno = alumno; } public List<Alumno> getAlumno() { /*if(alumno == null) return new ArrayList<Alumno>();*/ return alumno; } public void setAlumno(List<Alumno> alumno) { this.alumno = alumno; } }
a7ebc959c39f4f36530d31208c1590df3d262d4d
62495169d3e327725956ed93403ecf925d57a489
/piflow-web/src/main/java/cn/cnic/base/config/jwt/CustomUserDetailsService.java
d9124ecc62a996c4c925ce645a7519b63c122bc2
[ "Apache-2.0" ]
permissive
cas-bigdatalab/piflow-web
681a32c1da76fb88792e5fbac52ea0305fb7909c
1e84686279ceadb7a4a096e3b97db2f59d8fb263
refs/heads/master
2023-06-08T08:42:15.071556
2023-05-25T02:04:59
2023-05-25T02:04:59
150,813,542
66
47
Apache-2.0
2023-03-06T22:42:41
2018-09-29T02:01:37
JavaScript
UTF-8
Java
false
false
3,664
java
package cn.cnic.base.config.jwt; import java.util.ArrayList; import java.util.List; import org.apache.commons.collections.CollectionUtils; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; import cn.cnic.base.vo.UserVo; import cn.cnic.common.Eunm.SysRoleType; import cn.cnic.component.system.mapper.SysMenuMapper; import cn.cnic.component.system.mapper.SysUserMapper; import cn.cnic.component.system.entity.SysMenu; import cn.cnic.component.system.entity.SysRole; import cn.cnic.component.system.entity.SysUser; import cn.cnic.component.system.vo.SysMenuVo; /** * 登陆身份认证 */ @Component public class CustomUserDetailsService implements UserDetailsService { private final SysUserMapper sysUserMapper; private final SysMenuMapper sysMenuMapper; @Autowired public CustomUserDetailsService(SysUserMapper sysUserMapper, SysMenuMapper sysMenuMapper) { this.sysUserMapper = sysUserMapper; this.sysMenuMapper = sysMenuMapper; } @Override public UserVo loadUserByUsername(String username) throws UsernameNotFoundException { UserVo userVo = null; SysUser sysUser = sysUserMapper.findUserByUserName(username); if (sysUser == null) { throw new UsernameNotFoundException(String.format("No user found with username '%s'.", username)); } if (null != sysUser) { userVo = new UserVo(); userVo.setUsername(sysUser.getUsername()); userVo.setPassword(sysUser.getPassword()); userVo.setName(sysUser.getName()); userVo.setAge(sysUser.getAge()); List<SysRole> sysRoleTypes = sysUser.getRoles(); userVo.setRoles(sysRoleTypes); if (CollectionUtils.isNotEmpty(sysRoleTypes)) { SysRoleType sysRoleHighest = null; String[] valueArray = new String[sysRoleTypes.size()]; for (int i = 0; i < sysRoleTypes.size(); i++) { SysRole sysRole = sysRoleTypes.get(i); if (null != sysRole && null != sysRole.getRole()) { SysRoleType role = sysRole.getRole(); valueArray[i] = sysRole.getRole().getValue(); if (role == SysRoleType.ADMIN) { sysRoleHighest = role; } } } if (valueArray.length > 0) { userVo.setAuthorities(AuthorityUtils.createAuthorityList(valueArray)); if (null == sysRoleHighest) { sysRoleHighest = SysRoleType.USER; } } List<SysMenu> sysMenuList = sysMenuMapper.getSysMenuList(sysRoleHighest.getValue()); if (CollectionUtils.isNotEmpty(sysMenuList)) { List<SysMenuVo> sysMenuVoList = new ArrayList<>(); SysMenuVo sysMenuVo; for (SysMenu sysMenu : sysMenuList) { sysMenuVo = new SysMenuVo(); BeanUtils.copyProperties(sysMenu, sysMenuVo); sysMenuVoList.add(sysMenuVo); } userVo.setSysMenuVoList(sysMenuVoList); } } } return userVo; } }
905541bd14e53d5b9c2ea8338f4c8b5ad284e18d
45778fde886de28e2e95ad3ff3904213e89720a0
/app/src/main/java/com/joe/androidkeystore/MainActivity.java
33fb5a06f1e59852ea7c36b2e6b6424a74417c38
[]
no_license
whysqwhw/AndroidKeyStore
bbe15c37c6cc1a02c977f38173ae3431099d09d9
25ce23eddf4bb3fd74cf8861b03a8f4dc120bf93
refs/heads/master
2023-05-30T12:32:07.222689
2021-06-18T14:39:56
2021-06-18T14:39:56
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,633
java
package com.joe.androidkeystore; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { EditText editTextInput; TextView textEncrypt; TextView textDecrypt; Button buttonEncrypt; Button buttonDecrypt; Button buttonSave; KeyStoreHelper keyStoreHelper; SharedPreferencesHelper preferencesHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); preferencesHelper = new SharedPreferencesHelper(getApplicationContext()); keyStoreHelper = new KeyStoreHelper(getApplicationContext(), preferencesHelper); initView(); initEditTextInput(); setupButton(); } private void initEditTextInput() { String encryptedText = preferencesHelper.getInput(); String plainInput = keyStoreHelper.decrypt(encryptedText); editTextInput.setText(plainInput); } private void setupButton() { buttonEncrypt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String encryptedText = keyStoreHelper.encrypt(editTextInput.getText().toString()); textEncrypt.setText(encryptedText); } }); buttonDecrypt.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String decryptedText = keyStoreHelper.decrypt(textEncrypt.getText().toString()); textDecrypt.setText(decryptedText); } }); buttonSave.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { preferencesHelper.setInput(textEncrypt.getText().toString()); Toast.makeText(getApplicationContext(), "Successfully saved!", Toast.LENGTH_SHORT).show(); } }); } private void initView() { editTextInput = (EditText) findViewById(R.id.editText_input); textEncrypt = (TextView) findViewById(R.id.text_encrypt); textDecrypt = (TextView) findViewById(R.id.text_decrypt); buttonEncrypt = (Button) findViewById(R.id.button_encrypt); buttonDecrypt = (Button) findViewById(R.id.button_decrypt); buttonSave = (Button) findViewById(R.id.button_save); } }
11bda42959980dad2cb727730f028626cb279101
d52e8de4ca24705dd88b3708c92dd931778b39e6
/WEB-INF/lib/ContAjoGerant.java
0f5ecb60aab78b9f2a4d54f5c380c9ec616d03bc
[]
no_license
BenoitLefebvre99/ProjetJEE
8b78c0f3e5c180b2733322f4943046dc4eb0264a
febfe55712787bcb076648e2021047ef6a6584ed
refs/heads/master
2022-04-19T23:37:55.152164
2020-04-11T08:48:59
2020-04-11T08:48:59
254,826,755
0
0
null
null
null
null
UTF-8
Java
false
false
5,585
java
import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.annotation.*; import java.io.*; import java.sql.*; import org.unbescape.html.HtmlEscape; @WebServlet("/ContAjoGerant") public class ContAjoGerant extends HttpServlet { public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { ContIntegrer include = new ContIntegrer(); res.setContentType("text/html"); PrintWriter out = res.getWriter(); //ON ENVOIE LA FORME PROPRE AU SITE ET DISPONIBLE SUR TOUTES LES PAGES out.println("<html>"); String head = HtmlEscape.unescapeHtml(include.getContent(FichiersInclude.HEAD)); out.println(head); out.println("<body>"); String navbar = HtmlEscape.unescapeHtml(include.getContent(FichiersInclude.NAVBAR)); out.println(navbar); String sidebar = HtmlEscape.unescapeHtml(include.getContent(FichiersInclude.SIDEBAR)); out.println(sidebar); //PARTIE SPECIFIQUE A LA PAGE COURANTE out.println("<div class=\"contenu\" id=\"contAjoGerant\">"); out.println("<h1>Ajouter un nouveau gérant</h1>"); //AFFICHAGE DES EVENTUELLES ALERTES String alert = HtmlEscape.unescapeHtml(include.getContent(FichiersInclude.ALERT)); out.println(alert); //AFFICHAGE DU FORMULAIRE out.println("<div class=\"shadow p-3 mb-5 bg-white rounded\">"); out.println("<div class=\"card\" >"); out.println("<div class=\"card-body\">"); Gerant g = new Gerant(0,"","",0,""); out.println("<form method=\"POST\" action=\"TraitementAjoutGerant\">"); out.println("<div class=\"form-group\">"); out.println("<div class=\"form-row\">"); try { //CONNEXION A LA BASE DE DONNEES. Class.forName("org.postgresql.Driver"); BDD c = new BDD(); Connection conn = DriverManager.getConnection(c.getUrl(), c.getLogin(), c.getPassword()); String sql; Statement stat; ResultSet rs; try { sql = "SELECT * FROM gerant WHERE id_gerant = " + req.getParameter("id") + " ;"; stat = conn.createStatement(); rs = stat.executeQuery(sql); while (rs.next()) { g = new Gerant(rs.getInt("id_gerant"), rs.getString("nom_gerant"), rs.getString("prenom_gerant"), rs.getInt("id_statut"), rs.getString("remarques_gerant")); } }catch(Exception e){ out.println("erreur de récupération"); } //INPUT NOM GERANT out.println("<div class=\"form-group col-md-4\">"); out.println("<label for=\"inputNomGerant\">Nom</label>"); out.println("<input type=\"input\" class=\"form-control\" id=\"inputNomGerant\" name=\"inputNomGerant\" placeholder=\"Nom\" value=\""+g.getNom()+"\">"); out.println("</div>"); //INPUT PRENOM GERANT out.println("<div class=\"form-group col-md-4\">"); out.println("<label for=\"inputPrenomGerant\">Prénom</label>"); out.println("<input type=\"input\" class=\"form-control\" id=\"inputPrenomGerant\" name=\"inputPrenomGerant\" placeholder=\"Prénom\" value=\""+g.getPrenom()+"\">"); out.println("</div>"); //INPUT DE SELECTION DU STATUT out.println("<div class=\"form-group col-md-4\">"); out.println("<label for=\"inputStatut\">Statut</label>"); out.println("<select id=\"inputStatut\" name=\"inputStatut\" class=\"form-control\" >"); //RECUPERATION DE LA LISTE DES STATUTS try { //ON RECUPERE LA LISTE sql = "SELECT * "+ "FROM statut;"; stat = conn.createStatement(); rs = stat.executeQuery(sql); while(rs.next()){ if(rs.getInt("id_statut") == g.getId_statut()) out.println("<option value=\""+rs.getInt("id_statut")+"\" selected>"+rs.getString("nom_statut")+"</option>"); else out.println("<option value=\""+rs.getInt("id_statut")+"\">"+rs.getString("nom_statut")+"</option>"); } stat.close(); }catch(Exception e){ out.println(e.getMessage()); } out.println("</select>"); out.println("</div>"); out.println("</div>"); out.println("</div>"); //INPUT DES REMARQUES SUR LE GERANT out.println("<div class=\"form-group\">"); out.println("<label for=\"inputRemarque\">Remarques</label>"); out.println("<textarea class=\"form-control\" id=\"inputRemarque\" name=\"inputRemarque\" rows=\"5\" placeholder=\"Remarques...\">"+g.getRemarques()+"</textarea>"); out.println("</div>"); //BOUTON SUBMIT out.println(" <button type=\"submit\" class=\"btn btn-success\" style=\"float: right;\">Créer</button>"); }catch(Exception e){ out.println(e.getMessage()); } out.println("</form>"); out.println("</div>"); out.println("</div>"); out.println("</div>"); out.println("</div>"); String cookies = HtmlEscape.unescapeHtml(include.getContent(FichiersInclude.COOKIES)); out.println(cookies); out.println("</body>"); out.println("</html>"); out.close(); } }
f652be73020411e7b80f224e14510852d0ddebf6
6229390cdcca859e9ff9cea1a005af953418be74
/src/main/java/l100/q40.java
a1f7cf8566f87d178ab855260debedadb6974511
[]
no_license
nkudinov/algo
7901f714135cefd6e6cd3eae7eea723f6b40c049
46cf2ce1a6958120300435afa491e9aba85e6151
refs/heads/master
2022-09-11T06:25:53.832356
2021-10-25T16:16:11
2021-10-25T16:16:11
216,255,323
3
0
null
2022-09-01T23:31:19
2019-10-19T18:52:00
Java
UTF-8
Java
false
false
1,453
java
package l100; public class q40 { static boolean equals(char[] arr1,int i, int j, char[] arr2, int i2, int j2){ if (j-i!=j2-i2){ return false; } int k = 0; while( i+k <= j){ if (arr1[i+k] != arr2[i2+k]){ return false; } k++; } return true; } static int calcHash(char[] arr, int i, int j){ int ans = 0; for(int k = i ; k <=j; k++){ ans = ans*10 + (arr[k]-'A'+1); } return ans; } static boolean isSubstring(String str, String s){ int M = s.length(); int pow = (int)Math.pow(10,M-1); int N = str.length(); char sub[] = s.toCharArray(); char[] arr = str.toCharArray(); int subHash = calcHash( sub,0,M-1); int winHash = calcHash( arr,0,M-1); if (subHash == winHash && equals(arr,0, M-1, sub, 0, M-1)){ return true; } for(int i = M; i < N; i++){ int first = (arr[i-M]-'A'+1); int last = (arr[i]-'A'+1); winHash = (winHash -first*pow)*10 + last; if (winHash == subHash && equals(arr,i-M+1, i, sub, 0, M-1)){ return true; } } return false; } public static void main(String[] args) { System.out.println(isSubstring("BAA","AA")); System.out.println(isSubstring("BDAAC","AAA")); } }
624ba27ca5b73ef85e7e10061aca2f4afc7538eb
7e1511cdceeec0c0aad2b9b916431fc39bc71d9b
/flakiness-predicter/input_data/original_tests/doanduyhai-Achilles/nonFlakyMethods/info.archinnov.achilles.type.CounterBuilderTest-should_incr.java
1826fe74c4d0a569252b5eafb15187a0a8b122af
[ "BSD-3-Clause" ]
permissive
Taher-Ghaleb/FlakeFlagger
6fd7c95d2710632fd093346ce787fd70923a1435
45f3d4bc5b790a80daeb4d28ec84f5e46433e060
refs/heads/main
2023-07-14T16:57:24.507743
2021-08-26T14:50:16
2021-08-26T14:50:16
null
0
0
null
null
null
null
UTF-8
Java
false
false
137
java
@Test public void should_incr() throws Exception { Counter counter=CounterBuilder.incr(); assertThat(counter.get()).isEqualTo(1L); }
90246a9bc6f023ce522ee2eac30da58ed6d79809
f8517de40106c2fc190f0a8c46128e8b67f7c169
/AllJoyn/Samples/OICAdapter/iotivity-1.0.0/service/simulator/java/eclipse-plugin/ServiceProviderPlugin/src/oic/simulator/serviceprovider/Activator.java
f9816d399fb543b5e499d06e3522834a6a94addb
[ "MIT", "BSD-3-Clause", "GPL-2.0-only", "Apache-2.0" ]
permissive
ferreiramarcelo/samples
eb77df10fe39567b7ebf72b75dc8800e2470108a
4691f529dae5c440a5df71deda40c57976ee4928
refs/heads/develop
2023-06-21T00:31:52.939554
2021-01-23T16:26:59
2021-01-23T16:26:59
66,746,116
0
0
MIT
2023-06-19T20:52:43
2016-08-28T02:48:20
C
UTF-8
Java
false
false
2,711
java
/* * Copyright 2015 Samsung Electronics All Rights Reserved. * * 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 oic.simulator.serviceprovider; import oic.simulator.serviceprovider.manager.ImageManager; import oic.simulator.serviceprovider.manager.LogManager; import oic.simulator.serviceprovider.manager.ResourceManager; import org.eclipse.ui.plugin.AbstractUIPlugin; import org.osgi.framework.BundleContext; /** * The activator class controls the plug-in life cycle. */ public class Activator extends AbstractUIPlugin { // The plug-in ID public static final String PLUGIN_ID = "ServiceProviderPlugin"; // The shared instance private static Activator plugin; private static ResourceManager resourceManager; private static LogManager logManager; private static ImageManager imageManager; static { System.loadLibrary("SimulatorManager"); } public Activator() { } public void start(BundleContext context) throws Exception { super.start(context); plugin = this; setLogManager(new LogManager()); setResourceManager(new ResourceManager()); imageManager = ImageManager.getInstance(); } public void stop(BundleContext context) throws Exception { plugin = null; // Stopping Resource Manager if (null != resourceManager) { resourceManager.shutdown(); resourceManager = null; } // Stopping Log Manager if (null != logManager) { logManager.shutdown(); logManager = null; } super.stop(context); } public static Activator getDefault() { return plugin; } public ResourceManager getResourceManager() { return resourceManager; } private static void setResourceManager(ResourceManager manager) { Activator.resourceManager = manager; } public LogManager getLogManager() { return logManager; } private static void setLogManager(LogManager logManager) { Activator.logManager = logManager; } public ImageManager getImageManager() { return imageManager; } }
d7bc96484a91e1fa0f72fe97bcfe7135f592fa05
d7972684fdd07284128d8d922ea7dbfa1dbad1ed
/service/service_statistic8007/src/main/java/com/github/stat/rabbitmq/VideoViewCount.java
60ee940228091cd57ae6897554c1d41bc5c908eb
[ "MIT" ]
permissive
a1040648671/Online-Education-Backend
e6c928e0c1793f3fdca2cc8d9a582fb9a00d6301
2e831abb1a88774737546295c9025c389fe2324f
refs/heads/master
2023-08-31T07:35:06.194581
2021-09-22T16:51:48
2021-09-22T16:51:48
null
0
0
null
null
null
null
UTF-8
Java
false
false
658
java
package com.github.stat.rabbitmq; import com.github.stat.service.StatisticsDailyService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; import java.util.function.Consumer; /** * @author HAN * @version 1.0 * @create 04-30-21:44 */ @Component public class VideoViewCount { @Autowired private StatisticsDailyService statisticsDailyService; /** * 统计视频观看数量+1 */ @Bean public Consumer<String> videoViewCountStat() { return date -> statisticsDailyService.videoViewCount(date); } }
50bc516613f048503e9ae7ab6727c03e8bb85139
6affebec89b7fc2b7b90fa93dca1f7af36783f9a
/O021MergeTwoSortedLists.java
968262359f01d66b9653d2d6cf8901c7803b4cd6
[]
no_license
daviewang/src
196e484ba2bc8b0ed398713c51b8272c36223a71
1bc0db1ed04179bbdff18e31274b7489c6669a03
refs/heads/master
2021-01-19T01:22:05.072309
2016-10-21T23:29:08
2016-10-21T23:29:08
60,808,595
0
0
null
null
null
null
UTF-8
Java
false
false
589
java
public class O021MergeTwoSortedLists { class ListNode { int val; ListNode next; ListNode(int x) {val = x;} } public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode dummy = new ListNode(0); ListNode mergeHead = dummy; while (l1 != null && l2 != null) { if (l1.val < l2.val) { mergeHead.next = l1; l1 = l1.next; mergeHead = mergeHead.next; } else { mergeHead.next = l2; l2 = l2.next; mergeHead = mergeHead.next; } } if (l1 == null) { mergeHead.next = l2; } else { mergeHead.next = l1; } return dummy.next; } }
1f665a41f21ac37cf049ca4af17f1752deabc1cc
5b0d51c9e9154d16c0b32252fd142b68964e49dd
/src/datastructure/Fig01_04.java
2e13189261cf9f825800ec7ff3c67677254df1ac
[]
no_license
kiragirl/test
8b2eb67e36a4adb457487d5e366da7c7343530d2
30baff7f45eff3fbc43a72cfa411d2a41cfd381c
refs/heads/master
2021-05-10T10:47:22.811815
2019-07-04T01:46:03
2019-07-04T01:46:03
118,392,839
0
0
null
null
null
null
UTF-8
Java
false
false
421
java
package datastructure; public class Fig01_04 { public static void printDigit( int n ) { System.out.print( n ); } public static void printOut( int n ) /* Print nonnegative n */ { if( n >= 10 ) printOut( n / 10 ); printDigit( n % 10 ); } public static void main( String [ ] args ) { printOut( 1369 ); System.out.println( ); } }
1e543523721d2d225eb3ccf340d9c398090f594b
c2c848c08c53314311cd5621c355409cfa44ada1
/user-service/user-api/src/main/java/com/user/IUserCoreService.java
e365bcbc94a02e5bb5f12ae34002b40abff87732
[]
no_license
sunyk/sunyk
2487f4733c8c9124f4c912c6e037190989a5fe55
89c180fde5be1b73e82306a73512745ec5686882
refs/heads/master
2020-03-19T04:04:37.016353
2018-10-29T16:32:00
2018-10-29T16:32:00
135,792,759
0
0
null
null
null
null
UTF-8
Java
false
false
173
java
package com.user; /** * Create by sunyang on 2018/6/30 20:32 * For me:One handred lines of code every day,make myself stronger. */ public interface IUserCoreService { }
558db1d341a8fa8af4588d30e8f3361ce08d3a82
dcc372bed2a9c33b5c2d136c16884ba0e38a5bb7
/EclipseDP/Interpreter/Robot/com/interpreter/robot/AndNode.java
bfc1dd3aed4f7004d18b8a8f79fb0553d063f043
[]
no_license
icodeu/RepositoryOnMac
a8c9826d549c51536f5e2c6d3d2fba6728e16572
ca67641d6f299103d5302539617769215910e48b
refs/heads/master
2020-05-13T03:40:55.761727
2015-04-23T01:55:48
2015-04-23T01:55:48
33,222,511
0
0
null
null
null
null
UTF-8
Java
false
false
346
java
package com.interpreter.robot; public class AndNode implements AbstractNode { private AbstractNode left; private AbstractNode right; public AndNode(AbstractNode left, AbstractNode right) { this.left = left; this.right = right; } @Override public String interpret() { return left.interpret() + " 再 " + right.interpret(); } }
21ca715bcc6e15de58ac5e490d2c4d009c96a1ec
3d5518ede5e6bbe794023991fa3040eb652f6d18
/basic/src/main/java/com/jingling/basic/utils/CheckFieldUtils.java
d083908175c36a081fda8b0ed70a53d7381f8507
[]
no_license
xiaoxin68/green-collection
55780605a4e6e8f1ff9edf73c1f194f1a643e6b4
378834aa34bb5dcab840fe271dcd19ab782f617e
refs/heads/master
2022-07-30T21:33:17.633923
2020-05-23T09:24:58
2020-05-23T09:24:58
266,302,746
1
0
null
null
null
null
UTF-8
Java
false
false
3,411
java
package com.jingling.basic.utils; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * Created by final on 17-7-25. */ public class CheckFieldUtils { /** * 检查传入对象的属性field是否为null * <p><如果field为null的数量 超过允许的空值数量,返回false/p> * @param o 受检查对象 * @param emptyCount 允许有emptyCount个field为空 * @return */ public static boolean checkField(Object o,int emptyCount) { emptyCount = (emptyCount < 0) ? 0 : emptyCount;//至少为0 int count = 0; Class clazz = o.getClass(); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { String fieldName = field.getName(); String methodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); // System.out.println(methodName); try { Method getMethod = clazz.getDeclaredMethod(methodName); try { Object obj = getMethod.invoke(o); if (obj == null) { //如果get方法的返回值为空,表示属性不完整 count++; if (count>emptyCount) //如果超过允许的空值数量,返回false return false; } } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } catch (NoSuchMethodException e) { e.printStackTrace(); } } return true; } /** * 检查传入对象是否有leastCount个属性不为空 * @param object * @param leastCount * @return */ public static boolean leastField(Object object, final int leastCount) { if (leastCount <= 0) { return true; } int count = 0; Class clazz = object.getClass(); Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { String fieldName = field.getName(); String methodName = "get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); // System.out.println(methodName); try { Method getMethod = clazz.getDeclaredMethod(methodName); try { Object obj = getMethod.invoke(object); if (obj != null) { // System.out.println(fieldName); //如果get方法的返回值为空,表示属性不完整 count++; if (count >= leastCount) { //如果超过允许的空值数量,返回false return true; } } } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } catch (NoSuchMethodException e) { e.printStackTrace(); } } return false; } }
ba1f69729b667b47842c8cc00608566da5b0bf0a
ea39e205fa5ebad4eff424dccf3f61d210d6ece4
/Rectangle.java
9d26905b232eab978c76beaf4ffbba4dfbbb2271
[]
no_license
adol0214/U10316009_taAssign2_normal
c89408916f95f0740775c18e2f38460174919535
c179250b4839edce0480a518d01929e09a8266b8
refs/heads/master
2016-09-06T09:56:18.774006
2015-05-16T14:24:44
2015-05-16T14:24:44
35,723,465
0
0
null
null
null
null
UTF-8
Java
false
false
284
java
public class Rectangle{ int RectangleLong; int RectangleWidth; Rectangle(){ RectangleLong = 0; RectangleWidth = 0; } int RecArea(int RecLong , int RecWidth){ return RecLong * RecWidth; } int RecPar(int RecLong , int RecWidth){ return (RecLong + RecWidth) * 2; } }
5241b497d0147e782fbbcbb2fa236b2f9528a696
3fa73cc68e4d17159e381ef8fb227b4f72848c3f
/src/test/java/me/sudohippie/throttle/strategy/bucket/StepDownLeakyTokenBucketTest.java
bd47e33946d4431088670dbc1377708b561663b6
[]
no_license
robertmircea/throttle
2cf3853d663fb72aabb402136725a65d30bdb1e9
ad977dcc98124b84ccbc4e7ec7f5e583f476c394
refs/heads/master
2020-12-26T05:01:45.887635
2013-09-27T23:44:03
2013-09-27T23:44:03
17,229,746
1
0
null
null
null
null
UTF-8
Java
false
false
6,535
java
package me.sudohippie.throttle.strategy.bucket; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; import java.util.concurrent.TimeUnit; /** * Raghav Sidhanti * 9/26/13 */ public class StepDownLeakyTokenBucketTest { // test state only // when max tokens is negative @Test(expected = IllegalArgumentException.class) public void testWhenMaxTokensIsNegative() throws Exception { StepDownLeakyTokenBucket bucket = new StepDownLeakyTokenBucket(-1, REFILL_INTERVAL, TimeUnit.MILLISECONDS, STEP_TOKENS, STEP_INTERVAL, TimeUnit.MILLISECONDS); } // when refill interval is negative @Test(expected = IllegalArgumentException.class ) public void testWhenRefillIntervalIsNegative() throws Exception { StepDownLeakyTokenBucket bucket = new StepDownLeakyTokenBucket(MAX_TOKENS, -1, TimeUnit.MILLISECONDS, STEP_TOKENS, STEP_INTERVAL, TimeUnit.MILLISECONDS); } // when step token is negative @Test(expected = IllegalArgumentException.class) public void testWhenStepTokenIsNegative() throws Exception { StepDownLeakyTokenBucket bucket = new StepDownLeakyTokenBucket(MAX_TOKENS, REFILL_INTERVAL, TimeUnit.MILLISECONDS, -1, STEP_INTERVAL, TimeUnit.MILLISECONDS); } // when step interval is negative @Test(expected = IllegalArgumentException.class) public void testWhenStepIntervalIsNegative() throws Exception { StepDownLeakyTokenBucket bucket = new StepDownLeakyTokenBucket(MAX_TOKENS, REFILL_INTERVAL, TimeUnit.MILLISECONDS, STEP_TOKENS, -1, TimeUnit.MILLISECONDS); } @Before public void setUp() throws Exception { bucket = new StepDownLeakyTokenBucket(MAX_TOKENS, REFILL_INTERVAL, TimeUnit.MILLISECONDS, STEP_TOKENS, STEP_INTERVAL, TimeUnit.MILLISECONDS); } // setup state private final long MAX_TOKENS = 10; private final long REFILL_INTERVAL = 5000L; private final long STEP_TOKENS = 2; private final long STEP_INTERVAL = 1000L; private StepDownLeakyTokenBucket bucket; // test behaviour, single threaded // at the beginning, number of tokens should be equal to max @Test public void testTokensEqualsMaxAtFirstStep() throws Exception { assertEquals(MAX_TOKENS, bucket.getCurrentTokenCount()); } // after one whole interval, at the beginning number of tokens should be equal to max @Test public void testTokensEqualsMaxAtTheStartOfNextInterval() throws Exception { Thread.sleep(REFILL_INTERVAL); assertEquals(MAX_TOKENS, bucket.getCurrentTokenCount()); } // throttle max, full bucket at beginning of next interval @Test public void testTokensEqualsMaxAtTheStartOfNextIntervalAfterMaxThrottle() throws Exception { bucket.isThrottled(MAX_TOKENS); Thread.sleep(REFILL_INTERVAL); assertEquals(MAX_TOKENS, bucket.getCurrentTokenCount()); } // throttle max, not throttled at beginning of next interval @Test public void testNotThrottledWhenThrottledToMaxOnceWithInInterval() throws Exception { boolean throttled = bucket.isThrottled(MAX_TOKENS); assertFalse(throttled); } // throttle max, zero tokens till end of interval @Test public void testZeroTokensTillEndOfIntervalAfterThrottleMaxOnce() throws Exception { bucket.isThrottled(MAX_TOKENS); final long SLEEP_TIME = 1000L; for(int i = 1; i < (REFILL_INTERVAL / STEP_INTERVAL); i ++){ Thread.sleep(SLEEP_TIME); assertEquals(0, bucket.getCurrentTokenCount()); } } // throttle max, throttled till end of interval @Test public void testThrottledTillEndOfIntervalAfterThrottleMaxOnce() throws Exception { boolean throttled = bucket.isThrottled(MAX_TOKENS); assertFalse(throttled); for(int i = 1; i < (REFILL_INTERVAL / STEP_INTERVAL); i ++){ Thread.sleep(STEP_INTERVAL); assertTrue(bucket.isThrottled()); } } // sleep at every step interval, tokens must be equal to max - (i*stepTokens) at each interval @Test public void testTokensAtEachStepIntervalIsCorrect() throws Exception { for(int i = 0; i < (REFILL_INTERVAL / STEP_INTERVAL); i ++){ long expectedTokens = MAX_TOKENS - (i * STEP_TOKENS); assertEquals(expectedTokens, bucket.getCurrentTokenCount()); Thread.sleep(STEP_INTERVAL); } } // throttle n = 1 + max - (i * stepTokens), where i is a step. Should be throttled as we keep decreasing throttle n over time @Test public void testThrottledWhenNGreaterThanTokensAtEachStep() throws Exception { for(int i = 0; i < (REFILL_INTERVAL / STEP_INTERVAL); i ++){ long excessTokensForStep = MAX_TOKENS - (i * STEP_TOKENS) + 1; assertTrue(bucket.isThrottled(excessTokensForStep)); Thread.sleep(STEP_INTERVAL); } } // test behaviour, multi threaded // throttle n (n < max/2) each, number of tokens remaining should be max - 2*n @Test public void testTokenCountInMultiThreadedThrottleThread1AndThread2WithInAnInterval() throws Exception { Thread thread1 = new Thread(new Runnable() { @Override public void run() { bucket.isThrottled(); } }); Thread thread2 = new Thread(new Runnable() { @Override public void run() { bucket.isThrottled(); } }); thread1.start(); thread2.start(); thread1.join(); thread2.join(); assertEquals(MAX_TOKENS - 2, bucket.getCurrentTokenCount()); } // throttle t1 n > max, t2 n < max. t1 should be throttled, t2 should not be throttled. @Test public void testMultiThreadedWhenThread1ThrottledAboveMaxAndThread2BelowMax() throws Exception { Thread thread1 = new Thread(new Runnable() { @Override public void run() { boolean throttled = bucket.isThrottled(MAX_TOKENS + 1); assertTrue(throttled); } }); Thread thread2 = new Thread(new Runnable() { @Override public void run() { boolean throttled = bucket.isThrottled(MAX_TOKENS - 1); assertFalse(throttled); } }); thread1.start(); thread2.start(); thread1.join(); thread2.join(); } }
3642f4ec5848f2eadecc5b18586c3ac2f3b08bd8
37775b86e497eb119902ab5376096e2f7812e2b3
/tarea10/src/tarea10/ColaPrioridad.java
e31e64218a56c989c23d101c9fcd01d88dcfcb39
[]
no_license
nicoluv/TareaP1
588ad5741281b9989c73a3b64d19d4064c8c4424
935dd622cd7af875712ddb60d7a266825fd10267
refs/heads/master
2023-03-30T12:24:49.595796
2021-04-09T02:50:38
2021-04-09T02:50:38
329,692,940
0
0
null
null
null
null
UTF-8
Java
false
false
2,311
java
package tarea10; import java.util.GregorianCalendar; /** * * @author Nicol Urena */ public class ColaPrioridad { //INSERT, MAXIMUM, EXTRACT-MAX, INCREASE-KEY /** * * COMPLEJIDADES COMPLEJIDAD DE ESPACIO O(N) -Todo el programa opera bajo un * arreglo de correos, por lo que es O(n) * - COMPLEJIDAD DE TIEMPO -Ver metodos- */ public static int tam = -1; public static Correo[] heap = new Correo[1000]; static void debajo(int i) {//COMPLEJIDAD Tiempo:O(log N) int indiceMax = i; int l = hijoIzq(i); if (l <= tam && heap[l].compareTo(heap[indiceMax]) > heap[indiceMax].compareTo(heap[l])) { indiceMax = l; } int r = hijoDer(i); if (r <= tam && heap[r].compareTo(heap[indiceMax]) > heap[indiceMax].compareTo(heap[r])) { indiceMax = r; } if (i != indiceMax) { cambiar(i, indiceMax); debajo(indiceMax); } } static void increaseKey(int i) {//COMPLEJIDAD Tiempo:O(log N) while (i > 0 && heap[padre(i)].compareTo(heap[i]) < heap[i].compareTo(heap[padre(i)])) { cambiar(padre(i), i); i = padre(i); } } static void insert(Correo c) {//COMPLEJIDAD Tiempo:O(log N) tam = tam + 1; heap[tam] = c; increaseKey(tam); } static Correo extractMax() {//COMPLEJIDAD Tiempo:O(log N) Correo result = heap[0]; heap[0] = heap[tam]; tam = tam - 1; debajo(0); return result; } static Correo maximun() {//COMPLEJIDAD Tiempo:O(1) return heap[0]; } static void cambiar(int i, int j) {//COMPLEJIDAD Tiempo:O(log N) Correo temp = heap[i]; heap[i] = heap[j]; heap[j] = temp; } public static int getTam() {//COMPLEJIDAD Tiempo:O(1) return tam; } public static Correo[] getHeap() {//COMPLEJIDAD Tiempo:O(1) return heap; } static int padre(int i) {//COMPLEJIDAD Tiempo:O(1) return (i - 1) / 2; } static int hijoIzq(int i) {//COMPLEJIDAD Tiempo:O(1) return ((2 * i) + 1); } static int hijoDer(int i) {//COMPLEJIDAD Tiempo:O(1) return ((2 * i) + 2); } }
04358771d789aa27a8c2d248b10b077d066cf436
9ab5bdb918b886f1f2d09d81efb63ff83a86bfb0
/coordinator/src/main/java/com/jdt/fedlearn/coordinator/entity/train/StartValues.java
81b4ec8ee7e371067b3c030e70c3140d87b1b404
[ "Apache-2.0" ]
permissive
BestJex/fedlearn
75a795ec51c4a37af34886c551874df419da3a9c
15395f77ac3ddd983ae3affb1c1a9367287cc125
refs/heads/master
2023-06-17T01:27:36.143351
2021-07-19T10:43:09
2021-07-19T10:43:09
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,345
java
/* Copyright 2020 The FedLearn Authors. All Rights Reserved. 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.jdt.fedlearn.coordinator.entity.train; import com.jdt.fedlearn.core.entity.ClientInfo; import com.jdt.fedlearn.core.entity.Message; import com.jdt.fedlearn.core.entity.feature.Features; import com.jdt.fedlearn.core.type.AlgorithmType; import com.jdt.fedlearn.core.psi.MatchResult; import java.util.List; /** * <p>任务训练中的参数</p> * <p>包含TaskID,数据集信息,超参数,算法类型,客户端信息,id对齐信息,特征对齐信息</p> * * @author lijingxi */ public class StartValues implements Message { /** * 任务id */ private String taskId; /** * 超参数,与算法对应 */ private List<SingleParameter> parameter; /** * 枚举类型的算法,与算法类对应 */ private AlgorithmType supportedAlgorithm; /** * 客户端信息 */ private List<ClientInfo> clientInfos; /** * 特征对齐信息,与clientInfo 排序一一对应 */ private List<Features> feature; /** * 数据集,与clientInfo 排序一一对应 */ private List<String> dataset; /** * id对齐信息 */ private MatchResult idMap; public StartValues() { } public StartValues(String taskId, List<ClientInfo> clientInfos, List<Features> feature, MatchResult idMap, List<String> dataset) { this.taskId = taskId; this.clientInfos = clientInfos; this.feature = feature; this.idMap = idMap; this.dataset = dataset; } public String getTaskId() { return this.taskId; } public List<SingleParameter> getParameter() { return this.parameter; } public AlgorithmType getSupportedAlgorithm() { return supportedAlgorithm; } public List<ClientInfo> getClientInfos() { return this.clientInfos; } public List<Features> getFeature() { return this.feature; } public void setSupportedAlgorithm(AlgorithmType supportedAlgorithm) { this.supportedAlgorithm = supportedAlgorithm; } public List<String> getDataset() { return dataset; } public void setParameter(List<SingleParameter> parameter) { this.parameter = parameter; } public MatchResult getIdMap() { return this.idMap; } @Override public String toString() { return "StartValues{" + "taskId='" + taskId + '\'' + ", dataset='" + dataset + '\'' + ", parameter=" + parameter + ", supportedAlgorithm=" + supportedAlgorithm + ", clientInfos=" + clientInfos + ", feature=" + feature + ", idMap=" + idMap + '}'; } }
32c27c9b2893b1b484f5144bdd65f74b39e38ff0
5f3ba2152c5276faaed1797b5ffff374319bc976
/agui_framework/src/main/java/agui/support/v4/util/SimpleArrayMap.java
851987e74d660b761d907e5f0d35729709bf75bd
[ "MIT" ]
permissive
thahn0720/agui_framework
11ce1421b9421c898ba14bbc0ad819c9e3e6a7a8
b08fdbf1e2c1d4533b830c401aa8fcaa0bd86e86
refs/heads/master
2016-09-08T05:04:14.480343
2015-04-05T16:23:46
2015-04-05T16:23:46
30,444,610
3
0
null
null
null
null
UTF-8
Java
false
false
20,417
java
/* * Copyright (C) 2013 The Android Open Source Project * * 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 agui.support.v4.util; import java.util.Map; import thahn.java.agui.utils.Log; /** * Base implementation of {@link ArrayMap} that doesn't include any standard Java * container API interoperability. These features are generally heavier-weight ways * to interact with the container, so discouraged, but they can be useful to make it * easier to use as a drop-in replacement for HashMap. If you don't need them, this * class can be preferrable since it doesn't bring in any of the implementation of those * APIs, allowing that code to be stripped by ProGuard. */ public class SimpleArrayMap<K, V> { private static final boolean DEBUG = false; private static final String TAG = "ArrayMap"; /** * The minimum amount by which the capacity of a ArrayMap will increase. * This is tuned to be relatively space-efficient. */ private static final int BASE_SIZE = 4; /** * Maximum number of entries to have in array caches. */ private static final int CACHE_SIZE = 10; /** * Caches of small array objects to avoid spamming garbage. The cache * Object[] variable is a pointer to a linked list of array objects. * The first entry in the array is a pointer to the next array in the * list; the second entry is a pointer to the int[] hash code array for it. */ static Object[] mBaseCache; static int mBaseCacheSize; static Object[] mTwiceBaseCache; static int mTwiceBaseCacheSize; int[] mHashes; Object[] mArray; int mSize; int indexOf(Object key, int hash) { final int N = mSize; // Important fast case: if nothing is in here, nothing to look for. if (N == 0) { return ~0; } int index = ContainerHelpers.binarySearch(mHashes, N, hash); // If the hash code wasn't found, then we have no entry for this key. if (index < 0) { return index; } // If the key at the returned index matches, that's what we want. if (key.equals(mArray[index<<1])) { return index; } // Search for a matching key after the index. int end; for (end = index + 1; end < N && mHashes[end] == hash; end++) { if (key.equals(mArray[end << 1])) return end; } // Search for a matching key before the index. for (int i = index - 1; i >= 0 && mHashes[i] == hash; i--) { if (key.equals(mArray[i << 1])) return i; } // Key not found -- return negative value indicating where a // new entry for this key should go. We use the end of the // hash chain to reduce the number of array entries that will // need to be copied when inserting. return ~end; } int indexOfNull() { final int N = mSize; // Important fast case: if nothing is in here, nothing to look for. if (N == 0) { return ~0; } int index = ContainerHelpers.binarySearch(mHashes, N, 0); // If the hash code wasn't found, then we have no entry for this key. if (index < 0) { return index; } // If the key at the returned index matches, that's what we want. if (null == mArray[index<<1]) { return index; } // Search for a matching key after the index. int end; for (end = index + 1; end < N && mHashes[end] == 0; end++) { if (null == mArray[end << 1]) return end; } // Search for a matching key before the index. for (int i = index - 1; i >= 0 && mHashes[i] == 0; i--) { if (null == mArray[i << 1]) return i; } // Key not found -- return negative value indicating where a // new entry for this key should go. We use the end of the // hash chain to reduce the number of array entries that will // need to be copied when inserting. return ~end; } private void allocArrays(final int size) { if (size == (BASE_SIZE*2)) { synchronized (ArrayMap.class) { if (mTwiceBaseCache != null) { final Object[] array = mTwiceBaseCache; mArray = array; mTwiceBaseCache = (Object[])array[0]; mHashes = (int[])array[1]; array[0] = array[1] = null; mTwiceBaseCacheSize--; if (DEBUG) Log.d(TAG, "Retrieving 2x cache " + mHashes + " now have " + mTwiceBaseCacheSize + " entries"); return; } } } else if (size == BASE_SIZE) { synchronized (ArrayMap.class) { if (mBaseCache != null) { final Object[] array = mBaseCache; mArray = array; mBaseCache = (Object[])array[0]; mHashes = (int[])array[1]; array[0] = array[1] = null; mBaseCacheSize--; if (DEBUG) Log.d(TAG, "Retrieving 1x cache " + mHashes + " now have " + mBaseCacheSize + " entries"); return; } } } mHashes = new int[size]; mArray = new Object[size<<1]; } private static void freeArrays(final int[] hashes, final Object[] array, final int size) { if (hashes.length == (BASE_SIZE*2)) { synchronized (ArrayMap.class) { if (mTwiceBaseCacheSize < CACHE_SIZE) { array[0] = mTwiceBaseCache; array[1] = hashes; for (int i=(size<<1)-1; i>=2; i--) { array[i] = null; } mTwiceBaseCache = array; mTwiceBaseCacheSize++; if (DEBUG) Log.d(TAG, "Storing 2x cache " + array + " now have " + mTwiceBaseCacheSize + " entries"); } } } else if (hashes.length == BASE_SIZE) { synchronized (ArrayMap.class) { if (mBaseCacheSize < CACHE_SIZE) { array[0] = mBaseCache; array[1] = hashes; for (int i=(size<<1)-1; i>=2; i--) { array[i] = null; } mBaseCache = array; mBaseCacheSize++; if (DEBUG) Log.d(TAG, "Storing 1x cache " + array + " now have " + mBaseCacheSize + " entries"); } } } } /** * Create a new empty ArrayMap. The default capacity of an array map is 0, and * will grow once items are added to it. */ public SimpleArrayMap() { mHashes = ContainerHelpers.EMPTY_INTS; mArray = ContainerHelpers.EMPTY_OBJECTS; mSize = 0; } /** * Create a new ArrayMap with a given initial capacity. */ public SimpleArrayMap(int capacity) { if (capacity == 0) { mHashes = ContainerHelpers.EMPTY_INTS; mArray = ContainerHelpers.EMPTY_OBJECTS; } else { allocArrays(capacity); } mSize = 0; } /** * Create a new ArrayMap with the mappings from the given ArrayMap. */ public SimpleArrayMap(SimpleArrayMap map) { this(); if (map != null) { putAll(map); } } /** * Make the array map empty. All storage is released. */ public void clear() { if (mSize != 0) { freeArrays(mHashes, mArray, mSize); mHashes = ContainerHelpers.EMPTY_INTS; mArray = ContainerHelpers.EMPTY_OBJECTS; mSize = 0; } } /** * Ensure the array map can hold at least <var>minimumCapacity</var> * items. */ public void ensureCapacity(int minimumCapacity) { if (mHashes.length < minimumCapacity) { final int[] ohashes = mHashes; final Object[] oarray = mArray; allocArrays(minimumCapacity); if (mSize > 0) { System.arraycopy(ohashes, 0, mHashes, 0, mSize); System.arraycopy(oarray, 0, mArray, 0, mSize<<1); } freeArrays(ohashes, oarray, mSize); } } /** * Check whether a key exists in the array. * * @param key The key to search for. * @return Returns true if the key exists, else false. */ public boolean containsKey(Object key) { return key == null ? (indexOfNull() >= 0) : (indexOf(key, key.hashCode()) >= 0); } int indexOfValue(Object value) { final int N = mSize*2; final Object[] array = mArray; if (value == null) { for (int i=1; i<N; i+=2) { if (array[i] == null) { return i>>1; } } } else { for (int i=1; i<N; i+=2) { if (value.equals(array[i])) { return i>>1; } } } return -1; } /** * Check whether a value exists in the array. This requires a linear search * through the entire array. * * @param value The value to search for. * @return Returns true if the value exists, else false. */ public boolean containsValue(Object value) { return indexOfValue(value) >= 0; } /** * Retrieve a value from the array. * @param key The key of the value to retrieve. * @return Returns the value associated with the given key, * or null if there is no such key. */ public V get(Object key) { final int index = key == null ? indexOfNull() : indexOf(key, key.hashCode()); return index >= 0 ? (V)mArray[(index<<1)+1] : null; } /** * Return the key at the given index in the array. * @param index The desired index, must be between 0 and {@link #size()}-1. * @return Returns the key stored at the given index. */ public K keyAt(int index) { return (K)mArray[index << 1]; } /** * Return the value at the given index in the array. * @param index The desired index, must be between 0 and {@link #size()}-1. * @return Returns the value stored at the given index. */ public V valueAt(int index) { return (V)mArray[(index << 1) + 1]; } /** * Set the value at a given index in the array. * @param index The desired index, must be between 0 and {@link #size()}-1. * @param value The new value to store at this index. * @return Returns the previous value at the given index. */ public V setValueAt(int index, V value) { index = (index << 1) + 1; V old = (V)mArray[index]; mArray[index] = value; return old; } /** * Return true if the array map contains no items. */ public boolean isEmpty() { return mSize <= 0; } /** * Add a new value to the array map. * @param key The key under which to store the value. <b>Must not be null.</b> If * this key already exists in the array, its value will be replaced. * @param value The value to store for the given key. * @return Returns the old value that was stored for the given key, or null if there * was no such key. */ public V put(K key, V value) { final int hash; int index; if (key == null) { hash = 0; index = indexOfNull(); } else { hash = key.hashCode(); index = indexOf(key, hash); } if (index >= 0) { index = (index<<1) + 1; final V old = (V)mArray[index]; mArray[index] = value; return old; } index = ~index; if (mSize >= mHashes.length) { final int n = mSize >= (BASE_SIZE*2) ? (mSize+(mSize>>1)) : (mSize >= BASE_SIZE ? (BASE_SIZE*2) : BASE_SIZE); if (DEBUG) Log.d(TAG, "put: grow from " + mHashes.length + " to " + n); final int[] ohashes = mHashes; final Object[] oarray = mArray; allocArrays(n); if (mHashes.length > 0) { if (DEBUG) Log.d(TAG, "put: copy 0-" + mSize + " to 0"); System.arraycopy(ohashes, 0, mHashes, 0, ohashes.length); System.arraycopy(oarray, 0, mArray, 0, oarray.length); } freeArrays(ohashes, oarray, mSize); } if (index < mSize) { if (DEBUG) Log.d(TAG, "put: move " + index + "-" + (mSize-index) + " to " + (index+1)); System.arraycopy(mHashes, index, mHashes, index + 1, mSize - index); System.arraycopy(mArray, index << 1, mArray, (index + 1) << 1, (mSize - index) << 1); } mHashes[index] = hash; mArray[index<<1] = key; mArray[(index<<1)+1] = value; mSize++; return null; } /** * Perform a {@link #put(Object, Object)} of all key/value pairs in <var>array</var> * @param array The array whose contents are to be retrieved. */ public void putAll(SimpleArrayMap<? extends K, ? extends V> array) { final int N = array.mSize; ensureCapacity(mSize + N); if (mSize == 0) { if (N > 0) { System.arraycopy(array.mHashes, 0, mHashes, 0, N); System.arraycopy(array.mArray, 0, mArray, 0, N<<1); mSize = N; } } else { for (int i=0; i<N; i++) { put(array.keyAt(i), array.valueAt(i)); } } } /** * Remove an existing key from the array map. * @param key The key of the mapping to remove. * @return Returns the value that was stored under the key, or null if there * was no such key. */ public V remove(Object key) { int index = key == null ? indexOfNull() : indexOf(key, key.hashCode()); if (index >= 0) { return removeAt(index); } return null; } /** * Remove the key/value mapping at the given index. * @param index The desired index, must be between 0 and {@link #size()}-1. * @return Returns the value that was stored at this index. */ public V removeAt(int index) { final Object old = mArray[(index << 1) + 1]; if (mSize <= 1) { // Now empty. if (DEBUG) Log.d(TAG, "remove: shrink from " + mHashes.length + " to 0"); freeArrays(mHashes, mArray, mSize); mHashes = ContainerHelpers.EMPTY_INTS; mArray = ContainerHelpers.EMPTY_OBJECTS; mSize = 0; } else { if (mHashes.length > (BASE_SIZE*2) && mSize < mHashes.length/3) { // Shrunk enough to reduce size of arrays. We don't allow it to // shrink smaller than (BASE_SIZE*2) to avoid flapping between // that and BASE_SIZE. final int n = mSize > (BASE_SIZE*2) ? (mSize + (mSize>>1)) : (BASE_SIZE*2); if (DEBUG) Log.d(TAG, "remove: shrink from " + mHashes.length + " to " + n); final int[] ohashes = mHashes; final Object[] oarray = mArray; allocArrays(n); mSize--; if (index > 0) { if (DEBUG) Log.d(TAG, "remove: copy from 0-" + index + " to 0"); System.arraycopy(ohashes, 0, mHashes, 0, index); System.arraycopy(oarray, 0, mArray, 0, index << 1); } if (index < mSize) { if (DEBUG) Log.d(TAG, "remove: copy from " + (index+1) + "-" + mSize + " to " + index); System.arraycopy(ohashes, index + 1, mHashes, index, mSize - index); System.arraycopy(oarray, (index + 1) << 1, mArray, index << 1, (mSize - index) << 1); } } else { mSize--; if (index < mSize) { if (DEBUG) Log.d(TAG, "remove: move " + (index+1) + "-" + mSize + " to " + index); System.arraycopy(mHashes, index + 1, mHashes, index, mSize - index); System.arraycopy(mArray, (index + 1) << 1, mArray, index << 1, (mSize - index) << 1); } mArray[mSize << 1] = null; mArray[(mSize << 1) + 1] = null; } } return (V)old; } /** * Return the number of items in this array map. */ public int size() { return mSize; } /** * {@inheritDoc} * * <p>This implementation returns false if the object is not a map, or * if the maps have different sizes. Otherwise, for each key in this map, * values of both maps are compared. If the values for any key are not * equal, the method returns false, otherwise it returns true. */ @Override public boolean equals(Object object) { if (this == object) { return true; } if (object instanceof Map) { Map<?, ?> map = (Map<?, ?>) object; if (size() != map.size()) { return false; } try { for (int i=0; i<mSize; i++) { K key = keyAt(i); V mine = valueAt(i); Object theirs = map.get(key); if (mine == null) { if (theirs != null || !map.containsKey(key)) { return false; } } else if (!mine.equals(theirs)) { return false; } } } catch (NullPointerException ignored) { return false; } catch (ClassCastException ignored) { return false; } return true; } return false; } /** * {@inheritDoc} */ @Override public int hashCode() { final int[] hashes = mHashes; final Object[] array = mArray; int result = 0; for (int i = 0, v = 1, s = mSize; i < s; i++, v+=2) { Object value = array[v]; result += hashes[i] ^ (value == null ? 0 : value.hashCode()); } return result; } /** * {@inheritDoc} * * <p>This implementation composes a string by iterating over its mappings. If * this map contains itself as a key or a value, the string "(this Map)" * will appear in its place. */ @Override public String toString() { if (isEmpty()) { return "{}"; } StringBuilder buffer = new StringBuilder(mSize * 28); buffer.append('{'); for (int i=0; i<mSize; i++) { if (i > 0) { buffer.append(", "); } Object key = keyAt(i); if (key != this) { buffer.append(key); } else { buffer.append("(this Map)"); } buffer.append('='); Object value = valueAt(i); if (value != this) { buffer.append(value); } else { buffer.append("(this Map)"); } } buffer.append('}'); return buffer.toString(); } }
7da74065dc79dd5f99d7f89fc8ef7d3d5d9f3683
3ddcca4c638ed285d96515ba94cf091fc60a2826
/Mage.Sets/src/mage/sets/returntoravnica/JaceArchitectOfThought.java
644c71e4481f269ae8279d0762125516ad5738bc
[]
no_license
xdaft/mage
5c8b6aa140ea25b99be2e786e22d5d16e9a58f7e
2803ffe5397212cac892f62a8b03a95dc75ca765
refs/heads/master
2021-01-24T03:43:42.164479
2013-01-06T11:58:38
2013-01-06T11:58:38
null
0
0
null
null
null
null
UTF-8
Java
false
false
15,878
java
/* * Copyright 2010 BetaSteward_at_googlemail.com. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY BetaSteward_at_googlemail.com ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL BetaSteward_at_googlemail.com OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those of the * authors and should not be interpreted as representing official policies, either expressed * or implied, of BetaSteward_at_googlemail.com. */ package mage.sets.returntoravnica; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.UUID; import mage.Constants; import mage.Constants.CardType; import mage.Constants.Duration; import mage.Constants.Outcome; import mage.Constants.Rarity; import mage.Constants.Zone; import mage.abilities.Ability; import mage.abilities.LoyaltyAbility; import mage.abilities.TriggeredAbilityImpl; import mage.abilities.common.EntersBattlefieldAbility; import mage.abilities.effects.ContinuousEffectImpl; import mage.abilities.effects.Effect; import mage.abilities.effects.OneShotEffect; import mage.abilities.effects.common.continious.BoostTargetEffect; import mage.abilities.effects.common.counter.AddCountersSourceEffect; import mage.cards.Card; import mage.cards.CardImpl; import mage.cards.Cards; import mage.cards.CardsImpl; import mage.counters.CounterType; import mage.filter.FilterCard; import mage.filter.common.FilterNonlandCard; import mage.game.ExileZone; import mage.game.Game; import mage.game.events.GameEvent; import mage.game.permanent.Permanent; import mage.game.turn.Step; import mage.players.Player; import mage.target.TargetCard; import mage.target.common.TargetCardInExile; import mage.target.common.TargetCardInLibrary; import mage.target.common.TargetOpponent; import mage.target.targetpointer.FixedTarget; /** * * * @author LevelX2 */ public class JaceArchitectOfThought extends CardImpl<JaceArchitectOfThought> { public JaceArchitectOfThought(UUID ownerId) { super(ownerId, 44, "Jace, Architect of Thought", Rarity.MYTHIC, new CardType[]{CardType.PLANESWALKER}, "{2}{U}{U}"); this.expansionSetCode = "RTR"; this.subtype.add("Jace"); this.color.setBlue(true); this.addAbility(new EntersBattlefieldAbility(new AddCountersSourceEffect(CounterType.LOYALTY.createInstance(4)), false)); // +1: Until your next turn, whenever a creature an opponent controls attacks, it gets -1/-0 until end of turn. this.addAbility(new LoyaltyAbility(new JaceArchitectOfThoughtGainAbilityEffect(new JaceArchitectOfThoughtTriggeredAbility()),1)); // -2: Reveal the top three cards of your library. An opponent separates those cards into two piles. Put one pile into your hand and the other on the bottom of your library in any order. this.addAbility(new LoyaltyAbility(new JaceArchitectOfThoughtEffect2(), -2)); // -8: For each player, search that player's library for a nonland card and exile it, then that player shuffles his or her library. You may cast those cards without paying their mana costs. this.addAbility(new LoyaltyAbility(new JaceArchitectOfThoughtEffect3(), -8)); } public JaceArchitectOfThought(final JaceArchitectOfThought card) { super(card); } @Override public JaceArchitectOfThought copy() { return new JaceArchitectOfThought(this); } } class JaceArchitectOfThoughtGainAbilityEffect extends ContinuousEffectImpl<JaceArchitectOfThoughtGainAbilityEffect> { protected Ability ability; public JaceArchitectOfThoughtGainAbilityEffect(Ability ability) { super(Duration.Custom, Constants.Layer.AbilityAddingRemovingEffects_6, Constants.SubLayer.NA, Constants.Outcome.AddAbility); this.ability = ability; staticText = "Until your next turn, whenever a creature an opponent controls attacks, it gets -1/-0 until end of turn"; } public JaceArchitectOfThoughtGainAbilityEffect(final JaceArchitectOfThoughtGainAbilityEffect effect) { super(effect); this.ability = effect.ability.copy(); } @Override public JaceArchitectOfThoughtGainAbilityEffect copy() { return new JaceArchitectOfThoughtGainAbilityEffect(this); } @Override public boolean apply(Game game, Ability source) { Permanent permanent = game.getPermanent(source.getSourceId()); if (permanent != null) { permanent.addAbility(ability, game); return true; } return false; } @Override public boolean isInactive(Ability source, Game game) { if (game.getPhase().getStep().getType() == Constants.PhaseStep.UNTAP && game.getStep().getStepPart() == Step.StepPart.PRE) { if (game.getActivePlayerId().equals(source.getControllerId())) { return true; } } return false; } } class JaceArchitectOfThoughtTriggeredAbility extends TriggeredAbilityImpl<JaceArchitectOfThoughtTriggeredAbility> { public JaceArchitectOfThoughtTriggeredAbility() { super(Constants.Zone.BATTLEFIELD, new JaceArchitectOfThoughtEffectUnboostEffect(-1,0, Duration.EndOfTurn)); } public JaceArchitectOfThoughtTriggeredAbility(final JaceArchitectOfThoughtTriggeredAbility ability) { super(ability); } @Override public JaceArchitectOfThoughtTriggeredAbility copy() { return new JaceArchitectOfThoughtTriggeredAbility(this); } @Override public boolean checkTrigger(GameEvent event, Game game) { if (event.getType() == GameEvent.EventType.ATTACKER_DECLARED) { Permanent attacker = game.getPermanent(event.getSourceId()); Player defender = game.getPlayer(event.getTargetId()); Player you = game.getPlayer(controllerId); if (attacker.getControllerId() != you.getId() && defender == you) { for (Effect effect : getEffects()) { effect.setTargetPointer(new FixedTarget(attacker.getId())); } return true; } } return false; } @Override public String getRule() { return "Until your next turn, whenever a creature an opponent controls attacks, it gets -1/-0 until end of turn."; } } /* * effect only applies if creature continues to attack (if it's left the combat, it#s no longer attacking */ class JaceArchitectOfThoughtEffectUnboostEffect extends BoostTargetEffect { public JaceArchitectOfThoughtEffectUnboostEffect(int power, int toughness, Duration duration) { super(power, toughness, duration); } public JaceArchitectOfThoughtEffectUnboostEffect (final JaceArchitectOfThoughtEffectUnboostEffect effect) { super(effect); } @Override public JaceArchitectOfThoughtEffectUnboostEffect copy() { return new JaceArchitectOfThoughtEffectUnboostEffect(this); } @Override public boolean apply(Game game, Ability source) { for (UUID permanentId : targetPointer.getTargets(game, source)) { Permanent target = (Permanent) game.getPermanent(permanentId); if (target != null && target.isAttacking()) { return super.apply(game, source); } } return false; } } class JaceArchitectOfThoughtEffect2 extends OneShotEffect<JaceArchitectOfThoughtEffect2> { public JaceArchitectOfThoughtEffect2() { super(Constants.Outcome.DrawCard); this.staticText = "Reveal the top three cards of your library. An opponent separates those cards into two piles. Put one pile into your hand and the other on the bottom of your library in any order"; } public JaceArchitectOfThoughtEffect2(final JaceArchitectOfThoughtEffect2 effect) { super(effect); } @Override public JaceArchitectOfThoughtEffect2 copy() { return new JaceArchitectOfThoughtEffect2(this); } @Override public boolean apply(Game game, Ability source) { Player player = game.getPlayer(source.getControllerId()); if (player == null) { return false; } Cards cards = new CardsImpl(Zone.PICK); int count = Math.min(player.getLibrary().size(), 3); for (int i = 0; i < count; i++) { Card card = player.getLibrary().removeFromTop(game); if (card != null) { cards.add(card); game.setZone(card.getId(), Zone.PICK); } } player.revealCards("Jace, Architect of Thought", cards, game); Set<UUID> opponents = game.getOpponents(source.getControllerId()); if (!opponents.isEmpty()) { Player opponent = null; if (opponents.size() > 1) { TargetOpponent targetOpponent = new TargetOpponent(); if (player.chooseTarget(Outcome.Neutral, targetOpponent, source, game)) { opponent = game.getPlayer(targetOpponent.getFirstTarget()); } } if (opponent == null) { opponent = game.getPlayer(opponents.iterator().next()); } TargetCard target = new TargetCard(0, cards.size(), Zone.PICK, new FilterCard("cards to put in the first pile")); Cards pile1 = new CardsImpl(); if (opponent.choose(Constants.Outcome.Neutral, cards, target, game)) { List<UUID> targets = target.getTargets(); for (UUID targetId : targets) { Card card = cards.get(targetId, game); if (card != null) { pile1.add(card); cards.remove(card); } } } player.revealCards("Pile 1 (Jace, Architect of Thought)", pile1, game); player.revealCards("Pile 2 (Jace, Architect of Thought)", cards, game); Cards cardsToHand = cards; Cards cardsToLibrary = pile1; List<Card> cardPile1 = new ArrayList<Card>(); List<Card> cardPile2 = new ArrayList<Card>(); for (UUID cardId: pile1) { cardPile1.add(game.getCard(cardId)); } for (UUID cardId: cards) { cardPile2.add(game.getCard(cardId)); } boolean pileChoice = player.choosePile(Outcome.Neutral, "Choose a pile to to put into your hand.", cardPile1, cardPile2, game); if (pileChoice){ cardsToHand = pile1; cardsToLibrary = cards; } game.informPlayers(player.getName() +" chose pile" + (pileChoice?"1":"2")); for (UUID cardUuid : cardsToHand) { Card card = cardsToHand.get(cardUuid, game); if (card != null) { card.moveToZone(Zone.HAND, source.getId(), game, false); } } TargetCard targetCard = new TargetCard(Zone.PICK, new FilterCard("card to put on the bottom of your library")); targetCard.setRequired(true); while (cardsToLibrary.size() > 1) { player.choose(Constants.Outcome.Neutral, cardsToLibrary, targetCard, game); Card card = cardsToLibrary.get(targetCard.getFirstTarget(), game); if (card != null) { cardsToLibrary.remove(card); card.moveToZone(Zone.LIBRARY, source.getId(), game, false); } target.clearChosen(); } if (cardsToLibrary.size() == 1) { Card card = cardsToLibrary.get(cardsToLibrary.iterator().next(), game); card.moveToZone(Zone.LIBRARY, source.getId(), game, false); } return true; } return false; } } class JaceArchitectOfThoughtEffect3 extends OneShotEffect<JaceArchitectOfThoughtEffect3> { public JaceArchitectOfThoughtEffect3() { super(Outcome.PlayForFree); this.staticText = "For each player, search that player's library for a nonland card and exile it, then that player shuffles his or her library. You may cast those cards without paying their mana costs"; } public JaceArchitectOfThoughtEffect3(final JaceArchitectOfThoughtEffect3 effect) { super(effect); } @Override public JaceArchitectOfThoughtEffect3 copy() { return new JaceArchitectOfThoughtEffect3(this); } @Override public boolean apply(Game game, Ability source) { Player controller = game.getPlayer(source.getControllerId()); if (controller == null) { return false; } for (UUID playerId : controller.getInRange()) { Cards playerLibrary = new CardsImpl(); Player player = game.getPlayer(playerId); playerLibrary.addAll(player.getLibrary().getCardList()); TargetCardInLibrary target = new TargetCardInLibrary(new FilterNonlandCard()); if (controller.choose(Constants.Outcome.Benefit, playerLibrary, target, game)) { UUID targetId = target.getFirstTarget(); Card card = player.getLibrary().remove(targetId, game); if (card != null) { card.moveToExile(source.getSourceId(), "Jace, Architect of Thought", source.getSourceId(), game); } } player.shuffleLibrary(game); } ExileZone JaceExileZone = game.getExile().getExileZone(source.getSourceId()); FilterCard filter = new FilterCard("card to cast without mana costs"); TargetCardInExile target = new TargetCardInExile(filter, source.getSourceId()); while (JaceExileZone.count(filter, game) > 0 && controller.choose(Outcome.PlayForFree, JaceExileZone, target, game)) { Card card = game.getCard(target.getFirstTarget()); if (card != null) { if (controller.cast(card.getSpellAbility(), game, true)) { game.getExile().removeCard(card, game); } } target.clearChosen(); } return true; } }
59d65d9ba6089822aa137837d5b7718e8b572be9
fd271eeedde211fa9e321dc63e0b768d773a573b
/wiked/com.xpn.xwiki.wiked/src/main/java/com/xpn/xwiki/wiked/internal/ui/DefaultPerspective.java
5ac112e858e8a9f6c729fd855bdc8c75b157b1ed
[]
no_license
xwiki-attic/retired
03bbed6eeb7d00dbf2d3c3078a83253ab84f31da
cfeae5e0446368b045c8e0498c0949d4a6dda1cd
refs/heads/master
2021-05-29T10:34:50.969303
2015-05-27T15:01:16
2015-05-27T15:01:16
2,192,499
0
1
null
null
null
null
UTF-8
Java
false
false
1,072
java
package com.xpn.xwiki.wiked.internal.ui; import org.eclipse.ui.IFolderLayout; import org.eclipse.ui.IPageLayout; import org.eclipse.ui.IPerspectiveFactory; /** * Perspective with erpository view, property sheet and problems view. * @author Psenicka_Ja */ public class DefaultPerspective implements IPerspectiveFactory { public static final String ID = "com.xpn.xwiki.wiked.DefaultPerspective"; public void createInitialLayout(IPageLayout layout) { String editorArea = layout.getEditorArea(); IFolderLayout left = layout.createFolder("left", IPageLayout.LEFT, 0.3f, editorArea); left.addView(RepositoryView.ID); IFolderLayout bottomleft = layout.createFolder("bottom-left", IPageLayout.BOTTOM, 0.5f, "left"); bottomleft.addView(IPageLayout.ID_PROP_SHEET); IFolderLayout bottom = layout.createFolder("bottom", IPageLayout.BOTTOM, 0.6f, editorArea); bottom.addPlaceholder(IPageLayout.ID_TASK_LIST); bottom.addView(IPageLayout.ID_PROBLEM_VIEW); } }
0909efcf3b16a5be77299a7dad8f0801ed0f1f03
83a9fc6c90fa4baa547cb301e66b564d9a9e5212
/src/main/java/com/cn/common/utils/DesUtils.java
952a7dc3130b352774b9afe6f985a34aa2779c2d
[]
no_license
48715564/calculator
3d126280cf010697c4a348568f0c3a71db516638
239381fb99eb2428fffc9ce051997480ab395ed9
refs/heads/master
2020-03-28T20:22:12.942398
2018-09-22T07:25:49
2018-09-22T07:25:49
149,063,218
0
0
null
null
null
null
UTF-8
Java
false
false
4,837
java
package com.cn.common.utils; import javax.crypto.Cipher; import java.security.Key; import java.security.Security; /** DES加密和解密工具,可以对字符串进行加密和解密操作 。 * * @author 刘尧兴 * <p> * 2009-12-5 * </p> */ public class DesUtils { /** 字符串默认键值 */ private static String strDefaultKey = "national"; /** 加密工具 */ private Cipher encryptCipher = null; /** 解密工具 */ private Cipher decryptCipher = null; /** 将byte数组转换为表示16进制值的字符串, 如:byte[]{8,18}转换为:0813, 和public static byte[] hexStr2ByteArr(String strIn) 互为可逆的转换过程 * * @param arrB * 需要转换的byte数组 * @return 转换后的字符串 * @throws Exception * 本方法不处理任何异常,所有异常全部抛出 */ public static String byteArr2HexStr(byte[] arrB) throws Exception { int iLen = arrB.length; // 每个byte用两个字符才能表示,所以字符串的长度是数组长度的两倍 StringBuffer sb = new StringBuffer(iLen * 2); for (int i = 0; i < iLen; i++) { int intTmp = arrB[i]; // 把负数转换为正数 while (intTmp < 0) { intTmp = intTmp + 256; } // 小于0F的数需要在前面补0 if (intTmp < 16) { sb.append("0"); } sb.append(Integer.toString(intTmp, 16)); } return sb.toString(); } /** 将表示16进制值的字符串转换为byte数组, 和public static String byteArr2HexStr(byte[] arrB) 互为可逆的转换过程 * * @param strIn * 需要转换的字符串 * @return 转换后的byte数组 * @throws Exception * 本方法不处理任何异常,所有异常全部抛出 * @author <a href="mailto:[email protected]">LiGuoQing</a> */ public static byte[] hexStr2ByteArr(String strIn) throws Exception { byte[] arrB = strIn.getBytes(); int iLen = arrB.length; // 两个字符表示一个字节,所以字节数组长度是字符串长度除以2 int byteleng = 2; byte[] arrOut = new byte[iLen / byteleng]; for (int i = 0; i < iLen; i = i + byteleng) { String strTmp = new String(arrB, i, byteleng); arrOut[i / 2] = (byte) Integer.parseInt(strTmp, 16); } return arrOut; } /** 默认构造方法,使用默认密钥 * * @throws Exception */ public DesUtils() throws Exception { this(strDefaultKey); } /** 指定密钥构造方法 * * @param strKey * 指定的密钥 * @throws Exception */ public DesUtils(String strKey) throws Exception { Security.addProvider(new com.sun.crypto.provider.SunJCE()); Key key = getKey(strKey.getBytes()); encryptCipher = Cipher.getInstance("DES"); encryptCipher.init(Cipher.ENCRYPT_MODE, key); decryptCipher = Cipher.getInstance("DES"); decryptCipher.init(Cipher.DECRYPT_MODE, key); } /** 加密字节数组 * * @param arrB * 需加密的字节数组 * @return 加密后的字节数组 * @throws Exception */ public byte[] encrypt(byte[] arrB) throws Exception { return encryptCipher.doFinal(arrB); } /** 加密字符串 * * @param strIn * 需加密的字符串 * @return 加密后的字符串 * @throws Exception */ public String encrypt(String strIn) throws Exception { return byteArr2HexStr(encrypt(strIn.getBytes())); } /** 解密字节数组 * * @param arrB * 需解密的字节数组 * @return 解密后的字节数组 * @throws Exception */ public byte[] decrypt(byte[] arrB) throws Exception { return decryptCipher.doFinal(arrB); } /** 解密字符串 * * @param strIn * 需解密的字符串 * @return 解密后的字符串 * @throws Exception */ public String decrypt(String strIn) throws Exception { return new String(decrypt(hexStr2ByteArr(strIn))); } /** 从指定字符串生成密钥,密钥所需的字节数组长度为8位 不足8位时后面补0,超出8位只取前8位 * * @param arrBTmp * 构成该字符串的字节数组 * @return 生成的密钥 * @throws Exception */ private Key getKey(byte[] arrBTmp) throws Exception { // 创建一个空的8位字节数组(默认值为0) byte[] arrB = new byte[8]; // 将原始字节数组转换为8位 for (int i = 0; i < arrBTmp.length && i < arrB.length; i++) { arrB[i] = arrBTmp[i]; } // 生成密钥 Key key = new javax.crypto.spec.SecretKeySpec(arrB, "DES"); return key; } /** main方法 。 * * @author 刘尧兴 * @param args */ public void main(String[] args) { try { String test = "123456"; // 自定义密钥 DesUtils des = new DesUtils("leemenz"); System.out.println(new DesUtils().encrypt(test)); } catch (Exception e) { e.printStackTrace(); } } }
c9f6f53478171f23770e9561c80714f0d33ff920
0c3495f5775393978989560e647be9b3c818e156
/app/src/main/java/com/nuist/mybank/POJO/ResultBean/GetBCResult.java
4536d1a2e717b62c348b19ab3c0c44542f83af57
[]
no_license
sunyunlin199725/MyBank
a202ca57675050a19bb7a7d64f834e45cac29ace
72bdaadd3d1daf241f2c7479601e3b0a60727279
refs/heads/master
2022-10-26T03:38:55.413773
2020-06-08T04:01:42
2020-06-08T04:01:42
270,520,453
0
0
null
null
null
null
UTF-8
Java
false
false
4,530
java
package com.nuist.mybank.POJO.ResultBean; public class GetBCResult { /** * message : 操作成功 * success : true * code : 10000 * data : {"bc_no":"6228480395827245614","bc_type":"1","user_id":100000001,"bank":{"bank_no":"103","bank_name":"中国建设银行","bank_address":"北京市西城区金融大街25号","bank_phone":"95533","bank_email":"[email protected]","bank_pc":"100033"},"bc_money":3636.74,"bc_pwd":"199725"} */ private String message; private boolean success; private int code; private BcBean data; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public boolean isSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public BcBean getData() { return data; } public void setData(BcBean data) { this.data = data; } public static class BcBean { /** * bc_no : 6228480395827245614 * bc_type : 1 * user_id : 100000001 * bank : {"bank_no":"103","bank_name":"中国建设银行","bank_address":"北京市西城区金融大街25号","bank_phone":"95533","bank_email":"[email protected]","bank_pc":"100033"} * bc_money : 3636.74 * bc_pwd : 199725 */ private String bc_no; private String bc_type; private int user_id; private BankBean bank; private double bc_money; private String bc_pwd; public String getBc_no() { return bc_no; } public void setBc_no(String bc_no) { this.bc_no = bc_no; } public String getBc_type() { return bc_type; } public void setBc_type(String bc_type) { this.bc_type = bc_type; } public int getUser_id() { return user_id; } public void setUser_id(int user_id) { this.user_id = user_id; } public BankBean getBank() { return bank; } public void setBank(BankBean bank) { this.bank = bank; } public double getBc_money() { return bc_money; } public void setBc_money(double bc_money) { this.bc_money = bc_money; } public String getBc_pwd() { return bc_pwd; } public void setBc_pwd(String bc_pwd) { this.bc_pwd = bc_pwd; } public static class BankBean { /** * bank_no : 103 * bank_name : 中国建设银行 * bank_address : 北京市西城区金融大街25号 * bank_phone : 95533 * bank_email : [email protected] * bank_pc : 100033 */ private String bank_no; private String bank_name; private String bank_address; private String bank_phone; private String bank_email; private String bank_pc; public String getBank_no() { return bank_no; } public void setBank_no(String bank_no) { this.bank_no = bank_no; } public String getBank_name() { return bank_name; } public void setBank_name(String bank_name) { this.bank_name = bank_name; } public String getBank_address() { return bank_address; } public void setBank_address(String bank_address) { this.bank_address = bank_address; } public String getBank_phone() { return bank_phone; } public void setBank_phone(String bank_phone) { this.bank_phone = bank_phone; } public String getBank_email() { return bank_email; } public void setBank_email(String bank_email) { this.bank_email = bank_email; } public String getBank_pc() { return bank_pc; } public void setBank_pc(String bank_pc) { this.bank_pc = bank_pc; } } } }
c5c8f6f41ff044cc9db1800ff6f7e04662655825
1f19aec2ecfd756934898cf0ad2758ee18d9eca2
/u-1/u-11/u-11-f2358.java
314fd5a9c29674163643a32719533c56a842dde1
[]
no_license
apertureatf/perftest
f6c6e69efad59265197f43af5072aa7af8393a34
584257a0c1ada22e5486052c11395858a87b20d5
refs/heads/master
2020-06-07T17:52:51.172890
2019-06-21T18:53:01
2019-06-21T18:53:01
193,039,805
0
0
null
null
null
null
UTF-8
Java
false
false
105
java
mastercard 5555555555554444 4012888888881881 4222222222222 378282246310005 6011111111111117 587172572652
49d4e83b2352e9d92e1e39320124cd5df5166882
3c717bd4aa8ea05696e032a40e9d44aed9b8bf09
/springProjects/DojosNinjas/src/main/java/com/codingdojo/dojosninjas/services/NinjaService.java
35fffb29fef2125c8274cf92409adb892475bdaf
[]
no_license
nalydmartin/Java-Stack
81aad91227c1f0efcd5534583d6819787645d003
02e0fbf5c4ea276db7396ed3e80d3748c30c9b0e
refs/heads/master
2023-02-05T00:30:12.476549
2020-12-20T06:31:36
2020-12-20T06:31:36
318,294,309
0
0
null
null
null
null
UTF-8
Java
false
false
1,233
java
package com.codingdojo.dojosninjas.services; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.codingdojo.dojosninjas.models.Ninja; import com.codingdojo.dojosninjas.repos.NinjaRepo; @Service public class NinjaService { @Autowired private NinjaRepo ninjaRepo; // ------------- Find All Ninjas ------------- // public List<Ninja> findAllNinjas() { return ninjaRepo.findAll(); } // ------------- Find All Ninjas ------------- // // ------------- Find One Ninja ------------- // public Ninja findNinjaById(Long id) { Optional<Ninja> ninja = ninjaRepo.findById(id); if(ninja.isPresent()) { return ninja.get(); } else { return null; } } // ------------- Find One Ninja ------------- // // ------------- Create/Update Ninja ------------- // public Ninja createNinja(Ninja ninja) { return ninjaRepo.save(ninja); } // ------------- Create/Update Ninja ------------- // // ------------- Delete Ninja ------------- // public void deleteNinja(Long id) { ninjaRepo.deleteById(id); } // ------------- Delete Ninja ------------- // }
76bc2337c7128d47d312ab01bafbfc4550d90202
db9c82c2eb8548738004a60077178cf0c4ab7e89
/app/src/main/java/com/computer/mazhihuapp/application/myApplication.java
f37e6b6cdc147fa4b6d232acee9175c78342200f
[]
no_license
keninqiu/android-Mazhihuapp
2cc0f2c98a2c1ca05f8d19ec854e4230719f8247
8dfed043f0bef4b135584ddb1fa8bc81b081cf80
refs/heads/master
2021-01-20T18:52:55.103972
2016-06-25T03:01:38
2016-06-25T03:01:38
61,924,189
0
0
null
null
null
null
UTF-8
Java
false
false
2,280
java
package com.computer.mazhihuapp.application; import android.app.Application; import android.content.Context; import android.os.Looper; import com.computer.mazhihuapp.utils.net.ImageUtil; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.utils.StorageUtils; import net.tsz.afinal.FinalBitmap; import java.io.File; /** * Created by computer on 2015/9/15. */ public class myApplication extends Application { /** 全局Context,原理是因为Application类是应用最先运行的,所以在我们的代码调用时,该值已经被赋值过了 */ private static myApplication mInstance; /** 主线程Looper */ private static Looper mMainLooper; private FinalBitmap mFinalBitmap; public String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public void onCreate() { mInstance = this; mMainLooper = getMainLooper(); super.onCreate(); initImageLoader(getApplicationContext()); } public static myApplication getApplication() { return mInstance; } /** 获取主线程的looper */ public static Looper getMainThreadLooper() { return mMainLooper; } /** * 获取FinalBitmap * * @return */ public FinalBitmap getFinalBitmap() { if (mFinalBitmap == null) { mFinalBitmap = FinalBitmap.create(this); mFinalBitmap.configDiskCachePath(ImageUtil.getDiskCacheDir(this, "imageCache/")); mFinalBitmap .configMemoryCachePercent(0.3f); mFinalBitmap.configDiskCacheSize(30 * 1024 * 1024); mFinalBitmap.configBitmapLoadThreadSize(5); } return mFinalBitmap; } private void initImageLoader(Context context) { File cacheDir = StorageUtils.getCacheDirectory(context); ImageLoaderConfiguration config = ImageLoaderConfiguration.createDefault(context); ImageLoader.getInstance().init(config); } }
f6be1489c3a8cf2828f2813abd6183ae893305cf
133071ec8016954f4a9555d33547728295c56cdd
/src/main/java/com/mycompany/dbclpm/DAO/UserDAO.java
a638ab42f065a74129400ee7ffd80898d91bf54a
[]
no_license
bleach1606/dam-bao-chat-luong-pham-mem
2586b182ba5d9664bc9f295c440fa61b977be37d
a883e25d95d880fa19dee2fe4ccaadb51f9743c6
refs/heads/master
2022-07-08T17:56:00.873475
2020-06-25T08:05:12
2020-06-25T08:05:12
250,813,389
4
0
null
2022-06-21T03:07:23
2020-03-28T14:19:38
Java
UTF-8
Java
false
false
1,558
java
package com.mycompany.dbclpm.DAO; import com.mycompany.dbclpm.model.User; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; public class UserDAO extends DAO{ public UserDAO(){ super(); try { connectToDB(); } catch (Exception ex) { Logger.getLogger(UserDAO.class.getName()).log(Level.SEVERE, null, ex); } } public User CheckUser(String username, String password) throws Exception{ if(checkSQl(password) || checkSQl(username)) { throw new Exception("Chứa kí tự đặc biết"); } User user = null; String sql = "select * from tbl_user where username = ? and password = ?"; try{ PreparedStatement ps = connect.prepareStatement(sql); ps.setString(1, username); ps.setString(2, password); ResultSet rs = ps.executeQuery(); System.out.println(ps); if(rs.next()) { user = new User(); user.setId(rs.getInt("id")); user.setUsername(rs.getString("username")); user.setPassword(rs.getString("password")); } }catch(Exception e){ e.printStackTrace(); } return user; } public static void main(String[] args) throws Exception { UserDAO test = new UserDAO(); System.out.println(test.CheckUser("admin", "123456").toString()); } }
7900164b1e6f6fb1831e12f6016b1949624fcc34
f017d7635e4f6f40b9c50fb94033d9919b33a0d3
/BTree/TestAVL/AVL_Tree/AVLTree.java
d2e445fd71e72514309567a6f4e24adf76dd8506
[]
no_license
sokolenko100/Study
2da776b8bcfbfd9a39cc5c15151bd22d4a281994
80b88f7cf4257a824ed2fbcfa52cc313cf286eb1
refs/heads/master
2020-06-14T08:55:33.268217
2017-06-09T14:43:25
2017-06-09T14:43:25
75,208,454
0
0
null
null
null
null
WINDOWS-1251
Java
false
false
11,432
java
package AVL_Tree; import java.util.Iterator; import BTree.ETree; public class AVLTree implements ETree { public static void main(String[] args) { AVLTree tree = new AVLTree(); int val = 4; int[] ex = { 2, 3, 4 }; tree.init(ex); tree.toString(); } private int heightNode(Node p) { int result; if (p == null) { result = 0; } else { result=p.height; } return result; } private int balanceFactor(Node p) { return heightNode(p.left) - heightNode(p.right); } private Node rotateRight(Node p) { if(p==null) return null; Node temp = p.left; p.left = temp.right; temp.right = p; p.height = Math.max(heightNode(p.left), heightNode(p.right)) + 1; temp.height = Math.max(heightNode(temp.left), heightNode(temp.right)) + 1; return temp; } private Node rotateLeft(Node p) { if(p==null) return null; Node temp = p.right; p.right = temp.left; temp.left = p; p.height = Math.max(heightNode(p.left), heightNode(p.right)) + 1; temp.height = Math.max(heightNode(temp.left), heightNode(temp.right)) + 1; return temp; } private Node Balance(Node p) { if(p==null) return null; // int balanceFactor = balanceFactor(p); // if( balanceFactor <= -2 ) if (heightNode( p.left)+1>heightNode( p.right)) { if( balanceFactor(p.right) > 0 ) { p.right = rotateRight(p.right); } return rotateLeft(p); } //if( balanceFactor >= 2 ) if(heightNode( p.left)<heightNode( p.right)+1) { if( balanceFactor(p.left) < 0 ) { p.left = rotateLeft(p.left); } return rotateRight(p); } p.height = Math.max(heightNode(p.left), heightNode(p.right)) + 1; return p; } //////////////////////////////////////////////////////// // Add //////////////////////////////////////////////////////// public void add(int val) { if (root==null) { root= new Node(val); return; } else { this.AddNode(root, val); } } Node AddNode(Node p, int val) { if( p == null) return new Node(val); if( val < p.val ) { p.left = AddNode(p.left, val); } else { p.right = AddNode(p.right, val); } return Balance(p); } //////////////////////////////////////////////////////// // init //////////////////////////////////////////////////////// public void init(int[] tempArray) { this. clear(); if (tempArray== null||tempArray.length==0) return; for (int i = 0; i < tempArray.length; i++) { this.add(tempArray[i]); } } //////////////////////////////////////////////////////// // print //////////////////////////////////////////////////////// public void print() { printNode(root); } private void printNode(Node p) { if(p==null) return; this.printNode(p.left); System.out.print(p.val+", "); this.printNode(p.right); } //////////////////////////////////////////////////////// // clear //////////////////////////////////////////////////////// public void clear() { root =null; } //////////////////////////////////////////////////////// // size //////////////////////////////////////////////////////// @Override public int size() { int size =0; size= sizeNode(root); return size; } private int sizeNode(Node root) { if(root ==null) return 0; return 1 +sizeNode(root.left)+sizeNode(root.right); } //////////////////////////////////////////////////////// // nodes //////////////////////////////////////////////////////// @Override public int nodes() { int result = 0; result= Nodes( root); return result; } private int Nodes(Node p) { if (p==null) return 0; int count=0; if ((p.left!=null)|| (p.right!=null)) count++; count+=Nodes( p.left); count+=Nodes( p.right); return count; } //////////////////////////////////////////////////////// // leaves //////////////////////////////////////////////////////// @Override public int leaves() { int result = 0; result= Leaves( root); return result; } private int Leaves(Node p) { if (p==null) return 0; int count=0; if ((p.left==null)&&(p.right==null)) count++; count+=Leaves( p.left); count+=Leaves( p.right); return count; } //////////////////////////////////////////////////////// // height //////////////////////////////////////////////////////// @Override public int height() { int result =0; result = Height(root); return result; } public int Height(Node p) { if (p==null) { return 0; } int result =0; int leftCount=0; int rightCount=0; leftCount= Height(p.left); rightCount= Height(p.right); result=1 + Math.max(leftCount, rightCount); return result; } //////////////////////////////////////////////////////// // width //////////////////////////////////////////////////////// @Override public int width() { int result = 0; int [] array= new int[height()]; Width(root,array,0); result= max( array); return result; } public void Width(Node p,int [] array,int level) { if (p==null) return ; Width( p.left, array, level+1); array[level]++; Width( p.right, array, level+1); } private int max(int [] array) { int max = 0; if(array.length!=0) { max= array[0]; for (int i : array) { if (i>max) { max=i; } } } return max; } //////////////////////////////////////////////////////// // reverse //////////////////////////////////////////////////////// @Override public void reverse() { Reverse(root); } public void Reverse(Node p) { if(p.left == null ||p.right == null) return; Node tmp = p.left; p.left=p.right; p.right = tmp; Reverse(p.left); Reverse(p.right); } //////////////////////////////////////////////////////// // del1 смещением //////////////////////////////////////////////////////// private void DellNode (Node parent, Node current,int val) { if(current.val>val) { parent =current; DellNode ( parent, current.left, val); return; } else if(current.val<val) { parent =current; DellNode ( parent, current.right, val); return; } else { if(current.left==null&&current.right==null) { if(root==current) { root=null; return; } if (parent.left==current) { parent.left=null; } else { parent.right=null; } return; } if(current.left==null||current.right==null) { if (current.left==null) { if(root==current) { root=current.right; return; } if (parent.left==current) { parent.left=current.right; } else { parent.right=current.right; } } else { if(root==current) { root=current.left; return; } if (parent.left==current) { parent.left=current.left; } else { parent.right=current.left; } } } else { Node nodeSearch=null; if (root ==current) { if (current.left.right!=null) { nodeSearch= SearchNode(current.left.right,current.left); nodeSearch.left=root.left; nodeSearch.right=root.right; root=nodeSearch; } else { Node tmp = root.left; tmp.right=root.right; root=tmp; } } else { if (current.left.right!=null) { nodeSearch= SearchNode(current.left.right,current.left); if (parent.left==current) { nodeSearch.left=current.left; nodeSearch.right=current.right; parent.left=nodeSearch; } else { nodeSearch.left=current.left; nodeSearch.right=current.right; parent.right=nodeSearch; } } else { if (parent.left==current) { Node tmp = current.left; tmp.right=current.right; parent.left=tmp; } else { Node tmp = current.left; tmp.right=current.right; parent.right=tmp; } } } System.out.println(); } } } private Node SearchNode(Node p, Node parent) { if(p.right==null) { parent.right=p.left; return p; } parent = p; return SearchNode( p.right,parent ); } @Override public void del(int val) { if(root==null) return; Node parent = null; Node current = root; DellNode ( parent, current, val); } //////////////////////////////////////////////////////// // del2 поворотом //////////////////////////////////////////////////////// private void DellNode2 (Node parent, Node current,int val) { if(current.val>val) { parent =current; DellNode ( parent, current.left, val); return; } else if(current.val<val) { parent =current; DellNode ( parent, current.right, val); return; } else { if(current.left==null&&current.right==null) { if(root==current) { root=null; return; } if (parent.left==current) { parent.left=null; } else { parent.right=null; } return; } if(current.left==null||current.right==null) { if (current.left==null) { if(root==current) { root=current.right; return; } if (parent.left==current) { parent.left=current.right; } else { parent.right=current.right; } } else { if(root==current) { root=current.left; return; } if (parent.left==current) { parent.left=current.left; } else { parent.right=current.left; } } } else { Node nodeSearch=null; if (root ==current) { if (current.left.right!=null) { nodeSearch= SearchNode2(current.left.right); nodeSearch.right=root.right; root=root.left; } else { Node tmp = root.left; tmp.right=root.right; root=tmp; } } else { if (current.left.right!=null) { nodeSearch= SearchNode2(current.left.right); nodeSearch.right=current.right; parent.left=current.left; } else { Node tmp = current.left; tmp.right=current.right; parent.left=current.left; } } System.out.println(); } } } private Node SearchNode2(Node p) { if(p.right==null) { return p; } return SearchNode2(p.right); } //////////////////////////////////////////////////////// // toString //////////////////////////////////////////////////////// @Override public String toString() { return ToString(root).replaceFirst(", $", ""); } private String ToString(Node p) { if(p ==null) return ""; return ToString( p.left)+ p.val+", "+ToString( p.right); } //////////////////////////////////////////////////////// // toArray //////////////////////////////////////////////////////// @Override public int[] toArray() { int [] array = new int [size()]; Counter counter = new Counter(); ToArray(root,array, counter); return array; } private class Counter { int val= 0; } public void ToArray(Node p,int [] array,Counter counter) { if(p==null) return; ToArray( p.left,array, counter); array[counter.val++]=p.val; ToArray( p.right,array, counter); } public class Node { int val; Node left; Node right; int height; public Node(int val) { this.val=val; } } Node root = null; @Override public Iterator<Integer> iterator() { // TODO Auto-generated method stub return null; } }
15932a72685573f959e356b174e7891674186a73
020d1f1d171b43aa3aa07c4ac071ec38f1f514bc
/build/app/generated/not_namespaced_r_class_sources/debug/processDebugResources/r/com/google/firebase/R.java
8a45d7ca8725ddd75e37e35ef43f6a5673f993e8
[ "MIT" ]
permissive
sourpatchgummywyrm/wtw
63515e31ebed3b9c4b6b858af3a0a04e99c25950
ad06718128b76a3e2b08127fd2778cde16730f3a
refs/heads/master
2020-08-22T00:00:55.818165
2019-10-19T22:17:52
2019-10-19T22:17:52
216,276,217
0
0
null
null
null
null
UTF-8
Java
false
false
10,360
java
/* AUTO-GENERATED FILE. DO NOT MODIFY. * * This class was automatically generated by the * gradle plugin from the resource data it found. It * should not be modified by hand. */ package com.google.firebase; public final class R { private R() {} public static final class attr { private attr() {} public static final int font = 0x7f010005; public static final int fontProviderAuthority = 0x7f010006; public static final int fontProviderCerts = 0x7f010007; public static final int fontProviderFetchStrategy = 0x7f010008; public static final int fontProviderFetchTimeout = 0x7f010009; public static final int fontProviderPackage = 0x7f01000a; public static final int fontProviderQuery = 0x7f01000b; public static final int fontStyle = 0x7f01000c; public static final int fontWeight = 0x7f01000e; } public static final class color { private color() {} public static final int notification_action_color_filter = 0x7f02000b; public static final int notification_icon_bg_color = 0x7f02000c; public static final int notification_material_background_media_default_color = 0x7f02000d; public static final int primary_text_default_material_dark = 0x7f02000e; public static final int ripple_material_light = 0x7f02000f; public static final int secondary_text_default_material_dark = 0x7f020010; public static final int secondary_text_default_material_light = 0x7f020011; } public static final class dimen { private dimen() {} public static final int compat_button_inset_horizontal_material = 0x7f030000; public static final int compat_button_inset_vertical_material = 0x7f030001; public static final int compat_button_padding_horizontal_material = 0x7f030002; public static final int compat_button_padding_vertical_material = 0x7f030003; public static final int compat_control_corner_material = 0x7f030004; public static final int notification_action_icon_size = 0x7f030007; public static final int notification_action_text_size = 0x7f030008; public static final int notification_big_circle_margin = 0x7f030009; public static final int notification_content_margin_start = 0x7f03000a; public static final int notification_large_icon_height = 0x7f03000b; public static final int notification_large_icon_width = 0x7f03000c; public static final int notification_main_column_padding_top = 0x7f03000d; public static final int notification_media_narrow_margin = 0x7f03000e; public static final int notification_right_icon_size = 0x7f03000f; public static final int notification_right_side_padding_top = 0x7f030010; public static final int notification_small_icon_background_padding = 0x7f030011; public static final int notification_small_icon_size_as_large = 0x7f030012; public static final int notification_subtext_size = 0x7f030013; public static final int notification_top_pad = 0x7f030014; public static final int notification_top_pad_large_text = 0x7f030015; } public static final class drawable { private drawable() {} public static final int notification_action_background = 0x7f040015; public static final int notification_bg = 0x7f040016; public static final int notification_bg_low = 0x7f040017; public static final int notification_bg_low_normal = 0x7f040018; public static final int notification_bg_low_pressed = 0x7f040019; public static final int notification_bg_normal = 0x7f04001a; public static final int notification_bg_normal_pressed = 0x7f04001b; public static final int notification_icon_background = 0x7f04001c; public static final int notification_template_icon_bg = 0x7f04001d; public static final int notification_template_icon_low_bg = 0x7f04001e; public static final int notification_tile_bg = 0x7f04001f; public static final int notify_panel_notification_icon_bg = 0x7f040020; } public static final class id { private id() {} public static final int action0 = 0x7f050000; public static final int action_container = 0x7f050001; public static final int action_divider = 0x7f050002; public static final int action_image = 0x7f050003; public static final int action_text = 0x7f050004; public static final int actions = 0x7f050005; public static final int async = 0x7f050009; public static final int blocking = 0x7f05000b; public static final int cancel_action = 0x7f05000d; public static final int chronometer = 0x7f050011; public static final int end_padder = 0x7f050016; public static final int forever = 0x7f05001a; public static final int icon = 0x7f05001b; public static final int icon_group = 0x7f05001c; public static final int info = 0x7f05001e; public static final int italic = 0x7f05001f; public static final int line1 = 0x7f050022; public static final int line3 = 0x7f050023; public static final int media_actions = 0x7f050024; public static final int normal = 0x7f050026; public static final int notification_background = 0x7f050027; public static final int notification_main_column = 0x7f050028; public static final int notification_main_column_container = 0x7f050029; public static final int right_icon = 0x7f05002b; public static final int right_side = 0x7f05002c; public static final int status_bar_latest_event_content = 0x7f05002f; public static final int text = 0x7f050033; public static final int text2 = 0x7f050034; public static final int time = 0x7f050035; public static final int title = 0x7f050036; } public static final class integer { private integer() {} public static final int cancel_button_image_alpha = 0x7f060000; public static final int google_play_services_version = 0x7f060001; public static final int status_bar_notification_info_maxnum = 0x7f060002; } public static final class layout { private layout() {} public static final int notification_action = 0x7f070000; public static final int notification_action_tombstone = 0x7f070001; public static final int notification_media_action = 0x7f070002; public static final int notification_media_cancel_action = 0x7f070003; public static final int notification_template_big_media = 0x7f070004; public static final int notification_template_big_media_custom = 0x7f070005; public static final int notification_template_big_media_narrow = 0x7f070006; public static final int notification_template_big_media_narrow_custom = 0x7f070007; public static final int notification_template_custom_big = 0x7f070008; public static final int notification_template_icon_group = 0x7f070009; public static final int notification_template_lines_media = 0x7f07000a; public static final int notification_template_media = 0x7f07000b; public static final int notification_template_media_custom = 0x7f07000c; public static final int notification_template_part_chronometer = 0x7f07000d; public static final int notification_template_part_time = 0x7f07000e; } public static final class string { private string() {} public static final int common_google_play_services_unknown_issue = 0x7f090008; public static final int status_bar_notification_info_overflow = 0x7f09001a; } public static final class style { private style() {} public static final int TextAppearance_Compat_Notification = 0x7f0a0000; public static final int TextAppearance_Compat_Notification_Info = 0x7f0a0001; public static final int TextAppearance_Compat_Notification_Info_Media = 0x7f0a0002; public static final int TextAppearance_Compat_Notification_Line2 = 0x7f0a0003; public static final int TextAppearance_Compat_Notification_Line2_Media = 0x7f0a0004; public static final int TextAppearance_Compat_Notification_Media = 0x7f0a0005; public static final int TextAppearance_Compat_Notification_Time = 0x7f0a0006; public static final int TextAppearance_Compat_Notification_Time_Media = 0x7f0a0007; public static final int TextAppearance_Compat_Notification_Title = 0x7f0a0008; public static final int TextAppearance_Compat_Notification_Title_Media = 0x7f0a0009; public static final int Widget_Compat_NotificationActionContainer = 0x7f0a000a; public static final int Widget_Compat_NotificationActionText = 0x7f0a000b; } public static final class styleable { private styleable() {} public static final int[] FontFamily = { 0x7f010006, 0x7f010007, 0x7f010008, 0x7f010009, 0x7f01000a, 0x7f01000b }; public static final int FontFamily_fontProviderAuthority = 0; public static final int FontFamily_fontProviderCerts = 1; public static final int FontFamily_fontProviderFetchStrategy = 2; public static final int FontFamily_fontProviderFetchTimeout = 3; public static final int FontFamily_fontProviderPackage = 4; public static final int FontFamily_fontProviderQuery = 5; public static final int[] FontFamilyFont = { 0x1010532, 0x1010533, 0x101053f, 0x101056f, 0x1010570, 0x7f010005, 0x7f01000c, 0x7f01000d, 0x7f01000e, 0x7f01001a }; public static final int FontFamilyFont_android_font = 0; public static final int FontFamilyFont_android_fontWeight = 1; public static final int FontFamilyFont_android_fontStyle = 2; public static final int FontFamilyFont_android_ttcIndex = 3; public static final int FontFamilyFont_android_fontVariationSettings = 4; public static final int FontFamilyFont_font = 5; public static final int FontFamilyFont_fontStyle = 6; public static final int FontFamilyFont_fontVariationSettings = 7; public static final int FontFamilyFont_fontWeight = 8; public static final int FontFamilyFont_ttcIndex = 9; } }
a8451b0be886723c87d9355b6491efc1a8d41d46
2ae3b7d8c8914c95b0b83276ffef49c42812111e
/RabbitMQ_Demo/src/main/java/connection/ConnectionDemo.java
cc90aaf870154f8198a4023e71b080d537d3eda5
[]
no_license
dream-yl/First_Repository
d21804ede50db4340f82c9c8b9a407e5d697a5f0
683df965821215ef04286a88572b183e4ffd943d
refs/heads/master
2020-11-30T07:31:20.949827
2019-12-27T02:13:13
2019-12-27T02:13:13
230,348,197
0
0
null
2020-10-13T18:28:25
2019-12-27T00:56:47
Java
UTF-8
Java
false
false
666
java
package connection; import com.rabbitmq.client.Connection; import com.rabbitmq.client.ConnectionFactory; /** * 获取rabbit链接 */ public class ConnectionDemo { public static Connection GetRabbitConnection() { ConnectionFactory factory = new ConnectionFactory(); factory.setUsername("guest"); factory.setPassword("guest"); factory.setVirtualHost("demo"); factory.setHost("127.0.0.1 "); factory.setPort(5672); Connection conn = null; try { conn = factory.newConnection(); } catch (Exception e) { e.printStackTrace(); } return conn; } }
c45b59d6f74d0e2a82b5ed3bf065232a8914f4f2
450e2e8dc0d2bf6ab97b80820332bc44ba085e81
/src/main/java/com/greenfox/chat/service/JsonService.java
4f7bd9dda57b8da979ef1a39b35cdd62e60bd514
[]
no_license
green-fox-academy/viktorhegyi-p2p
6293e029b8ec44ba9bd69582efc25dd26d2f2630
616d6553fd3c0204a5f227dd7fc7856416e774bb
refs/heads/master
2021-06-17T14:33:04.643020
2017-05-25T14:51:33
2017-05-25T14:51:33
null
0
0
null
null
null
null
UTF-8
Java
false
false
110
java
package com.greenfox.chat.service; /** * Created by Viktor on 2017-05-18. */ public class JsonService { }
34bf36c2e9d2cf39ee74ac4f3de60ef46265c390
d81e885577e5ab10fb3cb2ca83dcee9c610bb7fe
/src/main/java/com/console/entity/Users.java
0f5824c15f555275dbd0a3604da6d5542af2548b
[]
no_license
theTuring/west2
63ece04b8e8b25feafe19391e96f46fd67f882e2
2fa6a2e78a91e897eb860d9e5303fcdf601e40cc
refs/heads/master
2020-04-16T04:54:32.901426
2019-01-11T18:02:24
2019-01-11T18:02:24
165,285,812
0
0
null
null
null
null
UTF-8
Java
false
false
1,265
java
//users的实体类 package com.console.entity; import java.io.Serializable; public class Users implements Serializable{ private static final long serialVersionUID = 1L; //id private Integer id; //用户名 private String username; //密码 private String password; //姓名 private String name; //性别 private String gender; //电话号码 private String phone; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } }
f845faabd725cab08c4e82a94dd50df27b4888ff
1a3f717e581e0dc94f6b543dbae5ec383e145d2d
/src/main/java/com/example/watcheshop/service/WatchServiceImpl.java
60def8e7dd9b092583b70501112c92c9d84bd5c8
[]
no_license
jirijanecek77/watch-eshop
c55ce07d72ae9480181e6b00b1400d49eac923f8
14e51343964b933a20b01dfd4722c9e50a9f9524
refs/heads/master
2022-12-24T11:31:51.668176
2020-10-10T06:48:37
2020-10-10T06:48:37
289,843,796
0
0
null
null
null
null
UTF-8
Java
false
false
671
java
package com.example.watcheshop.service; import com.example.watcheshop.model.Watch; import com.example.watcheshop.repository.WatchRepository; import org.springframework.stereotype.Service; @Service public class WatchServiceImpl implements WatchService { private final WatchRepository watchRepository; public WatchServiceImpl(WatchRepository watchRepository) { this.watchRepository = watchRepository; } @Override public Watch save(Watch watch) { return watchRepository.save(watch); } @Override public boolean findDuplicity(Watch watch) { return !watchRepository.findByTitle(watch.getTitle()).isEmpty(); } }
43eb6e28edc650bf167aedf4d11f3a1411d8ddb4
6392035b0421990479baf09a3bc4ca6bcc431e6e
/projects/presto-8b1f5ce4/prev/presto-main/src/main/java/com/facebook/presto/sql/planner/ExpressionInterpreter.java
a182c6deac62b6fda9d07073cb45625ab12c80df
[]
no_license
ameyaKetkar/RMinerEvaluationTools
4975130072bf1d4940f9aeb6583eba07d5fedd0a
6102a69d1b78ae44c59d71168fc7569ac1ccb768
refs/heads/master
2020-09-26T00:18:38.389310
2020-05-28T17:34:39
2020-05-28T17:34:39
226,119,387
3
1
null
null
null
null
UTF-8
Java
false
false
35,386
java
/* * 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.facebook.presto.sql.planner; import com.facebook.presto.Session; import com.facebook.presto.metadata.FunctionInfo; import com.facebook.presto.metadata.FunctionRegistry; import com.facebook.presto.metadata.Metadata; import com.facebook.presto.metadata.OperatorType; import com.facebook.presto.spi.ConnectorSession; import com.facebook.presto.spi.PrestoException; import com.facebook.presto.spi.RecordCursor; import com.facebook.presto.spi.block.Block; import com.facebook.presto.spi.type.Type; import com.facebook.presto.sql.tree.ArithmeticBinaryExpression; import com.facebook.presto.sql.tree.ArithmeticUnaryExpression; import com.facebook.presto.sql.tree.ArrayConstructor; import com.facebook.presto.sql.tree.AstVisitor; import com.facebook.presto.sql.tree.BetweenPredicate; import com.facebook.presto.sql.tree.BooleanLiteral; import com.facebook.presto.sql.tree.Cast; import com.facebook.presto.sql.tree.CoalesceExpression; import com.facebook.presto.sql.tree.ComparisonExpression; import com.facebook.presto.sql.tree.Expression; import com.facebook.presto.sql.tree.FunctionCall; import com.facebook.presto.sql.tree.InListExpression; import com.facebook.presto.sql.tree.InPredicate; import com.facebook.presto.sql.tree.InputReference; import com.facebook.presto.sql.tree.IsNotNullPredicate; import com.facebook.presto.sql.tree.IsNullPredicate; import com.facebook.presto.sql.tree.LikePredicate; import com.facebook.presto.sql.tree.Literal; import com.facebook.presto.sql.tree.LogicalBinaryExpression; import com.facebook.presto.sql.tree.Node; import com.facebook.presto.sql.tree.NotExpression; import com.facebook.presto.sql.tree.NullIfExpression; import com.facebook.presto.sql.tree.NullLiteral; import com.facebook.presto.sql.tree.QualifiedName; import com.facebook.presto.sql.tree.QualifiedNameReference; import com.facebook.presto.sql.tree.Row; import com.facebook.presto.sql.tree.SearchedCaseExpression; import com.facebook.presto.sql.tree.SimpleCaseExpression; import com.facebook.presto.sql.tree.StringLiteral; import com.facebook.presto.sql.tree.SubscriptExpression; import com.facebook.presto.sql.tree.WhenClause; import com.facebook.presto.type.LikeFunctions; import com.google.common.base.Functions; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import io.airlift.joni.Regex; import io.airlift.slice.Slice; import java.lang.invoke.MethodHandle; import java.util.ArrayList; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Stream; import static com.facebook.presto.spi.StandardErrorCode.NOT_SUPPORTED; import static com.facebook.presto.spi.type.TypeSignature.parseTypeSignature; import static com.facebook.presto.sql.planner.LiteralInterpreter.toExpression; import static com.facebook.presto.sql.planner.LiteralInterpreter.toExpressions; import static com.facebook.presto.util.ImmutableCollectors.toImmutableList; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.base.Predicates.instanceOf; import static com.google.common.collect.Iterables.any; import static java.nio.charset.StandardCharsets.UTF_8; public class ExpressionInterpreter { private final Expression expression; private final Metadata metadata; private final ConnectorSession session; private final boolean optimize; private final IdentityHashMap<Expression, Type> expressionTypes; private final Visitor visitor; // identity-based cache for LIKE expressions with constant pattern and escape char private final IdentityHashMap<LikePredicate, Regex> likePatternCache = new IdentityHashMap<>(); private final IdentityHashMap<InListExpression, Set<Object>> inListCache = new IdentityHashMap<>(); public static ExpressionInterpreter expressionInterpreter(Expression expression, Metadata metadata, Session session, IdentityHashMap<Expression, Type> expressionTypes) { checkNotNull(expression, "expression is null"); checkNotNull(metadata, "metadata is null"); checkNotNull(session, "session is null"); return new ExpressionInterpreter(expression, metadata, session, expressionTypes, false); } public static ExpressionInterpreter expressionOptimizer(Expression expression, Metadata metadata, Session session, IdentityHashMap<Expression, Type> expressionTypes) { checkNotNull(expression, "expression is null"); checkNotNull(metadata, "metadata is null"); checkNotNull(session, "session is null"); return new ExpressionInterpreter(expression, metadata, session, expressionTypes, true); } private ExpressionInterpreter(Expression expression, Metadata metadata, Session session, IdentityHashMap<Expression, Type> expressionTypes, boolean optimize) { this.expression = expression; this.metadata = metadata; this.session = session.toConnectorSession(); this.expressionTypes = expressionTypes; this.optimize = optimize; this.visitor = new Visitor(); } public Object evaluate(RecordCursor inputs) { checkState(!optimize, "evaluate(RecordCursor) not allowed for optimizer"); return visitor.process(expression, inputs); } public Object evaluate(int position, Block... inputs) { checkState(!optimize, "evaluate(int, Block...) not allowed for optimizer"); return visitor.process(expression, new PagePositionContext(position, inputs)); } public Object optimize(SymbolResolver inputs) { checkState(optimize, "evaluate(SymbolResolver) not allowed for interpreter"); return visitor.process(expression, inputs); } @SuppressWarnings("FloatingPointEquality") private class Visitor extends AstVisitor<Object, Object> { @Override public Object visitInputReference(InputReference node, Object context) { Type type = expressionTypes.get(node); int channel = node.getChannel(); if (context instanceof PagePositionContext) { PagePositionContext pagePositionContext = (PagePositionContext) context; int position = pagePositionContext.getPosition(); Block block = pagePositionContext.getBlock(channel); if (block.isNull(position)) { return null; } Class<?> javaType = type.getJavaType(); if (javaType == boolean.class) { return type.getBoolean(block, position); } else if (javaType == long.class) { return type.getLong(block, position); } else if (javaType == double.class) { return type.getDouble(block, position); } else if (javaType == Slice.class) { return type.getSlice(block, position); } else { throw new UnsupportedOperationException("not yet implemented"); } } else if (context instanceof RecordCursor) { RecordCursor cursor = (RecordCursor) context; if (cursor.isNull(channel)) { return null; } Class<?> javaType = type.getJavaType(); if (javaType == boolean.class) { return cursor.getBoolean(channel); } else if (javaType == long.class) { return cursor.getLong(channel); } else if (javaType == double.class) { return cursor.getDouble(channel); } else if (javaType == Slice.class) { return cursor.getSlice(channel); } else { throw new UnsupportedOperationException("not yet implemented"); } } throw new UnsupportedOperationException("Inputs or cursor myst be set"); } @Override protected Object visitQualifiedNameReference(QualifiedNameReference node, Object context) { if (node.getName().getPrefix().isPresent()) { // not a symbol return node; } Symbol symbol = Symbol.fromQualifiedName(node.getName()); return ((SymbolResolver) context).getValue(symbol); } @Override protected Object visitLiteral(Literal node, Object context) { return LiteralInterpreter.evaluate(metadata, session, node); } @Override protected Object visitIsNullPredicate(IsNullPredicate node, Object context) { Object value = process(node.getValue(), context); if (value instanceof Expression) { return new IsNullPredicate(toExpression(value, expressionTypes.get(node.getValue()))); } return value == null; } @Override protected Object visitIsNotNullPredicate(IsNotNullPredicate node, Object context) { Object value = process(node.getValue(), context); if (value instanceof Expression) { return new IsNotNullPredicate(toExpression(value, expressionTypes.get(node.getValue()))); } return value != null; } @Override protected Object visitSearchedCaseExpression(SearchedCaseExpression node, Object context) { Expression resultClause = node.getDefaultValue().orElse(null); for (WhenClause whenClause : node.getWhenClauses()) { Object value = process(whenClause.getOperand(), context); if (value instanceof Expression) { // TODO: optimize this case return node; } if (Boolean.TRUE.equals(value)) { resultClause = whenClause.getResult(); break; } } if (resultClause == null) { return null; } Object result = process(resultClause, context); if (result instanceof Expression) { return node; } return result; } @Override protected Object visitSimpleCaseExpression(SimpleCaseExpression node, Object context) { Object operand = process(node.getOperand(), context); if (operand == null) { return node.getDefaultValue().map(defaultValue -> process(defaultValue, context)).orElse(null); } else if (operand instanceof Expression) { return node; } List<WhenClause> whenClauses = new ArrayList<>(); Expression defaultClause = node.getDefaultValue().orElse(null); for (WhenClause whenClause : node.getWhenClauses()) { Object value = process(whenClause.getOperand(), context); if (value != null) { if (value instanceof Expression) { whenClauses.add(whenClause); } else if ((Boolean) invokeOperator(OperatorType.EQUAL, types(node.getOperand(), whenClause.getOperand()), ImmutableList.of(operand, value))) { defaultClause = whenClause.getResult(); break; } } } if (whenClauses.isEmpty()) { return defaultClause == null ? null : process(defaultClause, context); } else { return new SimpleCaseExpression(node.getOperand(), whenClauses, Optional.ofNullable(defaultClause)); } } @Override protected Object visitCoalesceExpression(CoalesceExpression node, Object context) { for (Expression expression : node.getOperands()) { Object value = process(expression, context); if (value instanceof Expression) { // TODO: optimize this case return node; } if (value != null) { return value; } } return null; } @Override protected Object visitInPredicate(InPredicate node, Object context) { Object value = process(node.getValue(), context); if (value == null) { return null; } Expression valueListExpression = node.getValueList(); if (!(valueListExpression instanceof InListExpression)) { if (!optimize) { throw new UnsupportedOperationException("IN predicate value list type not yet implemented: " + valueListExpression.getClass().getName()); } return node; } InListExpression valueList = (InListExpression) valueListExpression; Set<Object> set = inListCache.get(valueList); // We use the presence of the node in the map to indicate that we've already done // the analysis below. If the value is null, it means that we can't apply the HashSet // optimization if (!inListCache.containsKey(valueList)) { if (Iterables.all(valueList.getValues(), ExpressionInterpreter::isNullLiteral)) { // if all elements are constant, create a set with them set = new HashSet<>(); for (Expression expression : valueList.getValues()) { set.add(process(expression, context)); } } inListCache.put(valueList, set); } if (set != null && !(value instanceof Expression)) { return set.contains(value); } boolean hasUnresolvedValue = false; if (value instanceof Expression) { hasUnresolvedValue = true; } boolean hasNullValue = false; boolean found = false; List<Object> values = new ArrayList<>(valueList.getValues().size()); List<Type> types = new ArrayList<>(valueList.getValues().size()); for (Expression expression : valueList.getValues()) { Object inValue = process(expression, context); if (value instanceof Expression || inValue instanceof Expression) { hasUnresolvedValue = true; values.add(inValue); types.add(expressionTypes.get(expression)); continue; } if (inValue == null) { hasNullValue = true; } else if (!found && (Boolean) invokeOperator(OperatorType.EQUAL, types(node.getValue(), expression), ImmutableList.of(value, inValue))) { // in does not short-circuit so we must evaluate all value in the list found = true; } } if (found) { return true; } if (hasUnresolvedValue) { Type type = expressionTypes.get(node.getValue()); List<Expression> expressionValues = toExpressions(values, types); List<Expression> simplifiedExpressionValues = Stream.concat( expressionValues.stream() .filter(DeterminismEvaluator::isDeterministic) .distinct(), expressionValues.stream() .filter((expression -> !DeterminismEvaluator.isDeterministic(expression)))) .collect(toImmutableList()); return new InPredicate(toExpression(value, type), new InListExpression(simplifiedExpressionValues)); } if (hasNullValue) { return null; } return false; } @Override protected Object visitArithmeticUnary(ArithmeticUnaryExpression node, Object context) { Object value = process(node.getValue(), context); if (value == null) { return null; } if (value instanceof Expression) { return new ArithmeticUnaryExpression(node.getSign(), toExpression(value, expressionTypes.get(node.getValue()))); } switch (node.getSign()) { case PLUS: return value; case MINUS: FunctionInfo operatorInfo = metadata.resolveOperator(OperatorType.NEGATION, types(node.getValue())); MethodHandle handle = operatorInfo.getMethodHandle(); if (handle.type().parameterCount() > 0 && handle.type().parameterType(0) == ConnectorSession.class) { handle = handle.bindTo(session); } try { return handle.invokeWithArguments(value); } catch (Throwable throwable) { Throwables.propagateIfInstanceOf(throwable, RuntimeException.class); Throwables.propagateIfInstanceOf(throwable, Error.class); throw new RuntimeException(throwable.getMessage(), throwable); } } throw new UnsupportedOperationException("Unsupported unary operator: " + node.getSign()); } @Override protected Object visitArithmeticBinary(ArithmeticBinaryExpression node, Object context) { Object left = process(node.getLeft(), context); if (left == null) { return null; } Object right = process(node.getRight(), context); if (right == null) { return null; } if (hasUnresolvedValue(left, right)) { return new ArithmeticBinaryExpression(node.getType(), toExpression(left, expressionTypes.get(node.getLeft())), toExpression(right, expressionTypes.get(node.getRight()))); } return invokeOperator(OperatorType.valueOf(node.getType().name()), types(node.getLeft(), node.getRight()), ImmutableList.of(left, right)); } @Override protected Object visitComparisonExpression(ComparisonExpression node, Object context) { ComparisonExpression.Type type = node.getType(); Object left = process(node.getLeft(), context); if (left == null && type != ComparisonExpression.Type.IS_DISTINCT_FROM) { return null; } Object right = process(node.getRight(), context); if (type == ComparisonExpression.Type.IS_DISTINCT_FROM) { if (left == null && right == null) { return false; } else if (left == null || right == null) { return true; } } else if (right == null) { return null; } if (hasUnresolvedValue(left, right)) { return new ComparisonExpression(type, toExpression(left, expressionTypes.get(node.getLeft())), toExpression(right, expressionTypes.get(node.getRight()))); } if (type == ComparisonExpression.Type.IS_DISTINCT_FROM) { type = ComparisonExpression.Type.NOT_EQUAL; } return invokeOperator(OperatorType.valueOf(type.name()), types(node.getLeft(), node.getRight()), ImmutableList.of(left, right)); } @Override protected Object visitBetweenPredicate(BetweenPredicate node, Object context) { Object value = process(node.getValue(), context); if (value == null) { return null; } Object min = process(node.getMin(), context); if (min == null) { return null; } Object max = process(node.getMax(), context); if (max == null) { return null; } if (hasUnresolvedValue(value, min, max)) { return new BetweenPredicate( toExpression(value, expressionTypes.get(node.getValue())), toExpression(min, expressionTypes.get(node.getMin())), toExpression(max, expressionTypes.get(node.getMax()))); } return invokeOperator(OperatorType.BETWEEN, types(node.getValue(), node.getMin(), node.getMax()), ImmutableList.of(value, min, max)); } @Override protected Object visitNullIfExpression(NullIfExpression node, Object context) { Object first = process(node.getFirst(), context); if (first == null) { return null; } Object second = process(node.getSecond(), context); if (second == null) { return first; } Type firstType = expressionTypes.get(node.getFirst()); Type secondType = expressionTypes.get(node.getSecond()); if (hasUnresolvedValue(first, second)) { return new NullIfExpression(toExpression(first, firstType), toExpression(second, secondType)); } Type commonType = FunctionRegistry.getCommonSuperType(firstType, secondType).get(); FunctionInfo firstCast = metadata.getFunctionRegistry().getCoercion(firstType, commonType); FunctionInfo secondCast = metadata.getFunctionRegistry().getCoercion(secondType, commonType); // cast(first as <common type>) == cast(second as <common type>) boolean equal = (Boolean) invokeOperator( OperatorType.EQUAL, ImmutableList.of(commonType, commonType), ImmutableList.of( invoke(session, firstCast.getMethodHandle(), ImmutableList.of(first)), invoke(session, secondCast.getMethodHandle(), ImmutableList.of(second)))); if (equal) { return null; } else { return first; } } @Override protected Object visitNotExpression(NotExpression node, Object context) { Object value = process(node.getValue(), context); if (value == null) { return null; } if (value instanceof Expression) { return new NotExpression(toExpression(value, expressionTypes.get(node.getValue()))); } return !(Boolean) value; } @Override protected Object visitLogicalBinaryExpression(LogicalBinaryExpression node, Object context) { Object left = process(node.getLeft(), context); Object right = process(node.getRight(), context); switch (node.getType()) { case AND: { // if either left or right is false, result is always false regardless of nulls if (Boolean.FALSE.equals(left) || Boolean.TRUE.equals(right)) { return left; } if (Boolean.FALSE.equals(right) || Boolean.TRUE.equals(left)) { return right; } break; } case OR: { // if either left or right is true, result is always true regardless of nulls if (Boolean.TRUE.equals(left) || Boolean.FALSE.equals(right)) { return left; } if (Boolean.TRUE.equals(right) || Boolean.FALSE.equals(left)) { return right; } break; } } if (left == null && right == null) { return null; } return new LogicalBinaryExpression(node.getType(), toExpression(left, expressionTypes.get(node.getLeft())), toExpression(right, expressionTypes.get(node.getRight()))); } @Override protected Object visitBooleanLiteral(BooleanLiteral node, Object context) { return node.equals(BooleanLiteral.TRUE_LITERAL); } @Override protected Object visitFunctionCall(FunctionCall node, Object context) { List<Type> argumentTypes = new ArrayList<>(); List<Object> argumentValues = new ArrayList<>(); for (Expression expression : node.getArguments()) { Object value = process(expression, context); Type type = expressionTypes.get(expression); argumentValues.add(value); argumentTypes.add(type); } FunctionInfo function = metadata.resolveFunction(node.getName(), Lists.transform(argumentTypes, Type::getTypeSignature), false); for (int i = 0; i < argumentValues.size(); i++) { Object value = argumentValues.get(i); if (value == null && !function.getNullableArguments().get(i)) { return null; } } // do not optimize non-deterministic functions if (optimize && (!function.isDeterministic() || hasUnresolvedValue(argumentValues))) { return new FunctionCall(node.getName(), node.getWindow(), node.isDistinct(), toExpressions(argumentValues, argumentTypes)); } return invoke(session, function.getMethodHandle(), argumentValues); } @Override protected Object visitLikePredicate(LikePredicate node, Object context) { Object value = process(node.getValue(), context); if (value == null) { return null; } if (value instanceof Slice && node.getPattern() instanceof StringLiteral && (node.getEscape() instanceof StringLiteral || node.getEscape() == null)) { // fast path when we know the pattern and escape are constant return LikeFunctions.like((Slice) value, getConstantPattern(node)); } Object pattern = process(node.getPattern(), context); if (pattern == null) { return null; } Object escape = null; if (node.getEscape() != null) { escape = process(node.getEscape(), context); if (escape == null) { return null; } } if (value instanceof Slice && pattern instanceof Slice && (escape == null || escape instanceof Slice)) { Regex regex; if (escape == null) { regex = LikeFunctions.likePattern((Slice) pattern); } else { regex = LikeFunctions.likePattern((Slice) pattern, (Slice) escape); } return LikeFunctions.like((Slice) value, regex); } // if pattern is a constant without % or _ replace with a comparison if (pattern instanceof Slice && escape == null) { String stringPattern = ((Slice) pattern).toString(UTF_8); if (!stringPattern.contains("%") && !stringPattern.contains("_")) { return new ComparisonExpression(ComparisonExpression.Type.EQUAL, toExpression(value, expressionTypes.get(node.getValue())), toExpression(pattern, expressionTypes.get(node.getPattern()))); } } Expression optimizedEscape = null; if (node.getEscape() != null) { optimizedEscape = toExpression(escape, expressionTypes.get(node.getEscape())); } return new LikePredicate( toExpression(value, expressionTypes.get(node.getValue())), toExpression(pattern, expressionTypes.get(node.getPattern())), optimizedEscape); } private Regex getConstantPattern(LikePredicate node) { Regex result = likePatternCache.get(node); if (result == null) { StringLiteral pattern = (StringLiteral) node.getPattern(); StringLiteral escape = (StringLiteral) node.getEscape(); if (escape == null) { result = LikeFunctions.likePattern(pattern.getSlice()); } else { result = LikeFunctions.likePattern(pattern.getSlice(), escape.getSlice()); } likePatternCache.put(node, result); } return result; } @Override public Object visitCast(Cast node, Object context) { Object value = process(node.getExpression(), context); if (value instanceof Expression) { return new Cast((Expression) value, node.getType(), node.isSafe()); } // hack!!! don't optimize CASTs for types that cannot be represented in the SQL AST // TODO: this will not be an issue when we migrate to RowExpression tree for this, which allows arbitrary literals. if (optimize && !FunctionRegistry.isSupportedLiteralType(expressionTypes.get(node))) { return new Cast(toExpression(value, expressionTypes.get(node.getExpression())), node.getType(), node.isSafe()); } if (value == null) { return null; } Type type = metadata.getType(parseTypeSignature(node.getType())); if (type == null) { throw new IllegalArgumentException("Unsupported type: " + node.getType()); } FunctionInfo operatorInfo = metadata.getFunctionRegistry().getCoercion(expressionTypes.get(node.getExpression()), type); try { return invoke(session, operatorInfo.getMethodHandle(), ImmutableList.of(value)); } catch (RuntimeException e) { if (node.isSafe()) { return null; } throw e; } } @Override protected Object visitArrayConstructor(ArrayConstructor node, Object context) { return visitFunctionCall(new FunctionCall(QualifiedName.of(ArrayConstructor.ARRAY_CONSTRUCTOR), node.getValues()), context); } @Override protected Object visitRow(Row node, Object context) { throw new PrestoException(NOT_SUPPORTED, "Row expressions not yet supported"); } @Override protected Object visitSubscriptExpression(SubscriptExpression node, Object context) { Object base = process(node.getBase(), context); if (base == null) { return null; } Object index = process(node.getIndex(), context); if (index == null) { return null; } if (hasUnresolvedValue(base, index)) { return new SubscriptExpression(toExpression(base, expressionTypes.get(node.getBase())), toExpression(index, expressionTypes.get(node.getIndex()))); } return invokeOperator(OperatorType.SUBSCRIPT, types(node.getBase(), node.getIndex()), ImmutableList.of(base, index)); } @Override protected Object visitExpression(Expression node, Object context) { throw new PrestoException(NOT_SUPPORTED, "not yet implemented: " + node.getClass().getName()); } @Override protected Object visitNode(Node node, Object context) { throw new UnsupportedOperationException("Evaluator visitor can only handle Expression nodes"); } private List<Type> types(Expression... types) { return ImmutableList.copyOf(Iterables.transform(ImmutableList.copyOf(types), Functions.forMap(expressionTypes))); } private boolean hasUnresolvedValue(Object... values) { return hasUnresolvedValue(ImmutableList.copyOf(values)); } private boolean hasUnresolvedValue(List<Object> values) { return any(values, instanceOf(Expression.class)); } private Object invokeOperator(OperatorType operatorType, List<? extends Type> argumentTypes, List<Object> argumentValues) { FunctionInfo operatorInfo = metadata.resolveOperator(operatorType, argumentTypes); return invoke(session, operatorInfo.getMethodHandle(), argumentValues); } } private static class PagePositionContext { private final int position; private final Block[] blocks; private PagePositionContext(int position, Block[] blocks) { this.position = position; this.blocks = blocks; } public Block getBlock(int channel) { return blocks[channel]; } public int getPosition() { return position; } } public static Object invoke(ConnectorSession session, MethodHandle handle, List<Object> argumentValues) { if (handle.type().parameterCount() > 0 && handle.type().parameterType(0) == ConnectorSession.class) { handle = handle.bindTo(session); } try { return handle.invokeWithArguments(argumentValues); } catch (Throwable throwable) { if (throwable instanceof InterruptedException) { Thread.currentThread().interrupt(); } throw Throwables.propagate(throwable); } } private static boolean isNullLiteral(Expression entry) { return entry instanceof Literal && !(entry instanceof NullLiteral); } }
4549ef63c67468cd88e4f35b5944b0209edfec2c
1d7699c25a30a4f90398c32711567a61edb1f4b5
/src/hmeng/lc/medium/LC0837.java
7bb4dad3cff7f53ba51fb485352caecc78449cde
[]
no_license
autotiger/LCProblems
516a5b1afe153688d397ee247f8b4abac6456a52
83d9315cbd37dbcdd7d9118729fafa73e905c4a4
refs/heads/master
2018-07-05T18:43:07.098853
2018-05-31T22:03:01
2018-05-31T22:03:01
125,958,684
0
1
null
2018-03-20T06:10:52
2018-03-20T04:01:18
Java
UTF-8
Java
false
false
2,284
java
package hmeng.lc.medium; import java.util.Arrays; /* 37. New 21 Game Alice plays the following game, loosely based on the card game "21". Alice starts with 0 points, and draws numbers while she has less than K points. During each draw, she gains an integer number of points randomly from the range [1, W], where W is an integer. Each draw is independent and the outcomes have equal probabilities. Alice stops drawing numbers when she gets K or more points. What is the probability that she has N or less points? Example 1: Input: N = 10, K = 1, W = 10 Output: 1.00000 Explanation: Alice gets a single card, then stops. Example 2: Input: N = 6, K = 1, W = 10 Output: 0.60000 Explanation: Alice gets a single card, then stops. In 6 out of W = 10 possibilities, she is at or below N = 6 points. Example 3: Input: N = 21, K = 17, W = 10 Output: 0.73278 Note: 0 <= K <= N <= 10000 1 <= W <= 10000 Answers will be accepted as correct if they are within 10^-5 of the correct answer. The judging time limit has been reduced for this question. */ public class LC0837 { public double new21Game2(int N, int K, int W) { if (K == 0 || N >= K + W) return 1; double dp[] = new double[N + 1], Wsum = 1, res = 0; dp[0] = 1; for (int i = 1; i <= N; ++i) { dp[i] = Wsum / W; if (i < K) Wsum += dp[i]; else res += dp[i]; if (i - W >= 0) Wsum -= dp[i - W]; System.out.println("i: " + i + ", Wsum: " + Wsum); } System.out.println(Arrays.toString(dp)); return res; } public double new21Game(int N, int K, int W) { if (K == 0 || N >= K + W) return 1; double[] dp = new double[N+1]; dp[0] = 1.0; double wsum = 1.0; for (int i = 1; i <= N; i++) { dp[i] = wsum / W; if (i <= W) wsum += dp[i]; else if (i > W) wsum -= dp[i-W]; } System.out.println(Arrays.toString(dp)); double ans = 0.0; for (int i = K; i <= N; i++) { ans += dp[i]; } return ans; } public static void main(String[] args) { LC0837 lc = new LC0837(); System.out.println(lc.new21Game2(21, 17, 10)); } }
0af3eacf85d4c2872befc26449ab45da082c2456
e025b03e09da08f201b05bbc64bd005abd8bcefe
/FirstTest/src/com/steven/android/firsttest/tutorialFour.java
5df313a17d4a632a0151241e9862086325a0c226
[]
no_license
ambisonia/github
d9c751f3f4ab6c3077fff6e19faba6cc4a0f9a46
7bae622c4591db55939efbd017b2bbe7a40ac98c
refs/heads/master
2020-09-24T11:27:39.215971
2012-07-07T15:08:44
2012-07-07T15:08:44
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,620
java
package com.steven.android.firsttest; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import android.app.Activity; import android.media.MediaPlayer; import android.os.Bundle; import android.os.Environment; import android.view.View; import android.widget.Button; import android.widget.RadioGroup; import android.widget.Toast; import android.widget.RadioGroup.OnCheckedChangeListener; public class tutorialFour extends Activity implements OnCheckedChangeListener { MediaPlayer song1, song2, song3, song4; int Rsong; int whatsong; //this is the variable that will change to what the radio button tells it to RadioGroup rgMusic; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); setContentView(R.layout.tutorial4); whatsong = 0;//initializing rgMusic = (RadioGroup) findViewById(R.id.groupMusic); rgMusic.setOnCheckedChangeListener(this); song1 = MediaPlayer.create(tutorialFour.this, R.raw.song1); song2 = MediaPlayer.create(tutorialFour.this, R.raw.song2); song3 = MediaPlayer.create(tutorialFour.this, R.raw.song3); song4 = MediaPlayer.create(tutorialFour.this, R.raw.song4); Button bPlay = (Button) findViewById(R.id.bPlay); Button bStop = (Button) findViewById(R.id.bStop); Button bDelete = (Button) findViewById(R.id.bDelete); //on long click for Play button, save the selected song to SD card directory bPlay.setOnLongClickListener(new View.OnLongClickListener() { public boolean onLongClick(View v) { File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC); //path = path to phone SD (NOT external_SD) File file = new File(path, "Cornboyz Song" + whatsong + ".mp3"); //file is saved to "path" with name Cornboyz etc... try{ switch (whatsong){ case 1: Rsong = R.raw.song1; break; case 2: Rsong = R.raw.song2; break; case 3: Rsong = R.raw.song3; break; case 4: Rsong = R.raw.song4; break; } //file saving operations InputStream is = getResources().openRawResource(Rsong); OutputStream os = new FileOutputStream(file); byte[] data = new byte[is.available()]; //array for passing stuff in InputStream is.read(data);//read data from InputStream os.write(data);//write data to the file Toast.makeText(tutorialFour.this, "Saved", Toast.LENGTH_SHORT).show(); } catch (IOException e){ Toast fail = Toast.makeText(tutorialFour.this, "Saving Failed", Toast.LENGTH_SHORT); //toast to let user know IO failed fail.show(); } return false; } }); //setup Delete Button bDelete.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC); File file = new File(path, "Cornboyz Song" + whatsong + ".mp3"); if (file.exists() == false){ Toast.makeText(tutorialFour.this, "File does not exists.", Toast.LENGTH_SHORT).show(); } else { file.delete(); Toast.makeText(tutorialFour.this, "Deleted", Toast.LENGTH_SHORT).show(); } } }); //setup Play Button bPlay.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // get what the radio button is set up as and play the song accordingly //stop the current song if playing so we don't get overlaps if (song1.isPlaying()){ song1.pause(); song1.seekTo(0); //resets to 0sec } if (song2.isPlaying()){ song2.pause(); song2.seekTo(0); //resets to 0sec } if (song3.isPlaying()){ song3.pause(); song3.seekTo(0); //resets to 0sec } if (song4.isPlaying()){ song4.pause(); song4.seekTo(0); //resets to 0sec } //pass in value of whatsong and play the corresponding song file switch (whatsong){ case 0: Toast noSong = Toast.makeText(tutorialFour.this, "Please select a song", Toast.LENGTH_SHORT); noSong.show(); break; case 1: song1.start(); break; case 2: song2.start(); break; case 3: song3.start(); break; case 4: song4.start(); break; } } }); //setup Stop Button bStop.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // stop all music if (song1.isPlaying()){ song1.seekTo(0); song1.pause(); } else if (song2.isPlaying()){ song2.seekTo(0); song2.pause(); } else if (song3.isPlaying()){ song3.seekTo(0); song3.pause(); } else if (song4.isPlaying()){ song4.seekTo(0); song4.pause(); } } }); } public void onCheckedChanged(RadioGroup arg0, int arg1) { //change our song to what the current radio button is //this will happen automatically as radio button is changed //first checks the ID of the radio button, which is int passed into this method (arg1) switch (arg1){ case R.id.rbMusic1: //set reference of whatsong to the first file whatsong = 1; break; case R.id.rbMusic2: whatsong = 2; break; case R.id.rbMusic3: whatsong = 3; break; case R.id.rbMusic4: whatsong = 4; break; } } }
dca23dfeb398d17454d26ff972aec936ae0d01e3
9f8066596134ce9cc4f5a7c1ddb37c0f5911d807
/springbootconfig/src/main/java/com/digitalinnovationone/springbootconfig/config/DBconfiguration.java
212f615614388cfb511bcb1f44c638a14ab4aa3f
[ "MIT" ]
permissive
GabrielSilva2y3d/SpringBoot-projects
9acfebe95e738a33369617f666cc11c68c818fbf
e942376967db2701cb084e1dfdd3e5da38ae3be3
refs/heads/main
2023-06-29T16:04:31.296608
2021-07-30T11:56:10
2021-07-30T11:56:10
390,690,070
0
0
null
null
null
null
UTF-8
Java
false
false
1,162
java
package com.digitalinnovationone.springbootconfig.config; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Profile; import lombok.Getter; import lombok.Setter; @Configuration @ConfigurationProperties("spring.datasource") @Getter @Setter public class DBconfiguration { private String driverClassName; private String url; private String username; private String password; @Profile("dev") @Bean public String testDatabaseConnection() { System.out.println("DB connection for DEV - H2"); System.out.println(driverClassName); System.out.println(url); return "DB connection to H2_TEST - Test instance"; }; @Profile("prod") @Bean public String productionDatabaseConnection(){ System.out.println("DB connection for Production - MySQL"); System.out.println(driverClassName); System.out.println(url); return "DB connection to MySQL-PROD - Production instance"; }; }
0bc111a6949e684254a7e194ab21948c149fd1b0
4be5be629ca920a7c8a8a6ca51b5d5c7f2858546
/CarPoly_Web/src/main/java/com/poly/controller/UserController.java
a1be6f0a5f04c2f7e53157ba5df19729a9ae257b
[]
no_license
thanhlongdev/CarPoly_Web
d6fd58166924b9a2aa335e278e31fd36798f90e3
371de647be34170d8ff28eee632e6b3ca1e947a8
refs/heads/master
2023-06-24T22:01:03.019484
2023-06-21T06:54:18
2023-06-21T06:54:18
246,586,232
0
0
null
null
null
null
UTF-8
Java
false
false
1,049
java
package com.poly.controller; import com.poly.example.Categories; import org.hibernate.Criteria; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import java.util.List; @Controller @Transactional @RequestMapping("user/") public class UserController { @Autowired SessionFactory sessionFactory; @RequestMapping(value = "home") public ModelAndView homePage() { Session session = sessionFactory.getCurrentSession(); ModelAndView modelAndView = new ModelAndView("home"); Criteria criteria = session.createCriteria(Categories.class); modelAndView.addObject("listCategories", (List<Categories>) criteria.list()); return modelAndView; } }
04ed81f10de7639de26f9a4c27d82376e2134eb3
14320da4acbe8120143cbf672dda50a600fad76a
/src/main/java/com/tydic/service/impl/Test.java
da4e03b1b5a3b43cab2f0a7515c8c30fa53d7bec
[]
no_license
SherlockKim/dic-tools
2ebedf89902ac7ef94284af1cf12dd0603f6a001
9b64ecc8af96670757202a55f1b3defd36fc7a5e
refs/heads/master
2023-07-09T23:46:37.746184
2021-08-14T08:55:12
2021-08-14T08:55:12
395,949,574
0
0
null
null
null
null
UTF-8
Java
false
false
376
java
package com.tydic.service.impl; import java.util.ArrayList; import java.util.List; import java.util.function.Function; /** * @author 鸭屮 * @version 1.0 * @date 2021/8/6 10:57 */ public class Test { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("a"); list.add("b"); list.add("c"); } }
bb440010619889e58d13b53b56f6b7f3c638b896
3f2a81c9b8d9eec49433129a9cc0f6b4e0087f4f
/src/main/java/fr/aba/werewolf/business/service/impl/game/exception/VideoStreamException.java
7e49199939cf0680ce182089b1d41b269fa338d6
[]
no_license
aurelien-baudet/one-night-werewolf-back
192ebdbc30ed580b07cd88a0c25c3ffde194dbb3
7b4e2a53b486b8565220fcb57fc9ea2b91cb9126
refs/heads/master
2020-05-23T02:34:49.949130
2019-05-22T12:45:48
2019-05-22T12:45:48
186,607,612
0
0
null
null
null
null
UTF-8
Java
false
false
573
java
package fr.aba.werewolf.business.service.impl.game.exception; import fr.aba.werewolf.business.domain.Game; import fr.aba.werewolf.business.service.GameException; import lombok.Getter; @Getter public class VideoStreamException extends GameException { /** * */ private static final long serialVersionUID = 1L; private final Game game; public VideoStreamException(String message, Game game) { super(message); this.game = game; } public VideoStreamException(String message, Game game, Throwable cause) { super(message, cause); this.game = game; } }
ccf9a10443384a22bc221d1e334cb0226773b972
6870c4ed92eda02fd95265c00ad913c5cbb9a9be
/backend/src/main/java/com/minetec/backend/dto/form/workshop/JobCardUpdateForm.java
c4a9ca9ebf209f3c539ede8071c39bc851930408
[]
no_license
snncskn/cms
7aa04f43cd3dc1ace88081f16d52596d89cabb53
eb65ac11af72c37f05ca11a0685471f81d6a0cf8
refs/heads/master
2022-12-08T03:03:38.453920
2020-09-06T09:08:40
2020-09-06T09:08:40
293,239,697
0
0
null
null
null
null
UTF-8
Java
false
false
564
java
package com.minetec.backend.dto.form.workshop; import lombok.Data; import javax.validation.constraints.NotNull; import java.util.UUID; @Data public class JobCardUpdateForm { @NotNull private UUID jobCardUuid; @NotNull private UUID operatorUserUuid; @NotNull private UUID mechanicUserUuid; @NotNull private UUID foremanUserUuid; private boolean riskAssessment; private boolean lockOutProcedure; private boolean wheelNuts; private boolean oilLevel; private boolean machineGrease; }
16c479764c9c13b40eedc763725b55c50dd729bd
da456dbd2cad408aa2178aa9d99413df54f7e00e
/smartdevices-app/smartdevicesapp.model/src/test/java/de/vogler_engineering/smartdevicesapp/model/mock/OfflineTabRepositoryMock.java
646b6efefd11e35a8123eac60f9b0430e3b450dc
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
maxhurm/SmarDesAtWork
d0f80e6dd48ed21266809c47ba3dda277547b677
4a17e66e79ddd0fd15c345088ee42d586adde5da
refs/heads/master
2020-05-23T14:43:26.662343
2019-05-15T11:32:14
2019-05-15T11:32:14
186,810,428
0
0
MIT
2019-05-15T11:12:55
2019-05-15T11:12:55
null
UTF-8
Java
false
false
3,515
java
/** * Copyright (c) Vogler Engineering GmbH. All rights reserved. * Licensed under the MIT License. See LICENSE.md in the project root for license information. */ package de.vogler_engineering.smartdevicesapp.model.mock; import androidx.databinding.ObservableArrayList; import java.util.ArrayList; import java.util.List; import de.vogler_engineering.smartdevicesapp.common.rx.SchedulersFacade; import de.vogler_engineering.smartdevicesapp.model.entities.tabs.TabConfig; import de.vogler_engineering.smartdevicesapp.model.entities.tabs.TabFilterEntry; import de.vogler_engineering.smartdevicesapp.model.entities.tabs.TabSortEntry; import de.vogler_engineering.smartdevicesapp.model.management.AppManager; import de.vogler_engineering.smartdevicesapp.model.repository.ConfigRepository; import de.vogler_engineering.smartdevicesapp.model.repository.TabRepository; import de.vogler_engineering.smartdevicesapp.model.services.retrofit.RestServiceProvider; public class OfflineTabRepositoryMock extends TabRepository { private final ObservableArrayList<TabConfig> tabConfigs = new ObservableArrayList<>(); public OfflineTabRepositoryMock(AppManager appManager, SchedulersFacade schedulersFacade, RestServiceProvider restServiceProvider, ConfigRepository configRepository) { super(appManager, schedulersFacade, restServiceProvider, configRepository); tabConfigs.addAll(generateDemoTabs()); } @Override public ObservableArrayList<TabConfig> getTabConfig() { return tabConfigs; } public static List<TabConfig> generateDemoTabs() { List<TabConfig> list = new ArrayList<>(); TabConfig t; TabFilterEntry statusFilter = new TabFilterEntry(); statusFilter.setKey("status"); statusFilter.setInvertable(true); statusFilter.setName("Statusfilter"); statusFilter.setFilterType("state"); TabFilterEntry textFilter = new TabFilterEntry(); textFilter.setKey("text"); textFilter.setInvertable(true); textFilter.setName("Textfiler"); textFilter.setFilterType("text"); TabSortEntry stateSort = new TabSortEntry(); stateSort.setKey("status"); stateSort.setName("Status"); TabSortEntry dateSort = new TabSortEntry(); dateSort.setKey("createdAt"); dateSort.setName("Datum"); TabSortEntry typeSort = new TabSortEntry(); typeSort.setKey("name"); typeSort.setName("Typ"); t = new TabConfig(); t.setKey("livedata"); t.setTitle("Live-Daten"); t.setIcon("livefeed"); t.setMainTab(false); // t.getFilterEntries().add(textFilter); list.add(t); t = new TabConfig(); t.setKey("dashboard"); t.setTitle("Aufträge"); t.setIcon("job"); t.setMainTab(true); t.getFilterEntries().add(textFilter); t.getFilterEntries().add(statusFilter); t.getSortEntries().add(stateSort); t.getSortEntries().add(dateSort); t.getSortEntries().add(typeSort); list.add(t); t = new TabConfig(); t.setKey("actions"); t.setTitle("Aktionen"); t.setIcon("action"); t.setMainTab(false); t.getFilterEntries().add(textFilter); t.getFilterEntries().add(statusFilter); t.getSortEntries().add(stateSort); t.getSortEntries().add(dateSort); t.getSortEntries().add(typeSort); list.add(t); return list; } }
a5ee4ed221460e1e11e3742f92751643a4aff878
6f55347e2a2c2e05921a0d2c15677473069a88e5
/app/src/main/java/com/volkangurbuz/stajtakip/Fragment/TeacherFragment.java
0e57956059ae9e6a0be153da1ae0b88fcad24356
[]
no_license
VolkanGurbuz/StajTakip
4c9cbe1cad3f777cc0b9e97c20b881139069a56b
215d243ffa60149ee97fefaecabaf76fc6bec114
refs/heads/master
2020-08-05T15:30:30.814260
2019-10-31T20:28:35
2019-10-31T20:28:35
212,596,909
2
1
null
2019-10-31T20:28:36
2019-10-03T14:10:26
Java
UTF-8
Java
false
false
855
java
package com.volkangurbuz.stajtakip.Fragment; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.volkangurbuz.stajtakip.R; /** A simple {@link Fragment} subclass. */ public class TeacherFragment extends Fragment { public static TeacherFragment INSTANCE = null; public TeacherFragment() { // Required empty public constructor } public static TeacherFragment getInstance() { if (INSTANCE == null) { INSTANCE = new TeacherFragment(); } return INSTANCE; } @Override public View onCreateView( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_teacher, container, false); } }
a7fe5e84a6247d774846587a816d8efd4842a918
09a2c65b4bb4b8bfb1590d395aa2cc93dbbe5d56
/CortexSE/jpf-symbc/src/examples/rjc/struct5.java
0779985122668a0b419b3f55040ea003ea126642
[]
no_license
nunomachado/cortex-tool
0399e0f40c5eeb21cdaa55e061e687884b347518
96cb758d3f0ab9f06ef3b924020fdc8c0ca9516a
refs/heads/master
2021-05-23T02:49:10.154302
2020-12-27T11:59:16
2020-12-27T11:59:16
49,576,792
9
5
null
null
null
null
UTF-8
Java
false
false
105
java
package rjc; public class struct5 { public double signal1 = 0; public double signal2 = 0; }
c44ea55fbdb4dd14acb864b64f0e6f2b51527ca4
05f1b9b7010b9558ef0d77477071b584ed59617d
/random-regress/old-versions/ILP14/journal-revision/proximity/src/java/kdl/prox/dbmgr/ColumnValueFilter.java
4fff397e32cfdf57a6912d377b4ea9323bc6e386
[ "Apache-2.0" ]
permissive
sfu-cl-lab/our-papers
5194920eea72b4d82a5c8f942dc203a2973b584b
65e366218e85ce49e6a03682e172f91065ab8b0f
refs/heads/master
2023-07-07T11:13:53.496207
2023-06-29T22:01:58
2023-06-29T22:01:58
74,601,085
0
2
null
null
null
null
UTF-8
Java
false
false
3,868
java
/** * $Id: ColumnValueFilter.java 3658 2007-10-15 16:29:11Z schapira $ * * Part of the open-source Proximity system * (see LICENSE for copyright and license information). * */ /* $Id */ package kdl.prox.dbmgr; import kdl.prox.util.Assert; import kdl.prox.util.MonetUtil; import org.apache.log4j.Logger; /** * Implements a filter based on the value of a column */ public class ColumnValueFilter implements Filter { String column; String expectedValue; ComparisonOperatorEnum operator; /** * Class-based static logger */ static Logger log = Logger.getLogger(ColumnValueFilter.class); /** * Full-arg constructor * * @param column * @param op * @param value */ public ColumnValueFilter(String column, ComparisonOperatorEnum op, String value) { Assert.stringNotEmpty(column, "Empty column"); Assert.notNull(value, "Null value"); this.column = column; this.operator = op; this.expectedValue = value; } /** * Shortcut: operator is EQ * * @param column * @param value */ public ColumnValueFilter(String column, String value) { this(column, ComparisonOperatorEnum.EQ, value); } /** * The operations to apply the filter */ public String getApplyCmd(NST onNST) { Assert.notNull(onNST, "Empty NST"); // do a select on the BAT that column NSTColumn theColumn = onNST.getNSTColumn(column); StringBuffer milSB = new StringBuffer(); // Generate MIL according to operator (EQ,NE, GE, LE, GT, LT) // Cannot use [=] op for EQ/NE because of it wouldn't allow to search for nil values // ( a=nil always returns nil --it's not defined) if (operator == ComparisonOperatorEnum.EQ) { milSB.append(theColumn.getBATName()); milSB.append(".uselect("); milSB.append(MonetUtil.delimitValue(expectedValue, theColumn.getType())); milSB.append(")"); } else if (operator == ComparisonOperatorEnum.NE) { milSB.append(theColumn.getBATName()); milSB.append(".kdiff("); milSB.append(theColumn.getBATName()); milSB.append(".uselect("); milSB.append(MonetUtil.delimitValue(expectedValue, theColumn.getType())); milSB.append("))"); } else if (operator == ComparisonOperatorEnum.LE) { milSB.append(theColumn.getBATName()); milSB.append(".uselect("); milSB.append(theColumn.getType().toString()); milSB.append("(nil),"); milSB.append(MonetUtil.delimitValue(expectedValue, theColumn.getType())); milSB.append(")"); } else if (operator == ComparisonOperatorEnum.GE) { milSB.append(theColumn.getBATName()); milSB.append(".uselect("); milSB.append(MonetUtil.delimitValue(expectedValue, theColumn.getType())); milSB.append(","); milSB.append(theColumn.getType().toString()); milSB.append("(nil))"); } else if (operator == ComparisonOperatorEnum.GT || operator == ComparisonOperatorEnum.LT) { milSB.append("["); milSB.append(operator == ComparisonOperatorEnum.GT ? ">" : "<"); milSB.append("]("); milSB.append(theColumn.getBATName()); milSB.append(", const "); milSB.append(MonetUtil.delimitValue(expectedValue, theColumn.getType())); milSB.append(").uselect(true)"); } milSB.append(""); return milSB.toString(); } /** * Returns a description of this filter in a way that can be used in * an MIL statement */ public String getMILDescription() { return column + "_" + operator.toString() + "_value"; } }
4a23ab9d2191ea65050e83698f9f1a36b045f8fa
2f35729d0aaff4acaca7a62c9cf2c4a218907e3e
/Simple Phone Book Project/MyConnection/Final Project New/Final Project/Final Project/app/src/main/java/com/afinal/group/myconnections/DataBaseHelper.java
c1b8e06ccb8b37da5b7f1df89fac815ec5aaac50
[]
no_license
namnguyen191/Android-Studio
d650cde2955564842b60aa006acb342d7c6920e8
ae08f46a262e6384711f6b70fc5491d62962e5c1
refs/heads/master
2020-04-22T12:39:50.501088
2019-02-12T19:42:27
2019-02-12T19:42:27
170,379,999
0
0
null
null
null
null
UTF-8
Java
false
false
8,115
java
package com.afinal.group.myconnections; import java.util.ArrayList; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.support.design.widget.TextInputLayout; import android.util.Log; public class DataBaseHelper extends SQLiteOpenHelper { // Database Name public static String DATABASE_NAME = "contact_database"; // Current version of database private static final int DATABASE_VERSION = 1; // Name of table private static final String TABLE_CONTACT = "contact"; // All fields used in database table private static final String KEY_FIRST_NAME = "first_name"; private static final String KEY_LAST_NAME = "last_name"; private static final String EMAIL = "email"; private static final String PHONE = "phone"; private static final String COMPANY = "company"; private static final String NOTE = "note"; public static String TAG = "my_tag"; // Client Table Create Query in this string private static final String CREATE_TABLE_CONTACT = "CREATE TABLE " + TABLE_CONTACT + "(" + KEY_FIRST_NAME + " TEXT," + KEY_LAST_NAME + " TEXT," + EMAIL + " TEXT ," + PHONE + " TEXT ," + COMPANY + " TEXT, " + NOTE + " TEXT, PRIMARY KEY (" + KEY_FIRST_NAME + ", " + KEY_LAST_NAME + "));"; public DataBaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } /** * This method is called by system if the database is accessed but not yet * created. */ @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATE_TABLE_CONTACT); // create client table } /** * This method is called when any modifications in database are done like * version is updated or database schema is changed */ @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(" DROP TABLE IF EXISTS " + CREATE_TABLE_CONTACT); // drop table if exists onCreate(db); } /** * This method is used to add client detail in client Table */ public long addContactDetail(Contact contact) { SQLiteDatabase db = this.getWritableDatabase(); // Creating content values ContentValues values = new ContentValues(); values.put(KEY_FIRST_NAME, contact.getFirstName()); values.put(KEY_LAST_NAME, contact.getLastName()); values.put(EMAIL, contact.getEmail()); values.put(PHONE, contact.getPhoneNo()); values.put(COMPANY, contact.getCompany()); values.put(NOTE, contact.getNote()); // insert row in client table long insert = db.insert(TABLE_CONTACT, null, values); return insert; } /** * This method is used to update particular client entry */ public int updateEntry(Contact contact, String firstName, String lastName) { SQLiteDatabase db = this.getWritableDatabase(); // Creating content values ContentValues values = new ContentValues(); values.put(KEY_FIRST_NAME, contact.getFirstName()); values.put(KEY_LAST_NAME, contact.getLastName()); values.put(EMAIL, contact.getEmail()); values.put(PHONE, contact.getPhoneNo()); values.put(COMPANY, contact.getCompany()); values.put(NOTE, contact.getNote()); //update row in client table base on client.is value return db.update(TABLE_CONTACT, values, KEY_FIRST_NAME + " = ?" + " AND " + KEY_LAST_NAME + " = ?", new String[] { firstName, lastName }); } /** * Used to delete particular client entry */ public void deleteEntry(String firstName, String lastName) { // delete row in client table based on id SQLiteDatabase db = this.getWritableDatabase(); db.delete(TABLE_CONTACT, KEY_FIRST_NAME + " = ? AND " + KEY_LAST_NAME + " = ?", new String[] { String.valueOf(firstName), String.valueOf(lastName) }); } /** * Used to get particular client details * * @param firstName * @param lastName */ public Contact getContact(String firstName, String lastName) { SQLiteDatabase db = this.getReadableDatabase(); String selectQuery = "SELECT * FROM " + TABLE_CONTACT + " WHERE " + KEY_FIRST_NAME + " = '" + firstName + "' AND " + KEY_LAST_NAME + " = '" + lastName + "'"; Log.d(TAG, selectQuery); Cursor c = db.rawQuery(selectQuery, null); if (c != null && c.getCount()>0) { c.moveToFirst(); Contact contact = new Contact(); contact.setFirstName(c.getString(c.getColumnIndex(KEY_FIRST_NAME))); contact.setLastName(c.getString(c.getColumnIndex(KEY_LAST_NAME))); contact.setPhoneNo(c.getString(c.getColumnIndex(PHONE))); contact.setEmail(c.getString(c.getColumnIndex(EMAIL))); contact.setCompany(c.getString(c.getColumnIndex(COMPANY))); contact.setNote(c.getString(c.getColumnIndex(NOTE))); return contact; } else return null; } /** * Used to get detail of entire database and save in array list of data type * Clients */ public List<Contact> getAllContactsList() { List<Contact> contactsArrayList = new ArrayList<Contact>(); String selectQuery = "SELECT * FROM " + TABLE_CONTACT; Log.d(TAG, selectQuery); SQLiteDatabase db = this.getReadableDatabase(); Cursor c = db.rawQuery(selectQuery, null); // looping through all rows and adding to list if (c.moveToFirst()) { do { Contact contact = new Contact(); contact.setFirstName(c.getString(c.getColumnIndex(KEY_FIRST_NAME))); contact.setLastName(c.getString(c.getColumnIndex(KEY_LAST_NAME))); contact.setPhoneNo(c.getString(c.getColumnIndex(PHONE))); contact.setEmail(c.getString(c.getColumnIndex(EMAIL))); contact.setCompany(c.getString(c.getColumnIndex(COMPANY))); contact.setNote(c.getString(c.getColumnIndex(NOTE))); // adding to Clients list contactsArrayList.add(contact); } while (c.moveToNext()); } return contactsArrayList; } public Boolean getContactnumber(String phoneNo) { SQLiteDatabase db = this.getReadableDatabase(); String selectQuery = "SELECT * FROM " + TABLE_CONTACT + " WHERE " + PHONE + " = '" + phoneNo + "'"; Log.d(TAG, selectQuery); Cursor c = db.rawQuery(selectQuery, null); return true; } public String checkEmailExist(String email){ String fullName = null; SQLiteDatabase db = this.getReadableDatabase(); String selectQuery = "SELECT first_name, last_name FROM " + TABLE_CONTACT + " WHERE " + EMAIL + " = '" + email + "'"; Log.d(TAG, selectQuery); Cursor c = db.rawQuery(selectQuery, null); if (c != null && c.getCount() > 0) { c.moveToFirst(); fullName = c.getString(c.getColumnIndex(KEY_FIRST_NAME)) + " " + c.getString(c.getColumnIndex(KEY_LAST_NAME)); } return fullName; } public String checkPhoneExist(String phone){ String fullName = null; SQLiteDatabase db = this.getReadableDatabase(); String selectQuery = "SELECT first_name, last_name FROM " + TABLE_CONTACT + " WHERE " + PHONE + " = '" + phone + "'"; Log.d(TAG, selectQuery); Cursor c = db.rawQuery(selectQuery, null); if (c != null && c.getCount() > 0) { c.moveToFirst(); fullName = c.getString(c.getColumnIndex(KEY_FIRST_NAME)) + " " + c.getString(c.getColumnIndex(KEY_LAST_NAME)); } return fullName; } }
4791058df6f6bf1aad8ccca308c3e4af923f3d72
85fe2cf32021d9a8eebe4b8a24e981ccf700be42
/GiveMeOffer/src/Graph/ShortestPath/WeightedGraph.java
fed0056d9072aa19f94109e2df2ec0cb64613188
[]
no_license
WanGeliang/QiuZhao
2cfba899a3a278c5adbf7c6f8238d5138c499510
67b8499b90fc69bfbeccdee171a564e697018cb7
refs/heads/master
2023-07-14T19:32:11.036637
2021-08-31T08:30:46
2021-08-31T08:30:46
401,629,998
1
0
null
null
null
null
UTF-8
Java
false
false
2,026
java
package Graph.ShortestPath; import java.io.File; import java.util.Map; import java.util.Scanner; import java.util.TreeMap; /** * @author Geliang * @date 2021-07-13 * @slogan 致敬大师,致敬未来的你! */ //赞时支持无向的带权图 public class WeightedGraph { // 定义顶点,定义边 public int v; public int e; public int weight; // 使用TreeMap来构建图 public TreeMap<Integer, Integer>[] adj; public WeightedGraph(String filename) { File file = new File(filename); try (Scanner sc = new Scanner(file)) { v = sc.nextInt(); adj = new TreeMap[v]; for (int i = 0; i < v; i++) { adj[i] = new TreeMap<Integer, Integer>(); } //根据图来构建边 e = sc.nextInt(); for (int i = 0; i < e; i++) { int a = sc.nextInt(); int b = sc.nextInt(); weight = sc.nextInt(); if (a == b || adj[a].containsKey(b)) throw new IllegalArgumentException(); adj[a].put(b, weight); adj[b].put(a, weight); } } catch (Exception e) { e.printStackTrace(); } } @Override public String toString() { StringBuilder sb = new StringBuilder(); // 输出最小生成树的表示 sb.append(String.format("V = %d, E = %d\n", v, e)); for (int i = 0; i < v; i++) { sb.append(String.format("%d : ", i)); for (Map.Entry<Integer, Integer> entry : adj[i].entrySet()) sb.append(String.format("(%d: %d) ", entry.getKey(), entry.getValue())); sb.append('\n'); } return sb.toString(); } public static void main(String[] args) { WeightedGraph graph = new WeightedGraph("D:\\develop_files\\Idea_Project_files\\myproject\\My_leetcode\\GiveMeOffer\\src\\Graph\\MinimumTreeSpanning\\g.txt"); System.out.println(graph); } }
41edd00c31def36b03bb64781afdeca65b4817a0
5086f40988432788ce39edab1f9351c55c28eb1c
/sudbrain/src/br/com/project/sudbrain/model/help/Sorteio.java
d7a7dd41b9610370f30885dcfb304bdddef25396
[]
no_license
evertoncastro/sudbrain
54c8c6ff9f03e653c53f2769e49202ad414c63f8
e2aa79e74b0152f9ad2e83ba7a9dc49bbad9833d
refs/heads/master
2016-08-11T06:45:55.618010
2015-06-01T05:08:09
2015-06-01T05:08:09
36,272,519
0
0
null
null
null
null
UTF-8
Java
false
false
1,529
java
package br.com.project.sudbrain.model.help; import java.io.Serializable; import java.util.Random; public class Sorteio implements Serializable { /** * */ private static final long serialVersionUID = 1L; private int sorteio = 0; private int imagemSorteio = 0; private boolean alternativa1 = true; private boolean alternativa2 = true; private boolean alternativa3 = true; private boolean alternativa4 = true; public Sorteio(){ Random gerador = new Random(); do{ this.sorteio = gerador.nextInt(4); }while(this.sorteio==0); } public int getSorteio() { return sorteio; } public void setSorteio(int sorteio) { this.sorteio = sorteio; } public boolean isAlternativa1() { return alternativa1; } public void setAlternativa1(boolean alternativa1) { this.alternativa1 = alternativa1; } public boolean isAlternativa2() { return alternativa2; } public void setAlternativa2(boolean alternativa2) { this.alternativa2 = alternativa2; } public boolean isAlternativa3() { return alternativa3; } public void setAlternativa3(boolean alternativa3) { this.alternativa3 = alternativa3; } public boolean isAlternativa4() { return alternativa4; } public void setAlternativa4(boolean alternativa4) { this.alternativa4 = alternativa4; } public int getImagemSorteio() { return imagemSorteio; } public void setImagemSorteio(int imagemSorteio) { this.imagemSorteio = imagemSorteio; } }
18e19a0f34895f9b9bb79cfd950bddbeb715e588
b886c5033ae9303ac679d8f1c365b8b20d872f22
/Talantra/src/com/wraithavens/conquest/Math/Vector.java
5a97fee78dc3a335b3cd4dd184c174d130c36aab
[ "MIT" ]
permissive
TheDudeFromCI/Talantra-Old
3a725323c1ccfb96500b080094fe5fee775169f6
0dc8ce177f89ec0934ed1b0cf8444ae23a3e7131
refs/heads/master
2021-01-18T04:59:35.183317
2015-10-29T20:26:55
2015-10-29T20:26:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
317
java
package com.wraithavens.conquest.Math; import java.nio.FloatBuffer; abstract class Vector{ public abstract float lengthSquared(); public abstract Vector load(FloatBuffer buf); public abstract Vector negate(); public abstract Vector scale(float scale); public abstract Vector store(FloatBuffer buf); }
[ "thedudefromci@Encarta" ]
thedudefromci@Encarta
1c2b03e8521f1d3ce9b353082554752288df6c87
b4506a3f99547bbe0968778c6440b5b3e7ca81a2
/app/src/main/java/com/roka/rokaviewpicker/OnPickerScrollChangeListener.java
8356d8a5aa01f270137606265cdf775a52a3447e
[ "Apache-2.0" ]
permissive
roka88/rokaviewpicker
c103222655c81b90c6df7c5c167ca626f31fc89e
a1ef7b510689603623fb11b71e7367ae5d6f9397
refs/heads/master
2021-01-12T00:56:40.089952
2017-02-23T08:52:17
2017-02-23T08:52:17
78,321,022
1
0
null
null
null
null
UTF-8
Java
false
false
183
java
package com.roka.rokaviewpicker; /** * Created by roka on 2016. 12. 22.. */ public interface OnPickerScrollChangeListener { void onPickerScrollChangeListener(int x, int y); }
acaf67f6abe7a69a7e1673aa1d654f376b96f1f0
e68633bc1f19bdb8a044607a300e62005c59482d
/src/main/java/chat/ClientMain2.java
e947475bea36df40c8dd5c8722d9a04a4c771187
[ "MIT" ]
permissive
nisioka/java-grpc-basics
48d2232729c06a3c754f745b8c5e8afaff9ba80f
395c72b1e4bad27148924639546265b3322dd2e9
refs/heads/master
2020-05-27T18:17:56.798359
2019-06-09T23:56:53
2019-06-09T23:56:53
188,739,596
0
0
MIT
2019-06-09T15:06:14
2019-05-26T22:57:27
Java
UTF-8
Java
false
false
1,830
java
package chat; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; import io.grpc.stub.StreamObserver; import java.util.Objects; import java.util.Scanner; import java.util.concurrent.CountDownLatch; /** * クライアントからサーバへリクエストを送る。 */ public class ClientMain2 { public static void main(String[] args) throws InterruptedException { final int portNumber = 50051; ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", portNumber) .usePlaintext(true) // 簡単のためサーバ証明書なしのローカル通信とする。 .build(); var stub = ChatServiceGrpc.newStub(channel); // 非同期処理の結果を待つLatch。 CountDownLatch client = new CountDownLatch(1); // ファイル名をリクエストする。 var requestSender = stub.connect(new StreamObserver<Chat.Post>() { @Override public void onNext(Chat.Post value) { // レスポンスを表示する。 System.out.println("[" + value.getName() + "] " + value.getMessage()); } @Override public void onError(Throwable t) { t.printStackTrace(); } @Override public void onCompleted() { client.countDown(); } }); Scanner scanner = new Scanner(System.in); String input; while ((input = scanner.nextLine()) != null) { if (Objects.equals(input, ":quit")) { requestSender.onCompleted(); return; } requestSender.onNext(Chat.Post.newBuilder().setName("USER_B").setMessage(input).build()); } client.await(); } }
0370284d19ab8be4936b93d58f4f5159373868e5
05e969b5493bf839503add4bb5afc95fe9e32c87
/src/cit/group10/qlGiangvien/TeacherInfo/WindowImportData.java
9ea2bf1667878d49c0cce4f5b8c110466bc749fb
[]
no_license
nlnbich/qlGiangVien
97e99bbfbadcd7b535dc804b2bdd717c84a9891b
ef56646783893f556496c5b359b95e578e041dbe
refs/heads/master
2021-01-17T15:16:26.427048
2012-03-27T01:57:57
2012-03-27T01:57:57
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,330
java
package cit.group10.qlGiangvien.TeacherInfo ; import cit.group10.qlGiangvien.constants.Constants; import cit.group10.qlGiangvien.widgets.*; import com.vaadin.data.util.BeanItemContainer; import com.vaadin.terminal.Sizeable; import com.vaadin.ui.*; public class WindowImportData extends Window implements Constants { private static final long serialVersionUID = 1L; rightContentImportData rContent ; public WindowImportData() { setCaption("dang ky nghien cuu");//Constants.USER_CAPTION) ; HorizontalLayout mainLayout = new HorizontalLayout() ; mainLayout.setImmediate(false); mainLayout.setWidth(Constants.WIDTH_MAX, Sizeable.UNITS_PIXELS); mainLayout.setMargin(false); mainLayout.setSpacing(true); rContent = new rightContentImportData() ; rContent.setWidth("100%") ; mainLayout.addComponent(new leftSide()); mainLayout.addComponent(rContent) ; mainLayout.setExpandRatio(rContent, 1.0f) ; VerticalLayout v = new VerticalLayout() ; v.setWidth("100%") ; v.setStyleName("bl-mainContent") ; v.addComponent(mainLayout) ; v.setComponentAlignment(mainLayout, Alignment.MIDDLE_CENTER) ; addComponent(new topLogin()) ; addComponent(new topPanel()) ; addComponent(new mainMenu()) ; addComponent(v) ; addComponent(new bottom()) ; } }
8aaa6392fcf045a1e9affe13b250d822004bb9f8
6942aa9d5cd07e4d2aff775ae8fc75f152d1c6ad
/sdk/push/src/androidTest/java/com/app/push/ExampleInstrumentedTest.java
b3734af07fd28ce2f1c146b0168a0da41b76be96
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
qxf323/FastAndroid
25d67ce7af660f9fbecff09c420cc6c156e53cf4
480d056ac1b6069d0a02aea0b28db0599d21dbea
refs/heads/master
2020-03-06T14:26:20.395880
2018-03-21T09:34:06
2018-03-21T09:34:06
null
0
0
null
null
null
null
UTF-8
Java
false
false
751
java
package com.app.push; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() throws Exception { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.app.push", appContext.getPackageName()); } }
dd553685413fee06fdec25b9a364587b52e726e9
9e6c2765abda9ab7d017a19ae6b3637c56bb129f
/android/app/src/main/java/com/testcomponent/MainActivity.java
5be363d90f24ae422c265d8a4494ae8c6becee53
[]
no_license
MichelCreatingDev/React-Native-Circle-Step-Progress
ed71c46a10fe72cbe9403a4c41f0d435972c88bb
3895356f7c11997af29944473b9062027f63fb53
refs/heads/master
2021-01-20T04:26:08.512558
2017-04-28T09:39:37
2017-04-28T09:39:37
89,690,882
1
0
null
null
null
null
UTF-8
Java
false
false
458
java
package com.testcomponent; import com.facebook.react.ReactActivity; import com.horcrux.svg.SvgPackage; import com.BV.LinearGradient.LinearGradientPackage; public class MainActivity extends ReactActivity { /** * Returns the name of the main component registered from JavaScript. * This is used to schedule rendering of the component. */ @Override protected String getMainComponentName() { return "TestComponent"; } }
0a5012f4c9bb543d6a16c8034ebf6f370626b200
efeb6745a06e85c58fb9ad1c5d49e2a6f9a1f089
/src/main/java/com/monsource/bis/account/model/District.java
5c6539b785942b66bb44a409b755c8834c4840ee
[]
no_license
nasanjargal-b/bis
8fc9807d2e3fbb8c9b8cfaba3487c617c10c5eb1
d7a2d8183fb2fd65993cbe37de1ba38283360ed5
refs/heads/master
2016-09-05T09:42:40.496527
2014-08-28T18:03:17
2014-08-28T18:03:17
null
0
0
null
null
null
null
UTF-8
Java
false
false
579
java
package com.monsource.bis.account.model; /** * Created by nyamaa on 6/3/14. */ public class District { private Integer id; private Integer cityId; private String name; public Integer getCityId() { return cityId; } public void setCityId(Integer cityId) { this.cityId = cityId; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
cd385a4a6e5f023ebe056c91297b0989ed34cc7c
6f29f86a92cf3b5aeb3dd2f0549b6cfef5171bc7
/gwtexample-master/src/main/java/com/hellogwt/client/HelloGWT.java
0b42dd19e51a975f1a26df011155faf69b423291
[]
no_license
i1yassss/Homeworks
888a8af3d650404a05c85c4737e0690a805fd4bf
b0aa8e125623a746d0c51d4282002ba0b25ec28d
refs/heads/master
2021-01-20T20:45:25.414746
2016-05-31T21:33:07
2016-05-31T21:33:07
60,115,954
0
0
null
null
null
null
UTF-8
Java
false
false
5,592
java
package com.hellogwt.client; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.Window; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.*; import com.hellogwt.client.service.GreetingService; import com.hellogwt.client.service.GreetingServiceAsync; import com.hellogwt.shared.domain.Greeting; import java.util.List; public class HelloGWT implements EntryPoint { private GreetingServiceAsync greetingService = GWT.create(GreetingService.class); private HorizontalPanel authorPanel = new HorizontalPanel(); private HorizontalPanel textPanel = new HorizontalPanel(); private HorizontalPanel editPanel = new HorizontalPanel(); private Label authorLabel = new Label("Author:"); private Label textLabel = new Label("Text:"); private TextBox authorTextBox = new TextBox(); private TextBox textTextBox = new TextBox(); private Button addButton = new Button("Add"); private Button updateButton = new Button("Update"); private Button deleteButton = new Button("Delete"); private FlexTable greetingsFlexTable = new FlexTable(); @Override public void onModuleLoad() { initWidgets(); initHandlers(); refreshGreetingsTable(); } private void initWidgets() { authorLabel.setWidth("50"); authorTextBox.setWidth("100"); authorPanel.add(authorLabel); authorPanel.add(authorTextBox); textLabel.setWidth("50"); textTextBox.setWidth("100"); textPanel.add(textLabel); textPanel.add(textTextBox); addButton.setWidth("50"); updateButton.setWidth("50"); deleteButton.setWidth("50"); editPanel.add(addButton); editPanel.add(updateButton); editPanel.add(deleteButton); RootPanel.get().add(authorPanel); RootPanel.get().add(textPanel); RootPanel.get().add(editPanel); RootPanel.get().add(greetingsFlexTable); } private void initHandlers() { final AsyncCallback<Void> callback = new AsyncCallback<Void>() { @Override public void onFailure(Throwable caught) { Window.alert("ERROR: Cannot edit greetings!"); } @Override public void onSuccess(Void result) { refreshGreetingsTable(); } }; addButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent clickEvent) { if (!authorTextBox.getText().isEmpty() && !textTextBox.getText().isEmpty()) { greetingService.getGreeting(textTextBox.getText(), new AsyncCallback<Greeting>() { @Override public void onFailure(Throwable caught) { Window.alert("ERROR: Cannot find greeting!"); } @Override public void onSuccess(Greeting result) { if (result == null) { greetingService.addGreeting(authorTextBox.getText(), textTextBox.getText(), callback); } else { Window.alert("Greeting already exists!"); } } }); } else { Window.alert("\"Author\" and \"Text\" fields cannot be empty!"); } } }); updateButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { if (!authorTextBox.getText().isEmpty() && !textTextBox.getText().isEmpty()) { greetingService.updateGreeting(authorTextBox.getText(), textTextBox.getText(), callback); } else { Window.alert("\"Author\" and \"Text\" fields cannot be empty!"); } } }); deleteButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { greetingService.deleteGreeting(textTextBox.getText(), callback); } }); } private void refreshGreetingsTable() { greetingService.getGreetings(new AsyncCallback<List<Greeting>>() { @Override public void onFailure(Throwable throwable) { Window.alert("ERROR: Cannot load greetings!"); } @Override public void onSuccess(List<Greeting> greetings) { fillGreetingsTable(greetings); } }); } private void fillGreetingsTable(List<Greeting> greetings) { greetingsFlexTable.removeAllRows(); greetingsFlexTable.setText(0, 0, "Author"); greetingsFlexTable.setText(0, 1, "Text"); for (Greeting greeting : greetings) { int row = greetingsFlexTable.getRowCount(); greetingsFlexTable.setText(row, 0, greeting.getAuthor()); greetingsFlexTable.setText(row, 1, greeting.getText()); } } }
fe021b2bfc33a820b23c10b7f5802373a9eac27c
e658d1c3e94ee47afc07eaa8565fc013c6b9b495
/app/src/androidTest/java/com/app/bc/myapplication/ExampleInstrumentedTest.java
ec0475a50283276fc90984455ec40897bdcf02aa
[]
no_license
hoangmdoan/BCConnect
b46ddb2eb8728f7cb09e1e4d9f34b78854434af8
6e7d521efd47412a814156bdb2f1be0be09b2524
refs/heads/master
2020-04-03T00:41:52.587584
2020-02-28T16:52:38
2020-02-28T16:52:38
154,906,081
0
0
null
null
null
null
UTF-8
Java
false
false
732
java
package com.app.bc.myapplication; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getTargetContext(); assertEquals("com.app.bc.myapplication", appContext.getPackageName()); } }
6b828db4ea0bcc2835305c06dec4fb6b453b6763
304e3b0af707e081cb79f55f863bbac06986c796
/jdom/build/samples/DescendantDemo.java
e6bea0291f05bb52fc49217f102d724a08228583
[ "LicenseRef-scancode-jdom" ]
permissive
rlm33/TPV-RASS
b4fc62bd38fc393e473760afbbb5113501207442
e302190397542073a1fdda8890e5d2f4403e721a
refs/heads/master
2021-01-17T11:59:40.447239
2011-05-31T20:16:06
2011-05-31T20:16:06
1,603,461
4
0
null
null
null
null
UTF-8
Java
false
false
5,025
java
/*-- $Id: DescendantDemo.java,v 1.5 2007/11/10 05:36:01 jhunter Exp $ Copyright (C) 2000-2007 Jason Hunter & Brett McLaughlin. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions, and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions, and the disclaimer that follows these conditions in the documentation and/or other materials provided with the distribution. 3. The name "JDOM" must not be used to endorse or promote products derived from this software without prior written permission. For written permission, please contact <request_AT_jdom_DOT_org>. 4. Products derived from this software may not be called "JDOM", nor may "JDOM" appear in their name, without prior written permission from the JDOM Project Management <request_AT_jdom_DOT_org>. In addition, we request (but do not require) that you include in the end-user documentation provided with the redistribution and/or in the software itself an acknowledgement equivalent to the following: "This product includes software developed by the JDOM Project (http://www.jdom.org/)." Alternatively, the acknowledgment may be graphical using the logos available at http://www.jdom.org/images/logos. THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE JDOM AUTHORS OR THE PROJECT CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. This software consists of voluntary contributions made by many individuals on behalf of the JDOM Project and was originally created by Jason Hunter <jhunter_AT_jdom_DOT_org> and Brett McLaughlin <brett_AT_jdom_DOT_org>. For more information on the JDOM Project, please see <http://www.jdom.org/>. */ import java.io.*; import java.util.*; import org.jdom.*; import org.jdom.filter.ElementFilter; import org.jdom.input.*; import org.jdom.output.*; /** * Demonstrates the use of {@link Parent#getDescendants}. */ public class DescendantDemo { public static void main(String[] args) throws Exception { if (args.length != 1) { System.err.println("Usage: java DescendantDemo [web.xml]"); return; } SAXBuilder builder = new SAXBuilder(); Document doc = builder.build(args[0]); System.out.println("All content:"); Iterator itr = doc.getDescendants(); while (itr.hasNext()) { Content c = (Content) itr.next(); System.out.println(c); } System.out.println(); System.out.println("Only elements:"); itr = doc.getDescendants(new ElementFilter()); while (itr.hasNext()) { Content c = (Content) itr.next(); System.out.println(c); } System.out.println(); System.out.println("Everything that's not an element:"); itr = doc.getDescendants(new ElementFilter().negate()); while (itr.hasNext()) { Content c = (Content) itr.next(); System.out.println(c); } System.out.println(); System.out.println("Only elements with localname of servlet:"); itr = doc.getDescendants(new ElementFilter("servlet")); while (itr.hasNext()) { Content c = (Content) itr.next(); System.out.println(c); } System.out.println(); System.out.println( "Only elements with localname of servlet-name or servlet-class:"); itr = doc.getDescendants(new ElementFilter("servlet-name") .or(new ElementFilter("servlet-class"))); while (itr.hasNext()) { Content c = (Content) itr.next(); System.out.println(c); } System.out.println(); System.out.println("Remove elements with localname of servlet:"); itr = doc.getDescendants(new ElementFilter("servlet")); while (itr.hasNext()) { itr.next(); itr.remove(); } XMLOutputter outp = new XMLOutputter(); outp.output(doc, System.out); } }
eb324a863cc6c75e437fb66d2ad217317a8475b9
6baf1fe00541560788e78de5244ae17a7a2b375a
/hollywood/com.oculus.vrshell-VrShell/sources/com/oculus/android/exoplayer2/extractor/mp3/ConstantBitrateSeeker.java
33553db709aa3dfdd84035d30b6b34fde131bf0b
[]
no_license
phwd/quest-tracker
286e605644fc05f00f4904e51f73d77444a78003
3d46fbb467ba11bee5827f7cae7dfeabeb1fd2ba
refs/heads/main
2023-03-29T20:33:10.959529
2021-04-10T22:14:11
2021-04-10T22:14:11
357,185,040
4
2
null
2021-04-12T12:28:09
2021-04-12T12:28:08
null
UTF-8
Java
false
false
2,654
java
package com.oculus.android.exoplayer2.extractor.mp3; import com.oculus.android.exoplayer2.C; import com.oculus.android.exoplayer2.extractor.MpegAudioHeader; import com.oculus.android.exoplayer2.extractor.SeekMap; import com.oculus.android.exoplayer2.extractor.SeekPoint; import com.oculus.android.exoplayer2.extractor.mp3.Mp3Extractor; import com.oculus.android.exoplayer2.util.Util; /* access modifiers changed from: package-private */ public final class ConstantBitrateSeeker implements Mp3Extractor.Seeker { private static final int BITS_PER_BYTE = 8; private final int bitrate; private final long dataSize; private final long durationUs; private final long firstFramePosition; private final int frameSize; public ConstantBitrateSeeker(long j, long j2, MpegAudioHeader mpegAudioHeader) { this.firstFramePosition = j2; this.frameSize = mpegAudioHeader.frameSize; this.bitrate = mpegAudioHeader.bitrate; if (j == -1) { this.dataSize = -1; this.durationUs = C.TIME_UNSET; return; } this.dataSize = j - j2; this.durationUs = getTimeUs(j); } @Override // com.oculus.android.exoplayer2.extractor.SeekMap public boolean isSeekable() { return this.dataSize != -1; } @Override // com.oculus.android.exoplayer2.extractor.SeekMap public SeekMap.SeekPoints getSeekPoints(long j) { long j2 = this.dataSize; if (j2 == -1) { return new SeekMap.SeekPoints(new SeekPoint(0, this.firstFramePosition)); } int i = this.frameSize; long constrainValue = Util.constrainValue((((((long) this.bitrate) * j) / 8000000) / ((long) i)) * ((long) i), 0, j2 - ((long) i)); long j3 = this.firstFramePosition + constrainValue; long timeUs = getTimeUs(j3); SeekPoint seekPoint = new SeekPoint(timeUs, j3); if (timeUs < j) { long j4 = this.dataSize; int i2 = this.frameSize; if (constrainValue != j4 - ((long) i2)) { long j5 = j3 + ((long) i2); return new SeekMap.SeekPoints(seekPoint, new SeekPoint(getTimeUs(j5), j5)); } } return new SeekMap.SeekPoints(seekPoint); } @Override // com.oculus.android.exoplayer2.extractor.mp3.Mp3Extractor.Seeker public long getTimeUs(long j) { return ((Math.max(0L, j - this.firstFramePosition) * C.MICROS_PER_SECOND) * 8) / ((long) this.bitrate); } @Override // com.oculus.android.exoplayer2.extractor.SeekMap public long getDurationUs() { return this.durationUs; } }
4180eb57bdc84c80d7ce895396e6bb28300a523b
f800b206ed9d053d7b71c85a241b55fba07249be
/src/main/java/mu/mcbc/mcshares/web/rest/errors/LoginAlreadyUsedException.java
cdb357fde6299351d08bfeec39c9fb7bd0bec7b5
[]
no_license
Veeresh11/McShare
4bf248f40d12340dd5021bfc24073e458f2f0544
ed89d2c16ec90072f464e95f41826627ea3cc2e0
refs/heads/main
2023-07-05T00:00:49.926631
2021-08-29T16:30:27
2021-08-29T16:30:27
401,084,204
0
0
null
null
null
null
UTF-8
Java
false
false
336
java
package mu.mcbc.mcshares.web.rest.errors; public class LoginAlreadyUsedException extends BadRequestAlertException { private static final long serialVersionUID = 1L; public LoginAlreadyUsedException() { super(ErrorConstants.LOGIN_ALREADY_USED_TYPE, "Login name already used!", "userManagement", "userexists"); } }
3958bc01956f76a330e61e618641c3aa830acd51
ee1244b10de45679f053293e366f192af307be74
/sources/com/p001a/p002a/p003a/C0239q.java
0ec87b316f7dcf809e5e2aeeb9e3d129889f1fb3
[]
no_license
scarletstuff/Turbogram
a086e50b3f4d7036526075199616682a0d7c9c45
21b8862573953add9260f1eb586f0985d2c71e8e
refs/heads/master
2021-09-23T14:34:23.323880
2018-09-24T17:48:43
2018-09-24T17:48:43
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,563
java
package com.p001a.p002a.p003a; /* renamed from: com.a.a.a.q */ public class C0239q { /* renamed from: a */ public static final C0239q f360a = new C0240a(true); /* renamed from: b */ public static final C0239q f361b = new C0240a(false); /* renamed from: c */ private boolean f362c; /* renamed from: d */ private Long f363d; /* renamed from: e */ private Integer f364e; /* renamed from: f */ private boolean f365f = false; /* renamed from: com.a.a.a.q$a */ static class C0240a extends C0239q { public C0240a(boolean z) { super(z); } /* renamed from: a */ public void mo361a(Long l) { throw new IllegalStateException("This object is immutable. Create a new one using the constructor."); } } public C0239q(boolean z) { this.f362c = z; } /* renamed from: a */ public static C0239q m545a(int i, long j) { C0239q c0239q = new C0239q(true); c0239q.mo361a(Long.valueOf(((long) Math.pow(2.0d, (double) Math.max(0, i - 1))) * j)); return c0239q; } /* renamed from: a */ public void mo361a(Long l) { this.f363d = l; } /* renamed from: a */ public boolean m547a() { return this.f362c; } /* renamed from: b */ public Long m548b() { return this.f363d; } /* renamed from: c */ public Integer m549c() { return this.f364e; } /* renamed from: d */ public boolean m550d() { return this.f365f; } }
df21353323529246f61d62c0a7f3f6d141ef5b66
0308ca5b152a082c1a206a1a136fd45e79b48143
/usvao/prototype/single-signon/eventtide/trunk/src/org/nvo/eventtide/client/util/Similar.java
80365828cb2afbc4e91a27b50bad2414d0c10d04
[]
no_license
Schwarzam/usvirtualobservatory
b609bf21a09c187b70e311a4c857516284049c31
53fe6c14cc9312d048326acfa25377e3eac59858
refs/heads/master
2022-03-28T23:38:58.847018
2019-11-27T16:05:47
2019-11-27T16:05:47
null
0
0
null
null
null
null
UTF-8
Java
false
false
339
java
package org.nvo.eventtide.client.util; /** Adds a method <tt>isSimilar()</tt> that is like <tt>equals()</tt> but messier. * For example, two objects may claim to be similar if they are of the same class * and have the same database ID, even if their properties differ. */ public interface Similar { boolean isSimilar(Object o); }
[ "usvirtualobservatory@5a1e9bf7-f4d4-f7d4-5b89-e7d39643c4b5" ]
usvirtualobservatory@5a1e9bf7-f4d4-f7d4-5b89-e7d39643c4b5
683531af32bcbaf2608ff16a4adc9b7dd2740340
ca3bc4c8c68c15c961098c4efb2e593a800fe365
/TableToMyibatisUtf-8/file/com/neusoft/crm/api/cpc/prod/data/FuncCompDO.java
aa56397d3590acd302e8c13632f7ceeaa4620d47
[]
no_license
fansq-j/fansq-summary
211b01f4602ceed077b38bb6d2b788fcd4f2c308
00e838843e6885135eeff1eb1ac95d0553fc36ea
refs/heads/master
2022-12-17T01:18:34.323774
2020-01-14T06:57:24
2020-01-14T06:57:24
214,321,994
0
0
null
2022-11-17T16:20:29
2019-10-11T02:02:23
Java
UTF-8
Java
false
false
5,150
java
package com.neusoft.crm.api.cpc.prod.data; import com.neusoft.crm.common.persistence.BaseDO; import com.neusoft.crm.common.utils.SeqUtils; /** * @实体描述:指系统内的系统功能菜单的最小功能单元及组件。 * @实体表 :FUNC_COMP */ public class FuncCompDO extends BaseDO{ /** *主键对应的序列名称 */ public static final String ID_SEQ = "FUNC_COMP_S"; /** * 模块组件标识,主键 */ public java.lang.Integer compId; /** * 模块组件名称 */ public java.lang.String compName; /** * 模块组件类型,LOVB=STF-C-0014。 */ public java.lang.String compType; /** * 模块组件描述 */ public java.lang.String compDesc; /** * 模块组件URL链接地址 */ public java.lang.String urlAddr; /** * 菜单标识,主键 */ public java.lang.Integer menuId; /** * 模块组件状态 */ public java.lang.String statusCd; /** * 模块组件状态修改时间 */ public java.util.Date statusDate; /** * 创建时间 */ public java.util.Date createDate; /** * 创建人 */ public java.lang.Long createStaff; /** * 修改时间 */ public java.util.Date updateDate; /** * 修改人 */ public java.lang.Long updateStaff; /** * 设置 模块组件标识,主键 */ public void setCompId(java.lang.Integer compId) { this.compId = compId; } /** * 获取 模块组件标识,主键 */ public java.lang.Integer getCompId() { return this.compId; } /** * 设置主键,并返回主键ID */ public java.lang.Integer doCreateId(){ this.compId = SeqUtils.createIntegerId(ID_SEQ); return this.compId; } /** * 静态方法-生成主键ID */ public static final java.lang.Integer createId(){ return SeqUtils.createIntegerId(ID_SEQ); } /** * 设置 模块组件名称 */ public void setCompName(java.lang.String compName) { this.compName = compName; } /** * 获取 模块组件名称 */ public java.lang.String getCompName() { return this.compName; } /** * 设置 模块组件类型,LOVB=STF-C-0014。 */ public void setCompType(java.lang.String compType) { this.compType = compType; } /** * 获取 模块组件类型,LOVB=STF-C-0014。 */ public java.lang.String getCompType() { return this.compType; } /** * 设置 模块组件描述 */ public void setCompDesc(java.lang.String compDesc) { this.compDesc = compDesc; } /** * 获取 模块组件描述 */ public java.lang.String getCompDesc() { return this.compDesc; } /** * 设置 模块组件URL链接地址 */ public void setUrlAddr(java.lang.String urlAddr) { this.urlAddr = urlAddr; } /** * 获取 模块组件URL链接地址 */ public java.lang.String getUrlAddr() { return this.urlAddr; } /** * 设置 菜单标识,主键 */ public void setMenuId(java.lang.Integer menuId) { this.menuId = menuId; } /** * 获取 菜单标识,主键 */ public java.lang.Integer getMenuId() { return this.menuId; } /** * 设置 模块组件状态 */ public void setStatusCd(java.lang.String statusCd) { this.statusCd = statusCd; } /** * 获取 模块组件状态 */ public java.lang.String getStatusCd() { return this.statusCd; } /** * 设置 模块组件状态修改时间 */ public void setStatusDate(java.util.Date statusDate) { this.statusDate = statusDate; } /** * 获取 模块组件状态修改时间 */ public java.util.Date getStatusDate() { return this.statusDate; } /** * 设置 创建时间 */ public void setCreateDate(java.util.Date createDate) { this.createDate = createDate; } /** * 获取 创建时间 */ public java.util.Date getCreateDate() { return this.createDate; } /** * 设置 创建人 */ public void setCreateStaff(java.lang.Long createStaff) { this.createStaff = createStaff; } /** * 获取 创建人 */ public java.lang.Long getCreateStaff() { return this.createStaff; } /** * 设置 修改时间 */ public void setUpdateDate(java.util.Date updateDate) { this.updateDate = updateDate; } /** * 获取 修改时间 */ public java.util.Date getUpdateDate() { return this.updateDate; } /** * 设置 修改人 */ public void setUpdateStaff(java.lang.Long updateStaff) { this.updateStaff = updateStaff; } /** * 获取 修改人 */ public java.lang.Long getUpdateStaff() { return this.updateStaff; } }
ce47b4ebd0117c4d9055eccf50855a824d53224b
3163f929594c96efa353eff117885c781a539789
/src/main/java/com/sudip/avro/ModuleInstance.java
e415c00a73806b13d1182220b939c999a98f8fc2
[]
no_license
dinku/avro-projects
fe81d2bc27c1a7500d2785c68a16ce479ceb45e0
7cd68378ce6062c4337afb311f5b39e59589f6ad
refs/heads/master
2016-09-13T20:02:03.527849
2016-05-18T21:54:26
2016-05-18T21:54:26
59,154,038
0
0
null
null
null
null
UTF-8
Java
false
false
8,539
java
/** * Autogenerated by Avro * * DO NOT EDIT DIRECTLY */ package com.sudip.avro; @SuppressWarnings("all") @org.apache.avro.specific.AvroGenerated public class ModuleInstance extends org.apache.avro.specific.SpecificRecordBase implements org.apache.avro.specific.SpecificRecord { public static final org.apache.avro.Schema SCHEMA$ = new org.apache.avro.Schema.Parser().parse("{\"type\":\"record\",\"name\":\"ModuleInstance\",\"namespace\":\"com.sudip.avro\",\"fields\":[{\"name\":\"id\",\"type\":\"string\"},{\"name\":\"eventTime\",\"type\":\"long\"},{\"name\":\"parentApp\",\"type\":{\"type\":\"record\",\"name\":\"ApplicationInstance\",\"fields\":[{\"name\":\"id\",\"type\":\"string\"},{\"name\":\"eventTime\",\"type\":\"long\"}]}}]}"); public static org.apache.avro.Schema getClassSchema() { return SCHEMA$; } @Deprecated public java.lang.CharSequence id; @Deprecated public long eventTime; @Deprecated public com.sudip.avro.ApplicationInstance parentApp; /** * Default constructor. Note that this does not initialize fields * to their default values from the schema. If that is desired then * one should use <code>newBuilder()</code>. */ public ModuleInstance() {} /** * All-args constructor. */ public ModuleInstance(java.lang.CharSequence id, java.lang.Long eventTime, com.sudip.avro.ApplicationInstance parentApp) { this.id = id; this.eventTime = eventTime; this.parentApp = parentApp; } public org.apache.avro.Schema getSchema() { return SCHEMA$; } // Used by DatumWriter. Applications should not call. public java.lang.Object get(int field$) { switch (field$) { case 0: return id; case 1: return eventTime; case 2: return parentApp; default: throw new org.apache.avro.AvroRuntimeException("Bad index"); } } // Used by DatumReader. Applications should not call. @SuppressWarnings(value="unchecked") public void put(int field$, java.lang.Object value$) { switch (field$) { case 0: id = (java.lang.CharSequence)value$; break; case 1: eventTime = (java.lang.Long)value$; break; case 2: parentApp = (com.sudip.avro.ApplicationInstance)value$; break; default: throw new org.apache.avro.AvroRuntimeException("Bad index"); } } /** * Gets the value of the 'id' field. */ public java.lang.CharSequence getId() { return id; } /** * Sets the value of the 'id' field. * @param value the value to set. */ public void setId(java.lang.CharSequence value) { this.id = value; } /** * Gets the value of the 'eventTime' field. */ public java.lang.Long getEventTime() { return eventTime; } /** * Sets the value of the 'eventTime' field. * @param value the value to set. */ public void setEventTime(java.lang.Long value) { this.eventTime = value; } /** * Gets the value of the 'parentApp' field. */ public com.sudip.avro.ApplicationInstance getParentApp() { return parentApp; } /** * Sets the value of the 'parentApp' field. * @param value the value to set. */ public void setParentApp(com.sudip.avro.ApplicationInstance value) { this.parentApp = value; } /** Creates a new ModuleInstance RecordBuilder */ public static com.sudip.avro.ModuleInstance.Builder newBuilder() { return new com.sudip.avro.ModuleInstance.Builder(); } /** Creates a new ModuleInstance RecordBuilder by copying an existing Builder */ public static com.sudip.avro.ModuleInstance.Builder newBuilder(com.sudip.avro.ModuleInstance.Builder other) { return new com.sudip.avro.ModuleInstance.Builder(other); } /** Creates a new ModuleInstance RecordBuilder by copying an existing ModuleInstance instance */ public static com.sudip.avro.ModuleInstance.Builder newBuilder(com.sudip.avro.ModuleInstance other) { return new com.sudip.avro.ModuleInstance.Builder(other); } /** * RecordBuilder for ModuleInstance instances. */ public static class Builder extends org.apache.avro.specific.SpecificRecordBuilderBase<ModuleInstance> implements org.apache.avro.data.RecordBuilder<ModuleInstance> { private java.lang.CharSequence id; private long eventTime; private com.sudip.avro.ApplicationInstance parentApp; /** Creates a new Builder */ private Builder() { super(com.sudip.avro.ModuleInstance.SCHEMA$); } /** Creates a Builder by copying an existing Builder */ private Builder(com.sudip.avro.ModuleInstance.Builder other) { super(other); if (isValidValue(fields()[0], other.id)) { this.id = data().deepCopy(fields()[0].schema(), other.id); fieldSetFlags()[0] = true; } if (isValidValue(fields()[1], other.eventTime)) { this.eventTime = data().deepCopy(fields()[1].schema(), other.eventTime); fieldSetFlags()[1] = true; } if (isValidValue(fields()[2], other.parentApp)) { this.parentApp = data().deepCopy(fields()[2].schema(), other.parentApp); fieldSetFlags()[2] = true; } } /** Creates a Builder by copying an existing ModuleInstance instance */ private Builder(com.sudip.avro.ModuleInstance other) { super(com.sudip.avro.ModuleInstance.SCHEMA$); if (isValidValue(fields()[0], other.id)) { this.id = data().deepCopy(fields()[0].schema(), other.id); fieldSetFlags()[0] = true; } if (isValidValue(fields()[1], other.eventTime)) { this.eventTime = data().deepCopy(fields()[1].schema(), other.eventTime); fieldSetFlags()[1] = true; } if (isValidValue(fields()[2], other.parentApp)) { this.parentApp = data().deepCopy(fields()[2].schema(), other.parentApp); fieldSetFlags()[2] = true; } } /** Gets the value of the 'id' field */ public java.lang.CharSequence getId() { return id; } /** Sets the value of the 'id' field */ public com.sudip.avro.ModuleInstance.Builder setId(java.lang.CharSequence value) { validate(fields()[0], value); this.id = value; fieldSetFlags()[0] = true; return this; } /** Checks whether the 'id' field has been set */ public boolean hasId() { return fieldSetFlags()[0]; } /** Clears the value of the 'id' field */ public com.sudip.avro.ModuleInstance.Builder clearId() { id = null; fieldSetFlags()[0] = false; return this; } /** Gets the value of the 'eventTime' field */ public java.lang.Long getEventTime() { return eventTime; } /** Sets the value of the 'eventTime' field */ public com.sudip.avro.ModuleInstance.Builder setEventTime(long value) { validate(fields()[1], value); this.eventTime = value; fieldSetFlags()[1] = true; return this; } /** Checks whether the 'eventTime' field has been set */ public boolean hasEventTime() { return fieldSetFlags()[1]; } /** Clears the value of the 'eventTime' field */ public com.sudip.avro.ModuleInstance.Builder clearEventTime() { fieldSetFlags()[1] = false; return this; } /** Gets the value of the 'parentApp' field */ public com.sudip.avro.ApplicationInstance getParentApp() { return parentApp; } /** Sets the value of the 'parentApp' field */ public com.sudip.avro.ModuleInstance.Builder setParentApp(com.sudip.avro.ApplicationInstance value) { validate(fields()[2], value); this.parentApp = value; fieldSetFlags()[2] = true; return this; } /** Checks whether the 'parentApp' field has been set */ public boolean hasParentApp() { return fieldSetFlags()[2]; } /** Clears the value of the 'parentApp' field */ public com.sudip.avro.ModuleInstance.Builder clearParentApp() { parentApp = null; fieldSetFlags()[2] = false; return this; } @Override public ModuleInstance build() { try { ModuleInstance record = new ModuleInstance(); record.id = fieldSetFlags()[0] ? this.id : (java.lang.CharSequence) defaultValue(fields()[0]); record.eventTime = fieldSetFlags()[1] ? this.eventTime : (java.lang.Long) defaultValue(fields()[1]); record.parentApp = fieldSetFlags()[2] ? this.parentApp : (com.sudip.avro.ApplicationInstance) defaultValue(fields()[2]); return record; } catch (Exception e) { throw new org.apache.avro.AvroRuntimeException(e); } } } }
a19c6843923ca01d6200bee87fb9d712ba005e99
7cf01545d4df49502309c2f0ea49e21930457b03
/src/main/java/hospital/Application.java
a3f40c7651ecab30c8920b20eb3328f8d5e43a3b
[]
no_license
dmf2990/hospital---first-basic-console-project
f484911575e04df27c22763d8f3a395e8040d028
a548061949d187b8a781bf0b0cb982461802b7d8
refs/heads/master
2020-04-22T05:01:29.268689
2019-04-08T16:07:04
2019-04-08T16:07:04
170,144,857
2
0
null
2019-04-08T15:27:35
2019-02-11T14:42:30
Java
UTF-8
Java
false
false
10,142
java
package hospital; import java.util.Scanner; public class Application { public static void main(String[] args) { Scanner input = new Scanner(System.in); // hashmap Hospital list = new Hospital(10, 10); // objects Patient patient = new Patient("Sicky", "12"); Doctor doctor = new Doctor("Dr.Dave", "Doctor", "5"); Surgeon surgeon = new Surgeon("SaveEm Sam", "Surgeon", "6"); Nurse nurse = new Nurse("NancyNurse", "Nurse", "8"); Receptionist receptionist = new Receptionist("RoryRecptionist", "Receptionist", "9"); Janitor janitor = new Janitor("JerryJanitor", "Janitor", "3"); VampireJanitor jVam = new VampireJanitor("Vladd", "Vampire Janitor", "1"); // hard add to maps list.addPatient(patient); list.addEmployee(doctor); list.addEmployee(surgeon); list.addEmployee(nurse); list.addEmployee(receptionist); list.addEmployee(janitor); list.addEmployee(jVam); System.out.println("Welcome to your Administration tool for WCCI University Hospital"); System.out.println("Press any key to continue."); input.nextLine(); // medic or admin System.out.println("Please select one of the following options"); System.out.println("1. See directions"); System.out.println("2. Continue as the Medical Director"); System.out.println("3. Continue as the Hospital Manager"); String userChoice = input.nextLine(); switch (userChoice) { case "1": System.out.println("Directions will be added in future iterations"); System.out.println("Press any key to return to the previous menu"); break; // add remove. interact single or all patients case "2": Boolean foo = true; while (foo) { System.out.println("You have selected to work as the Medical Director"); System.out.println("Please select one of the follwing options:"); System.out.println("1. Admit a patient to this hospital"); System.out.println("2. Discharge a patient from this hospital"); System.out.println("3. Interact with a single patient"); System.out.println("4. Interact with all patients"); System.out.println("5. Return to previous menu"); String userInput1 = input.nextLine(); list.tickPatient(); // TICK METHOD switch (userInput1) { case "1": System.out.println("Please enter the name of your patient you'd like to add"); String patientName = input.nextLine(); System.out.println("Please enter the ID Number of this patient"); String patientIDNumber = input.nextLine(); Patient newPatient = new Patient(patientName, patientIDNumber); list.addPatient(newPatient); System.out.println("see individual patient stats"); System.out.println(newPatient); System.out.println("See your entire patient population"); System.out.println(list.getPatientStatList()); System.out.println("Press any key to return to the previous menu"); input.nextLine(); break; case "2": System.out.println(list.getPatientStatList()); System.out.println("Please enter the Patient id number of the patient you would like to remove"); String removePatient = input.nextLine(); Patient rmPt = list.getPatient(removePatient); list.removePatient(rmPt); System.out.println("See your entire patient population"); System.out.println(list.getPatientStatList()); System.out.println("Press any key to return to the previous menu"); input.nextLine(); break; case "3": System.out.println(list.getPatientStatList()); System.out.println("Please enter the ID number of the patient you would like to interact with"); String idEntered = input.nextLine(); Patient idPt = list.getPatient(idEntered); // interact with single patient System.out.println("What would you like to do next?"); System.out.println("1. Treat Patient"); System.out.println("2. Draw Blood"); System.out.println("3. Feed Patient"); System.out.println("4. See patient stats"); System.out.println("5. Return to previous menu"); String userInput2 = input.nextLine(); switch (userInput2) { case "1": System.out.println("Would who would you like to perform this task"); System.out.println("1. Doctor"); System.out.println("2. Surgeon"); String userInput4 = input.nextLine(); switch (userInput4) { case "1": doctor.treatPatient(idPt); System.out.println(idPt); System.out.println("Press any key to return to the previous menu"); String i = input.nextLine(); break; case "2": surgeon.treatPatient(idPt); System.out.println(idPt); System.out.println("Press any key to return to the previous menu"); input.nextLine(); break; } case "2": System.out.println("Would who would you like to perform this task"); System.out.println("1. Doctor"); System.out.println("2. Surgeon"); System.out.println("3. Nurse"); System.out.println("4. Return previous menu"); String userInput5 = input.nextLine(); switch (userInput5) { case "1": doctor.drawBlood(idPt); System.out.println(idPt); System.out.println("Press any key to return to the previous menu"); input.nextLine(); break; case "2": surgeon.drawBlood(idPt); System.out.println(idPt); System.out.println("Press any key to return to the previous menu"); input.nextLine(); break; case "3": nurse.drawBlood(idPt); System.out.println(idPt); System.out.println("Press any key to return to the previous menu"); input.nextLine(); break; case "4": foo = !foo; // want to go back to draw blood feed pt } case "3": nurse.feed(idPt); System.out.println("The Nurse has performed this task\n"); System.out.println(idPt); System.out.println("Press any key to return to the previous menu"); input.nextLine(); break; case "4": System.out.println(idPt); case "5": foo = !foo; break; } // interact with all patients case "4": System.out.println("What would you like to do?"); System.out.println("1. Interact with all patients"); System.out.println("2. See all patients stats"); System.out.println("3. Return to previous menu"); String userInput8 = input.nextLine(); switch (userInput8) { case "1": System.out.println("What would you like to do?"); System.out.println("1. Treat all patients"); System.out.println("2. Draw all patient blood"); String userInput7 = input.nextLine(); switch (userInput7) { case "1": list.treatAllPatients(); System.out.println(list.getPatientStatList()); System.out.println("Press any key to return to the previous menu"); String k = input.nextLine(); break; case "2": list.drawAllPatientBlood(); System.out.println(list.getPatientStatList()); System.out.println("Press any key to return to the previous menu"); String rd = input.nextLine(); break; } case "2": System.out.println(list.getPatientStatList()); break; case "3": foo = !foo; } case "5": foo = !foo; } } // end of foo loop // this is the start of manager side of application case "3": Boolean doo = true; while (doo) { System.out.println("You have selected to work as the Hospital Manager"); System.out.println("Please select one of the follwing options:"); System.out.println("1. Direct an individual employee to complete a task"); System.out.println("2. Return to previous menu"); String userInput10 = input.nextLine(); list.tickHosptial(); // HOSPTIAL TICK switch (userInput10) { // do work w/ one employee case "1": System.out.println("What type of work would you like to do"); System.out.println("1. Sweep Floors"); System.out.println("2. Organize Hospital"); String userInput11 = input.nextLine(); switch (userInput11) { case "1": System.out.println("Would who would you like to perform this task"); System.out.println("1. Janitor"); System.out.println("2. Vampire Janitor"); String userInput12 = input.nextLine(); switch (userInput12) { case "1": janitor.sweep(list); System.out.println(list.toString()); case "2": System.out.println("You have entered the lair of Vlad the Vampire Janitor"); System.out.println("muah ha ha ha Weeeelcome my friend, what should we do?"); System.out.println("1. Sweep the floors"); System.out.println("2. Something much more sinister"); System.out.println("3. Return to previous menu"); String userInput13 = input.nextLine(); switch (userInput13) { case "1": jVam.sweep(list); System.out.println(list.toString()); break; case "2": System.out.println("1. Draw blood from all patients to make an Army of Vampires"); System.out.println("2. Draw the blood of one patient soul to make them immortal"); String userInput14 = input.nextLine(); switch (userInput14) { case "1": list.drawAllPatientBlood(); System.out.println("Hospital Closed!"); System.exit(0); break; case "2": jVam.drawBlood(patient); System.out.println("Your Patient is now immortal!"); doo = !doo; break; } } } case "2": System.out.println("Would who would you like to perform this task"); System.out.println("1. Nurse"); System.out.println("2. Receptionist"); String userInput15 = input.nextLine(); switch (userInput15) { case "1": nurse.organize(list); System.out.println(list.toString()); case "2": receptionist.organize(list); System.out.println(list.toString()); case "3": doo = !doo; } } // 240 } // 231 } // 224 } // 41 } // 6 }// 5
f23ce6841ae1d00295ee06ea850a25de7de5cd7a
d3fe404b0a5eec8538dcf7af32c5f18e53a13aa0
/MLA_MappingImpl/src/generated/java/uima/tt/ParagraphAnnotation_Type.java
e3659345abc3dbb80916ce3374f9263bc25ca30c
[]
no_license
kristienverreydt/mla-belgium
f237dae31f065a8cd91761130bf34a08acbefd50
55471172a253647a2472f38df8898df7cdc79fbb
refs/heads/master
2021-01-19T03:07:52.899123
2017-04-05T13:12:23
2017-04-05T13:12:23
87,305,460
0
0
null
null
null
null
UTF-8
Java
false
false
1,958
java
/* First created by JCasGen Tue Sep 13 14:28:47 CEST 2016 */ package uima.tt; import org.apache.uima.jcas.JCas; import org.apache.uima.jcas.JCasRegistry; import org.apache.uima.cas.impl.CASImpl; import org.apache.uima.cas.impl.FSGenerator; import org.apache.uima.cas.FeatureStructure; import org.apache.uima.cas.impl.TypeImpl; import org.apache.uima.cas.Type; /** * Updated by JCasGen Tue Sep 13 14:28:47 CEST 2016 * @generated */ public class ParagraphAnnotation_Type extends DocStructureAnnotation_Type { /** @generated * @return the generator for this type */ @Override protected FSGenerator getFSGenerator() {return fsGenerator;} /** @generated */ private final FSGenerator fsGenerator = new FSGenerator() { public FeatureStructure createFS(int addr, CASImpl cas) { if (ParagraphAnnotation_Type.this.useExistingInstance) { // Return eq fs instance if already created FeatureStructure fs = ParagraphAnnotation_Type.this.jcas.getJfsFromCaddr(addr); if (null == fs) { fs = new ParagraphAnnotation(addr, ParagraphAnnotation_Type.this); ParagraphAnnotation_Type.this.jcas.putJfsFromCaddr(addr, fs); return fs; } return fs; } else return new ParagraphAnnotation(addr, ParagraphAnnotation_Type.this); } }; /** @generated */ @SuppressWarnings ("hiding") public final static int typeIndexID = ParagraphAnnotation.typeIndexID; /** @generated @modifiable */ @SuppressWarnings ("hiding") public final static boolean featOkTst = JCasRegistry.getFeatOkTst("uima.tt.ParagraphAnnotation"); /** initialize variables to correspond with Cas Type and Features * @generated * @param jcas JCas * @param casType Type */ public ParagraphAnnotation_Type(JCas jcas, Type casType) { super(jcas, casType); casImpl.getFSClassRegistry().addGeneratorForType((TypeImpl)this.casType, getFSGenerator()); } }
5c1b979016c67966b0d42849ed4987b2ef0278d1
8c776888e68058145b1d5abb03eafbf97613ded8
/library/userlibrary_1.0.0/src/main/java/com/lxh/userlibrary/UserCenter.java
ab1acd01454f71af2400af3f27aa6dab4af1e46a
[]
no_license
Hanson5920/Hulk_fitness
c5e03673d50d9915dd7ef70775524e81bc621c11
a1d59a24f9a3f9aec01612fc4b6b6f2c092de042
refs/heads/master
2021-01-13T16:48:16.390067
2017-06-21T03:40:06
2017-06-21T03:40:06
94,958,849
0
0
null
null
null
null
UTF-8
Java
false
false
5,835
java
package com.lxh.userlibrary; import android.app.Activity; import android.app.Service; import android.content.Context; import android.content.SharedPreferences; import android.os.Vibrator; import android.util.DisplayMetrics; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.lxh.userlibrary.constant.Configs; import com.lxh.userlibrary.constant.Constants; import com.lxh.userlibrary.load.ImageLoaderManager; import com.lxh.userlibrary.load.LocationService; import com.lxh.userlibrary.mineInterface.UserInterface; import com.lxh.userlibrary.manager.UserManage; import com.lxh.userlibrary.manager.dialog.LoadingDialog; import com.lxh.userlibrary.message.MessagePump; import com.lxh.userlibrary.mineInterface.AliPayInterface; import com.lxh.userlibrary.utils.AliPayUtil; import com.lxh.userlibrary.utils.ToastUtil; import com.lxh.userlibrary.utils.WechatPayUtil; import cn.sharesdk.framework.ShareSDK; import okhttp3.Call; /** * Created by wbb on 2016/8/2. */ public class UserCenter { private static UserCenter sInstance; private static Context mContext; private MessagePump mMessagePump; public static LocationService locationService; public static Vibrator mVibrator; public static String DKAETYA; public static String URL_KEY; //对应请求的c_appid public static String APPID; //对应请求的api版本号 public static String USER_API; public static void init(Context context, String dkaetya, String urlKey, String appid, String userApi) { DKAETYA = dkaetya; URL_KEY = urlKey; APPID = appid; USER_API = userApi; mContext = context.getApplicationContext(); sInstance = new UserCenter(); Configs.init();//网络接口连接初始化 ImageLoaderManager.init(context); locationService = new LocationService(context); mVibrator = (Vibrator) context.getSystemService(Service.VIBRATOR_SERVICE); ShareSDK.initSDK(context); DisplayMetrics dm = context.getResources().getDisplayMetrics(); int width = dm.widthPixels; int height = dm.heightPixels; Constants.Pwide = width; Constants.Phigh = height; } public static Context getContext() { return mContext; } public static synchronized UserCenter getInstance() { return sInstance; } public MessagePump getMessagePump() { if (mMessagePump == null) mMessagePump = new MessagePump(); return mMessagePump; } public SharedPreferences getSharedPreferences(String name, int modePrivate) { return mContext.getSharedPreferences(name, modePrivate); } public static void weixinPay(Context context,String uid, String rmb, final String wxappid, final String wxkey) { if (uid == null || uid.equals("")) { ToastUtil.toastShort(mContext, "检测到您未登录,请登录之后再试..."); return; } final LoadingDialog loadingDialog = new LoadingDialog(context,"正在调起微信支付,请稍候..."); loadingDialog.show(); UserManage.PayWeixin(uid, rmb, new UserInterface() { @Override public void onError(Call call, Exception e, String msg) { ToastUtil.toastShort(mContext,msg); loadingDialog.dismiss(); } @Override public void onSucceed(int state, String msg, String data, JSONObject obj) { loadingDialog.dismiss(); switch (state) { case 200: try { JSONObject jsonObject = JSON.parseObject(data); String prepay_id = jsonObject.getString("prepay_id"); String partnerid = jsonObject.getString("partnerid"); String noncestr = jsonObject.getString("noncestr"); String sign = jsonObject.getString("sign"); String time = String.valueOf(System.currentTimeMillis() / 1000); WechatPayUtil.wechatPay(mContext,wxappid,wxkey,sign,noncestr, partnerid, prepay_id, time); } catch (Exception e) { } break; default: ToastUtil.toastShort(mContext, msg); break; } ToastUtil.toastShort(mContext,msg); } }); } public static void aliPay(final Activity activity, String uid, String rmb, final AliPayInterface Interface){ if (uid == null || uid.equals("")) { ToastUtil.toastShort(mContext, "检测到您未登录,请登录之后再试..."); return; } final LoadingDialog loadingDialog = new LoadingDialog(activity,"正在调起支付宝支付,请稍候..."); loadingDialog.show(); UserManage.PayAlipay(uid, rmb, new UserInterface() { @Override public void onError(Call call, Exception e, String msg) { ToastUtil.toastShort(mContext,msg); loadingDialog.dismiss(); } @Override public void onSucceed(int state, String msg, String data, JSONObject obj) { loadingDialog.dismiss(); switch (state){ case 200: JSONObject jsonObject = JSON.parseObject(data); String requestInfo = jsonObject.getString("request_info"); AliPayUtil.pay(activity,requestInfo,Interface); break; } ToastUtil.toastShort(mContext,msg); } }); } }
[ "husong" ]
husong
4b1acea845a6d76f5e9e80d34a5106201f720ab1
1aa53d5cc013622d0d97a405655be4a33ab1e908
/src/main/java/coding/exercise/serviceimpl/CustomerServiceImpl.java
437be18fd5a5b6bd69adef7fe7779f2b3e53bc77
[]
no_license
pjsev/ShoppingCart
67e812984828ef520d024ca668aec87c491dd1c9
4f96051dffc26f00326f0a7f3bac20c98f541a1e
refs/heads/master
2020-05-20T03:46:40.183067
2019-06-26T08:04:07
2019-06-26T08:04:07
185,365,845
0
0
null
null
null
null
UTF-8
Java
false
false
1,022
java
package coding.exercise.serviceimpl; import java.util.List; import java.util.Set; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import coding.exercise.model.Customer; import coding.exercise.model.CustomerRepository; import coding.exercise.model.Item; import coding.exercise.service.CustomerService; @Service public class CustomerServiceImpl implements CustomerService { @Autowired CustomerRepository customerRepository; @Override public Customer saveCustomer(Customer customer) { return customerRepository.save(customer); } @Override public Customer findCustomer(long id) { return customerRepository.findById(id).orElse(null); } @Override public List<Customer> findAllCustomers() { return customerRepository.findAll(); } @Override public double computeCustomerItems(Set<Item> items) { double total = 0; for (Item i: items) { total += i.getPrice(); } return total; } }
38503c4de4d0151c513b80cd3d4eae856612d4e3
448cd295aca52be0757cab70bd2f45e8f72c98aa
/src/com/lxsh/model/Gtype.java
d0e6e28968d5525da22239568fb7008d0b510865
[]
no_license
mybsktb/ssm-freshlife
7fae3b99fc74ebea0bd9e0f80b2fbd4778cc4e74
53dabac099537fe788b777d232790a63442f6366
refs/heads/master
2021-01-12T16:14:35.650927
2016-10-31T09:25:25
2016-10-31T09:25:50
71,955,448
0
0
null
null
null
null
UTF-8
Java
false
false
430
java
package com.lxsh.model; public class Gtype { private Integer gtid; private String gtypename; public Integer getGtid() { return gtid; } public void setGtid(Integer gtid) { this.gtid = gtid; } public String getGtypename() { return gtypename; } public void setGtypename(String gtypename) { this.gtypename = gtypename == null ? null : gtypename.trim(); } }
9d8308312abb632639fc1bf38471672f5ecd2aa9
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/31/31_7763b36d6d95d78df49c5144291972d95ff7b4f6/LatinKeyboardBaseView/31_7763b36d6d95d78df49c5144291972d95ff7b4f6_LatinKeyboardBaseView_s.java
90252964e1e35a84e362a153bf8914faefea9f28
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
54,383
java
/* * Copyright (C) 2010 The Android Open Source Project * * 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.android.inputmethod.latin; import android.content.Context; import android.content.pm.PackageManager; import android.content.res.Resources; import android.content.res.TypedArray; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.PorterDuff; import android.graphics.Rect; import android.graphics.Region.Op; import android.graphics.Typeface; import android.graphics.drawable.Drawable; import android.inputmethodservice.Keyboard; import android.inputmethodservice.Keyboard.Key; import android.os.Handler; import android.os.Message; import android.util.AttributeSet; import android.util.Log; import android.util.TypedValue; import android.view.GestureDetector; import android.view.Gravity; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup.LayoutParams; import android.widget.PopupWindow; import android.widget.TextView; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; /** * A view that renders a virtual {@link LatinKeyboard}. It handles rendering of keys and * detecting key presses and touch movements. * * @attr ref R.styleable#LatinKeyboardBaseView_keyBackground * @attr ref R.styleable#LatinKeyboardBaseView_keyPreviewLayout * @attr ref R.styleable#LatinKeyboardBaseView_keyPreviewOffset * @attr ref R.styleable#LatinKeyboardBaseView_labelTextSize * @attr ref R.styleable#LatinKeyboardBaseView_keyTextSize * @attr ref R.styleable#LatinKeyboardBaseView_keyTextColor * @attr ref R.styleable#LatinKeyboardBaseView_verticalCorrection * @attr ref R.styleable#LatinKeyboardBaseView_popupLayout */ public class LatinKeyboardBaseView extends View implements PointerTracker.UIProxy { private static final String TAG = "LatinKeyboardBaseView"; private static final boolean DEBUG = false; public static final int NOT_A_TOUCH_COORDINATE = -1; public interface OnKeyboardActionListener { /** * Called when the user presses a key. This is sent before the * {@link #onKey} is called. For keys that repeat, this is only * called once. * * @param primaryCode * the unicode of the key being pressed. If the touch is * not on a valid key, the value will be zero. */ void onPress(int primaryCode); /** * Called when the user releases a key. This is sent after the * {@link #onKey} is called. For keys that repeat, this is only * called once. * * @param primaryCode * the code of the key that was released */ void onRelease(int primaryCode); /** * Send a key press to the listener. * * @param primaryCode * this is the key that was pressed * @param keyCodes * the codes for all the possible alternative keys with * the primary code being the first. If the primary key * code is a single character such as an alphabet or * number or symbol, the alternatives will include other * characters that may be on the same key or adjacent * keys. These codes are useful to correct for * accidental presses of a key adjacent to the intended * key. * @param x * x-coordinate pixel of touched event. If onKey is not called by onTouchEvent, * the value should be NOT_A_TOUCH_COORDINATE. * @param y * y-coordinate pixel of touched event. If onKey is not called by onTouchEvent, * the value should be NOT_A_TOUCH_COORDINATE. */ void onKey(int primaryCode, int[] keyCodes, int x, int y); /** * Sends a sequence of characters to the listener. * * @param text * the sequence of characters to be displayed. */ void onText(CharSequence text); /** * Called when user released a finger outside any key. */ void onCancel(); /** * Called when the user quickly moves the finger from right to * left. */ void swipeLeft(); /** * Called when the user quickly moves the finger from left to * right. */ void swipeRight(); /** * Called when the user quickly moves the finger from up to down. */ void swipeDown(); /** * Called when the user quickly moves the finger from down to up. */ void swipeUp(); } // Timing constants private static final int DELAY_BEFORE_PREVIEW = 0; private static final int DELAY_AFTER_PREVIEW = 150; private static final int REPEAT_INTERVAL = PointerTracker.REPEAT_INTERVAL; // Miscellaneous constants /* package */ static final int NOT_A_KEY = -1; private static final int[] LONG_PRESSABLE_STATE_SET = { android.R.attr.state_long_pressable }; // XML attribute private int mKeyTextSize; private int mKeyTextColor; private Typeface mKeyTextStyle = Typeface.DEFAULT; private int mLabelTextSize; private int mSymbolColorScheme = 0; private int mShadowColor; private float mShadowRadius; private Drawable mKeyBackground; private float mBackgroundDimAmount; private float mKeyHysteresisDistance; private float mVerticalCorrection; private int mPreviewOffset; private int mPreviewHeight; private int mPopupLayout; // Main keyboard private Keyboard mKeyboard; private Key[] mKeys; // Key preview popup private TextView mPreviewText; private PopupWindow mPreviewPopup; private int mPreviewTextSizeLarge; private int[] mOffsetInWindow; private int mOldPreviewKeyIndex = NOT_A_KEY; private boolean mShowPreview = true; private boolean mShowTouchPoints = true; private int mPopupPreviewOffsetX; private int mPopupPreviewOffsetY; private int mWindowY; // Popup mini keyboard private PopupWindow mMiniKeyboardPopup; private LatinKeyboardBaseView mMiniKeyboard; private View mMiniKeyboardParent; private Map<Key,View> mMiniKeyboardCache; private int mMiniKeyboardOriginX; private int mMiniKeyboardOriginY; private long mMiniKeyboardPopupTime; private int[] mWindowOffset; private final float mMiniKeyboardSlideAllowance; /** Listener for {@link OnKeyboardActionListener}. */ private OnKeyboardActionListener mKeyboardActionListener; private final ArrayList<PointerTracker> mPointerTrackers = new ArrayList<PointerTracker>(); private final PointerQueue mPointerQueue = new PointerQueue(); private final boolean mHasDistinctMultitouch; private int mOldPointerCount = 1; protected KeyDetector mKeyDetector = new ProximityKeyDetector(); // Swipe gesture detector private final GestureDetector mGestureDetector; private final SwipeTracker mSwipeTracker = new SwipeTracker(); private final int mSwipeThreshold; private final boolean mDisambiguateSwipe; // Drawing /** Whether the keyboard bitmap needs to be redrawn before it's blitted. **/ private boolean mDrawPending; /** The dirty region in the keyboard bitmap */ private final Rect mDirtyRect = new Rect(); /** The keyboard bitmap for faster updates */ private Bitmap mBuffer; /** Notes if the keyboard just changed, so that we could possibly reallocate the mBuffer. */ private boolean mKeyboardChanged; private Key mInvalidatedKey; /** The canvas for the above mutable keyboard bitmap */ private Canvas mCanvas; private final Paint mPaint; private final Rect mPadding; private final Rect mClipRegion = new Rect(0, 0, 0, 0); private final UIHandler mHandler = new UIHandler(); class UIHandler extends Handler { private static final int MSG_POPUP_PREVIEW = 1; private static final int MSG_DISMISS_PREVIEW = 2; private static final int MSG_REPEAT_KEY = 3; private static final int MSG_LONGPRESS_KEY = 4; private boolean mInKeyRepeat; @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_POPUP_PREVIEW: showKey(msg.arg1, (PointerTracker)msg.obj); break; case MSG_DISMISS_PREVIEW: mPreviewText.setVisibility(INVISIBLE); break; case MSG_REPEAT_KEY: { final PointerTracker tracker = (PointerTracker)msg.obj; tracker.repeatKey(msg.arg1); startKeyRepeatTimer(REPEAT_INTERVAL, msg.arg1, tracker); break; } case MSG_LONGPRESS_KEY: { final PointerTracker tracker = (PointerTracker)msg.obj; openPopupIfRequired(msg.arg1, tracker); break; } } } public void popupPreview(long delay, int keyIndex, PointerTracker tracker) { removeMessages(MSG_POPUP_PREVIEW); if (mPreviewPopup.isShowing() && mPreviewText.getVisibility() == VISIBLE) { // Show right away, if it's already visible and finger is moving around showKey(keyIndex, tracker); } else { sendMessageDelayed(obtainMessage(MSG_POPUP_PREVIEW, keyIndex, 0, tracker), delay); } } public void cancelPopupPreview() { removeMessages(MSG_POPUP_PREVIEW); } public void dismissPreview(long delay) { if (mPreviewPopup.isShowing()) { sendMessageDelayed(obtainMessage(MSG_DISMISS_PREVIEW), delay); } } public void cancelDismissPreview() { removeMessages(MSG_DISMISS_PREVIEW); } public void startKeyRepeatTimer(long delay, int keyIndex, PointerTracker tracker) { mInKeyRepeat = true; sendMessageDelayed(obtainMessage(MSG_REPEAT_KEY, keyIndex, 0, tracker), delay); } public void cancelKeyRepeatTimer() { mInKeyRepeat = false; removeMessages(MSG_REPEAT_KEY); } public boolean isInKeyRepeat() { return mInKeyRepeat; } public void startLongPressTimer(long delay, int keyIndex, PointerTracker tracker) { removeMessages(MSG_LONGPRESS_KEY); sendMessageDelayed(obtainMessage(MSG_LONGPRESS_KEY, keyIndex, 0, tracker), delay); } public void cancelLongPressTimer() { removeMessages(MSG_LONGPRESS_KEY); } public void cancelKeyTimers() { cancelKeyRepeatTimer(); cancelLongPressTimer(); } public void cancelAllMessages() { cancelKeyTimers(); cancelPopupPreview(); cancelDismissPreview(); } }; static class PointerQueue { private LinkedList<PointerTracker> mQueue = new LinkedList<PointerTracker>(); public void add(PointerTracker tracker) { mQueue.add(tracker); } public int lastIndexOf(PointerTracker tracker) { LinkedList<PointerTracker> queue = mQueue; for (int index = queue.size() - 1; index >= 0; index--) { PointerTracker t = queue.get(index); if (t == tracker) return index; } return -1; } public void releaseAllPointersOlderThan(PointerTracker tracker, long eventTime) { LinkedList<PointerTracker> queue = mQueue; int oldestPos = 0; for (PointerTracker t = queue.get(oldestPos); t != tracker; t = queue.get(oldestPos)) { if (t.isModifier()) { oldestPos++; } else { t.onUpEvent(t.getLastX(), t.getLastY(), eventTime); t.setAlreadyProcessed(); queue.remove(oldestPos); } } } public void releaseAllPointersExcept(PointerTracker tracker, long eventTime) { for (PointerTracker t : mQueue) { if (t == tracker) continue; t.onUpEvent(t.getLastX(), t.getLastY(), eventTime); t.setAlreadyProcessed(); } mQueue.clear(); if (tracker != null) mQueue.add(tracker); } public void remove(PointerTracker tracker) { mQueue.remove(tracker); } } public LatinKeyboardBaseView(Context context, AttributeSet attrs) { this(context, attrs, R.attr.keyboardViewStyle); } public LatinKeyboardBaseView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); TypedArray a = context.obtainStyledAttributes( attrs, R.styleable.LatinKeyboardBaseView, defStyle, R.style.LatinKeyboardBaseView); LayoutInflater inflate = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); int previewLayout = 0; int keyTextSize = 0; int n = a.getIndexCount(); for (int i = 0; i < n; i++) { int attr = a.getIndex(i); switch (attr) { case R.styleable.LatinKeyboardBaseView_keyBackground: mKeyBackground = a.getDrawable(attr); break; case R.styleable.LatinKeyboardBaseView_keyHysteresisDistance: mKeyHysteresisDistance = a.getDimensionPixelOffset(attr, 0); break; case R.styleable.LatinKeyboardBaseView_verticalCorrection: mVerticalCorrection = a.getDimensionPixelOffset(attr, 0); break; case R.styleable.LatinKeyboardBaseView_keyPreviewLayout: previewLayout = a.getResourceId(attr, 0); break; case R.styleable.LatinKeyboardBaseView_keyPreviewOffset: mPreviewOffset = a.getDimensionPixelOffset(attr, 0); break; case R.styleable.LatinKeyboardBaseView_keyPreviewHeight: mPreviewHeight = a.getDimensionPixelSize(attr, 80); break; case R.styleable.LatinKeyboardBaseView_keyTextSize: mKeyTextSize = a.getDimensionPixelSize(attr, 18); break; case R.styleable.LatinKeyboardBaseView_keyTextColor: mKeyTextColor = a.getColor(attr, 0xFF000000); break; case R.styleable.LatinKeyboardBaseView_labelTextSize: mLabelTextSize = a.getDimensionPixelSize(attr, 14); break; case R.styleable.LatinKeyboardBaseView_popupLayout: mPopupLayout = a.getResourceId(attr, 0); break; case R.styleable.LatinKeyboardBaseView_shadowColor: mShadowColor = a.getColor(attr, 0); break; case R.styleable.LatinKeyboardBaseView_shadowRadius: mShadowRadius = a.getFloat(attr, 0f); break; // TODO: Use Theme (android.R.styleable.Theme_backgroundDimAmount) case R.styleable.LatinKeyboardBaseView_backgroundDimAmount: mBackgroundDimAmount = a.getFloat(attr, 0.5f); break; //case android.R.styleable. case R.styleable.LatinKeyboardBaseView_keyTextStyle: int textStyle = a.getInt(attr, 0); switch (textStyle) { case 0: mKeyTextStyle = Typeface.DEFAULT; break; case 1: mKeyTextStyle = Typeface.DEFAULT_BOLD; break; default: mKeyTextStyle = Typeface.defaultFromStyle(textStyle); break; } break; case R.styleable.LatinKeyboardBaseView_symbolColorScheme: mSymbolColorScheme = a.getInt(attr, 0); break; } } mPreviewPopup = new PopupWindow(context); if (previewLayout != 0) { mPreviewText = (TextView) inflate.inflate(previewLayout, null); mPreviewTextSizeLarge = (int) mPreviewText.getTextSize(); mPreviewPopup.setContentView(mPreviewText); mPreviewPopup.setBackgroundDrawable(null); } else { mShowPreview = false; } mPreviewPopup.setTouchable(false); mMiniKeyboardParent = this; mMiniKeyboardPopup = new PopupWindow(context); mMiniKeyboardPopup.setBackgroundDrawable(null); mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setTextSize(keyTextSize); mPaint.setTextAlign(Align.CENTER); mPaint.setAlpha(255); mPadding = new Rect(0, 0, 0, 0); mMiniKeyboardCache = new HashMap<Key,View>(); mKeyBackground.getPadding(mPadding); final Resources res = getResources(); mSwipeThreshold = (int) (500 * res.getDisplayMetrics().density); // TODO: Refer frameworks/base/core/res/res/values/config.xml mDisambiguateSwipe = res.getBoolean(R.bool.config_swipeDisambiguation); mMiniKeyboardSlideAllowance = res.getDimension(R.dimen.mini_keyboard_slide_allowance); GestureDetector.SimpleOnGestureListener listener = new GestureDetector.SimpleOnGestureListener() { @Override public boolean onFling(MotionEvent me1, MotionEvent me2, float velocityX, float velocityY) { final float absX = Math.abs(velocityX); final float absY = Math.abs(velocityY); float deltaX = me2.getX() - me1.getX(); float deltaY = me2.getY() - me1.getY(); int travelX = getWidth() / 2; // Half the keyboard width int travelY = getHeight() / 2; // Half the keyboard height mSwipeTracker.computeCurrentVelocity(1000); final float endingVelocityX = mSwipeTracker.getXVelocity(); final float endingVelocityY = mSwipeTracker.getYVelocity(); if (velocityX > mSwipeThreshold && absY < absX && deltaX > travelX) { if (mDisambiguateSwipe && endingVelocityX >= velocityX / 4) { swipeRight(); return true; } } else if (velocityX < -mSwipeThreshold && absY < absX && deltaX < -travelX) { if (mDisambiguateSwipe && endingVelocityX <= velocityX / 4) { swipeLeft(); return true; } } else if (velocityY < -mSwipeThreshold && absX < absY && deltaY < -travelY) { if (mDisambiguateSwipe && endingVelocityY <= velocityY / 4) { swipeUp(); return true; } } else if (velocityY > mSwipeThreshold && absX < absY / 2 && deltaY > travelY) { if (mDisambiguateSwipe && endingVelocityY >= velocityY / 4) { swipeDown(); return true; } } return false; } }; final boolean ignoreMultitouch = true; mGestureDetector = new GestureDetector(getContext(), listener, null, ignoreMultitouch); mGestureDetector.setIsLongpressEnabled(false); mHasDistinctMultitouch = context.getPackageManager() .hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN_MULTITOUCH_DISTINCT); } public void setOnKeyboardActionListener(OnKeyboardActionListener listener) { mKeyboardActionListener = listener; for (PointerTracker tracker : mPointerTrackers) { tracker.setOnKeyboardActionListener(listener); } } /** * Returns the {@link OnKeyboardActionListener} object. * @return the listener attached to this keyboard */ protected OnKeyboardActionListener getOnKeyboardActionListener() { return mKeyboardActionListener; } /** * Attaches a keyboard to this view. The keyboard can be switched at any time and the * view will re-layout itself to accommodate the keyboard. * @see Keyboard * @see #getKeyboard() * @param keyboard the keyboard to display in this view */ public void setKeyboard(Keyboard keyboard) { if (mKeyboard != null) { dismissKeyPreview(); } // Remove any pending messages, except dismissing preview mHandler.cancelKeyTimers(); mHandler.cancelPopupPreview(); mKeyboard = keyboard; LatinImeLogger.onSetKeyboard(keyboard); mKeys = mKeyDetector.setKeyboard(keyboard, -getPaddingLeft(), -getPaddingTop() + mVerticalCorrection); for (PointerTracker tracker : mPointerTrackers) { tracker.setKeyboard(mKeys, mKeyHysteresisDistance); } requestLayout(); // Hint to reallocate the buffer if the size changed mKeyboardChanged = true; invalidateAllKeys(); computeProximityThreshold(keyboard); mMiniKeyboardCache.clear(); } /** * Returns the current keyboard being displayed by this view. * @return the currently attached keyboard * @see #setKeyboard(Keyboard) */ public Keyboard getKeyboard() { return mKeyboard; } /** * Return whether the device has distinct multi-touch panel. * @return true if the device has distinct multi-touch panel. */ public boolean hasDistinctMultitouch() { return mHasDistinctMultitouch; } /** * Sets the state of the shift key of the keyboard, if any. * @param shifted whether or not to enable the state of the shift key * @return true if the shift key state changed, false if there was no change */ public boolean setShifted(boolean shifted) { if (mKeyboard != null) { if (mKeyboard.setShifted(shifted)) { // The whole keyboard probably needs to be redrawn invalidateAllKeys(); return true; } } return false; } /** * Returns the state of the shift key of the keyboard, if any. * @return true if the shift is in a pressed state, false otherwise. If there is * no shift key on the keyboard or there is no keyboard attached, it returns false. */ public boolean isShifted() { if (mKeyboard != null) { return mKeyboard.isShifted(); } return false; } /** * Enables or disables the key feedback popup. This is a popup that shows a magnified * version of the depressed key. By default the preview is enabled. * @param previewEnabled whether or not to enable the key feedback popup * @see #isPreviewEnabled() */ public void setPreviewEnabled(boolean previewEnabled) { mShowPreview = previewEnabled; } /** * Returns the enabled state of the key feedback popup. * @return whether or not the key feedback popup is enabled * @see #setPreviewEnabled(boolean) */ public boolean isPreviewEnabled() { return mShowPreview; } public int getSymbolColorScheme() { return mSymbolColorScheme; } public void setPopupParent(View v) { mMiniKeyboardParent = v; } public void setPopupOffset(int x, int y) { mPopupPreviewOffsetX = x; mPopupPreviewOffsetY = y; if (mPreviewPopup.isShowing()) { mPreviewPopup.dismiss(); } } /** * When enabled, calls to {@link OnKeyboardActionListener#onKey} will include key * codes for adjacent keys. When disabled, only the primary key code will be * reported. * @param enabled whether or not the proximity correction is enabled */ public void setProximityCorrectionEnabled(boolean enabled) { mKeyDetector.setProximityCorrectionEnabled(enabled); } /** * Returns true if proximity correction is enabled. */ public boolean isProximityCorrectionEnabled() { return mKeyDetector.isProximityCorrectionEnabled(); } protected CharSequence adjustCase(CharSequence label) { if (mKeyboard.isShifted() && label != null && label.length() < 3 && Character.isLowerCase(label.charAt(0))) { label = label.toString().toUpperCase(); } return label; } @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // Round up a little if (mKeyboard == null) { setMeasuredDimension( getPaddingLeft() + getPaddingRight(), getPaddingTop() + getPaddingBottom()); } else { int width = mKeyboard.getMinWidth() + getPaddingLeft() + getPaddingRight(); if (MeasureSpec.getSize(widthMeasureSpec) < width + 10) { width = MeasureSpec.getSize(widthMeasureSpec); } setMeasuredDimension( width, mKeyboard.getHeight() + getPaddingTop() + getPaddingBottom()); } } /** * Compute the average distance between adjacent keys (horizontally and vertically) * and square it to get the proximity threshold. We use a square here and in computing * the touch distance from a key's center to avoid taking a square root. * @param keyboard */ private void computeProximityThreshold(Keyboard keyboard) { if (keyboard == null) return; final Key[] keys = mKeys; if (keys == null) return; int length = keys.length; int dimensionSum = 0; for (int i = 0; i < length; i++) { Key key = keys[i]; dimensionSum += Math.min(key.width, key.height) + key.gap; } if (dimensionSum < 0 || length == 0) return; mKeyDetector.setProximityThreshold((int) (dimensionSum * 1.4f / length)); } @Override public void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); // Release the buffer, if any and it will be reallocated on the next draw mBuffer = null; } @Override public void onDraw(Canvas canvas) { super.onDraw(canvas); if (mDrawPending || mBuffer == null || mKeyboardChanged) { onBufferDraw(); } canvas.drawBitmap(mBuffer, 0, 0, null); } private void onBufferDraw() { if (mBuffer == null || mKeyboardChanged) { if (mBuffer == null || mKeyboardChanged && (mBuffer.getWidth() != getWidth() || mBuffer.getHeight() != getHeight())) { // Make sure our bitmap is at least 1x1 final int width = Math.max(1, getWidth()); final int height = Math.max(1, getHeight()); mBuffer = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); mCanvas = new Canvas(mBuffer); } invalidateAllKeys(); mKeyboardChanged = false; } final Canvas canvas = mCanvas; canvas.clipRect(mDirtyRect, Op.REPLACE); if (mKeyboard == null) return; final Paint paint = mPaint; final Drawable keyBackground = mKeyBackground; final Rect clipRegion = mClipRegion; final Rect padding = mPadding; final int kbdPaddingLeft = getPaddingLeft(); final int kbdPaddingTop = getPaddingTop(); final Key[] keys = mKeys; final Key invalidKey = mInvalidatedKey; paint.setColor(mKeyTextColor); boolean drawSingleKey = false; if (invalidKey != null && canvas.getClipBounds(clipRegion)) { // Is clipRegion completely contained within the invalidated key? if (invalidKey.x + kbdPaddingLeft - 1 <= clipRegion.left && invalidKey.y + kbdPaddingTop - 1 <= clipRegion.top && invalidKey.x + invalidKey.width + kbdPaddingLeft + 1 >= clipRegion.right && invalidKey.y + invalidKey.height + kbdPaddingTop + 1 >= clipRegion.bottom) { drawSingleKey = true; } } canvas.drawColor(0x00000000, PorterDuff.Mode.CLEAR); final int keyCount = keys.length; for (int i = 0; i < keyCount; i++) { final Key key = keys[i]; if (drawSingleKey && invalidKey != key) { continue; } int[] drawableState = key.getCurrentDrawableState(); keyBackground.setState(drawableState); // Switch the character to uppercase if shift is pressed String label = key.label == null? null : adjustCase(key.label).toString(); final Rect bounds = keyBackground.getBounds(); if (key.width != bounds.right || key.height != bounds.bottom) { keyBackground.setBounds(0, 0, key.width, key.height); } canvas.translate(key.x + kbdPaddingLeft, key.y + kbdPaddingTop); keyBackground.draw(canvas); if (label != null) { // For characters, use large font. For labels like "Done", use small font. if (label.length() > 1 && key.codes.length < 2) { paint.setTextSize(mLabelTextSize); paint.setTypeface(Typeface.DEFAULT_BOLD); } else { paint.setTextSize(mKeyTextSize); paint.setTypeface(mKeyTextStyle); } // Draw a drop shadow for the text paint.setShadowLayer(mShadowRadius, 0, 0, mShadowColor); // Draw the text canvas.drawText(label, (key.width - padding.left - padding.right) / 2 + padding.left, (key.height - padding.top - padding.bottom) / 2 + (paint.getTextSize() - paint.descent()) / 2 + padding.top, paint); // Turn off drop shadow paint.setShadowLayer(0, 0, 0, 0); } else if (key.icon != null) { final int drawableX = (key.width - padding.left - padding.right - key.icon.getIntrinsicWidth()) / 2 + padding.left; final int drawableY = (key.height - padding.top - padding.bottom - key.icon.getIntrinsicHeight()) / 2 + padding.top; canvas.translate(drawableX, drawableY); key.icon.setBounds(0, 0, key.icon.getIntrinsicWidth(), key.icon.getIntrinsicHeight()); key.icon.draw(canvas); canvas.translate(-drawableX, -drawableY); } canvas.translate(-key.x - kbdPaddingLeft, -key.y - kbdPaddingTop); } mInvalidatedKey = null; // Overlay a dark rectangle to dim the keyboard if (mMiniKeyboard != null) { paint.setColor((int) (mBackgroundDimAmount * 0xFF) << 24); canvas.drawRect(0, 0, getWidth(), getHeight(), paint); } if (DEBUG) { if (mShowTouchPoints) { for (PointerTracker tracker : mPointerTrackers) { int startX = tracker.getStartX(); int startY = tracker.getStartY(); int lastX = tracker.getLastX(); int lastY = tracker.getLastY(); paint.setAlpha(128); paint.setColor(0xFFFF0000); canvas.drawCircle(startX, startY, 3, paint); canvas.drawLine(startX, startY, lastX, lastY, paint); paint.setColor(0xFF0000FF); canvas.drawCircle(lastX, lastY, 3, paint); paint.setColor(0xFF00FF00); canvas.drawCircle((startX + lastX) / 2, (startY + lastY) / 2, 2, paint); } } } mDrawPending = false; mDirtyRect.setEmpty(); } // TODO: clean up this method. private void dismissKeyPreview() { for (PointerTracker tracker : mPointerTrackers) tracker.updateKey(NOT_A_KEY); showPreview(NOT_A_KEY, null); } public void showPreview(int keyIndex, PointerTracker tracker) { int oldKeyIndex = mOldPreviewKeyIndex; mOldPreviewKeyIndex = keyIndex; // If key changed and preview is on ... if (oldKeyIndex != keyIndex && mShowPreview) { if (keyIndex == NOT_A_KEY) { mHandler.cancelPopupPreview(); mHandler.dismissPreview(DELAY_AFTER_PREVIEW); } else if (tracker != null) { mHandler.popupPreview(DELAY_BEFORE_PREVIEW, keyIndex, tracker); } } } private void showKey(final int keyIndex, PointerTracker tracker) { Key key = tracker.getKey(keyIndex); if (key == null) return; if (key.icon != null) { mPreviewText.setCompoundDrawables(null, null, null, key.iconPreview != null ? key.iconPreview : key.icon); mPreviewText.setText(null); } else { mPreviewText.setCompoundDrawables(null, null, null, null); mPreviewText.setText(adjustCase(tracker.getPreviewText(key))); if (key.label.length() > 1 && key.codes.length < 2) { mPreviewText.setTextSize(TypedValue.COMPLEX_UNIT_PX, mKeyTextSize); mPreviewText.setTypeface(Typeface.DEFAULT_BOLD); } else { mPreviewText.setTextSize(TypedValue.COMPLEX_UNIT_PX, mPreviewTextSizeLarge); mPreviewText.setTypeface(mKeyTextStyle); } } mPreviewText.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED)); int popupWidth = Math.max(mPreviewText.getMeasuredWidth(), key.width + mPreviewText.getPaddingLeft() + mPreviewText.getPaddingRight()); final int popupHeight = mPreviewHeight; LayoutParams lp = mPreviewText.getLayoutParams(); if (lp != null) { lp.width = popupWidth; lp.height = popupHeight; } int popupPreviewX = key.x - mPreviewText.getPaddingLeft() + getPaddingLeft(); int popupPreviewY = key.y - popupHeight + mPreviewOffset; mHandler.cancelDismissPreview(); if (mOffsetInWindow == null) { mOffsetInWindow = new int[2]; getLocationInWindow(mOffsetInWindow); mOffsetInWindow[0] += mPopupPreviewOffsetX; // Offset may be zero mOffsetInWindow[1] += mPopupPreviewOffsetY; // Offset may be zero int[] mWindowLocation = new int[2]; getLocationOnScreen(mWindowLocation); mWindowY = mWindowLocation[1]; } // Set the preview background state mPreviewText.getBackground().setState( key.popupResId != 0 ? LONG_PRESSABLE_STATE_SET : EMPTY_STATE_SET); popupPreviewX += mOffsetInWindow[0]; popupPreviewY += mOffsetInWindow[1]; // If the popup cannot be shown above the key, put it on the side if (popupPreviewY + mWindowY < 0) { // If the key you're pressing is on the left side of the keyboard, show the popup on // the right, offset by enough to see at least one key to the left/right. if (key.x + key.width <= getWidth() / 2) { popupPreviewX += (int) (key.width * 2.5); } else { popupPreviewX -= (int) (key.width * 2.5); } popupPreviewY += popupHeight; } if (mPreviewPopup.isShowing()) { mPreviewPopup.update(popupPreviewX, popupPreviewY, popupWidth, popupHeight); } else { mPreviewPopup.setWidth(popupWidth); mPreviewPopup.setHeight(popupHeight); mPreviewPopup.showAtLocation(mMiniKeyboardParent, Gravity.NO_GRAVITY, popupPreviewX, popupPreviewY); } mPreviewText.setVisibility(VISIBLE); } /** * Requests a redraw of the entire keyboard. Calling {@link #invalidate} is not sufficient * because the keyboard renders the keys to an off-screen buffer and an invalidate() only * draws the cached buffer. * @see #invalidateKey(Key) */ public void invalidateAllKeys() { mDirtyRect.union(0, 0, getWidth(), getHeight()); mDrawPending = true; invalidate(); } /** * Invalidates a key so that it will be redrawn on the next repaint. Use this method if only * one key is changing it's content. Any changes that affect the position or size of the key * may not be honored. * @param key key in the attached {@link Keyboard}. * @see #invalidateAllKeys */ public void invalidateKey(Key key) { if (key == null) return; mInvalidatedKey = key; mDirtyRect.union(key.x + getPaddingLeft(), key.y + getPaddingTop(), key.x + key.width + getPaddingLeft(), key.y + key.height + getPaddingTop()); onBufferDraw(); invalidate(key.x + getPaddingLeft(), key.y + getPaddingTop(), key.x + key.width + getPaddingLeft(), key.y + key.height + getPaddingTop()); } private boolean openPopupIfRequired(int keyIndex, PointerTracker tracker) { // Check if we have a popup layout specified first. if (mPopupLayout == 0) { return false; } Key popupKey = tracker.getKey(keyIndex); if (popupKey == null) return false; boolean result = onLongPress(popupKey); if (result) { dismissKeyPreview(); tracker.setAlreadyProcessed(); } return result; } private View inflateMiniKeyboardContainer(Key popupKey) { int popupKeyboardId = popupKey.popupResId; LayoutInflater inflater = (LayoutInflater)getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE); View container = inflater.inflate(mPopupLayout, null); if (container == null) throw new NullPointerException(); LatinKeyboardBaseView miniKeyboard = (LatinKeyboardBaseView)container.findViewById(R.id.LatinKeyboardBaseView); miniKeyboard.setOnKeyboardActionListener(new OnKeyboardActionListener() { public void onKey(int primaryCode, int[] keyCodes, int x, int y) { mKeyboardActionListener.onKey(primaryCode, keyCodes, x, y); dismissPopupKeyboard(); } public void onText(CharSequence text) { mKeyboardActionListener.onText(text); dismissPopupKeyboard(); } public void onCancel() { dismissPopupKeyboard(); } public void swipeLeft() { } public void swipeRight() { } public void swipeUp() { } public void swipeDown() { } public void onPress(int primaryCode) { mKeyboardActionListener.onPress(primaryCode); } public void onRelease(int primaryCode) { mKeyboardActionListener.onRelease(primaryCode); } }); // Override default ProximityKeyDetector. miniKeyboard.mKeyDetector = new MiniKeyboardKeyDetector(mMiniKeyboardSlideAllowance); Keyboard keyboard; if (popupKey.popupCharacters != null) { keyboard = new Keyboard(getContext(), popupKeyboardId, popupKey.popupCharacters, -1, getPaddingLeft() + getPaddingRight()); } else { keyboard = new Keyboard(getContext(), popupKeyboardId); } miniKeyboard.setKeyboard(keyboard); miniKeyboard.setPopupParent(this); container.measure(MeasureSpec.makeMeasureSpec(getWidth(), MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(getHeight(), MeasureSpec.AT_MOST)); return container; } /** * Called when a key is long pressed. By default this will open any popup keyboard associated * with this key through the attributes popupLayout and popupCharacters. * @param popupKey the key that was long pressed * @return true if the long press is handled, false otherwise. Subclasses should call the * method on the base class if the subclass doesn't wish to handle the call. */ protected boolean onLongPress(Key popupKey) { // TODO if popupKey.popupCharacters has only one letter, send it as key without opening // mini keyboard. if (popupKey.popupResId == 0) return false; View container = mMiniKeyboardCache.get(popupKey); if (container == null) { container = inflateMiniKeyboardContainer(popupKey); mMiniKeyboardCache.put(popupKey, container); } mMiniKeyboard = (LatinKeyboardBaseView)container.findViewById(R.id.LatinKeyboardBaseView); if (mWindowOffset == null) { mWindowOffset = new int[2]; getLocationInWindow(mWindowOffset); } // HACK: Have the leftmost number in the popup characters right above the key boolean isNumberAtLeftmost = false; if (popupKey.popupCharacters != null && popupKey.popupCharacters.length() > 1) { char leftmostChar = popupKey.popupCharacters.charAt(0); isNumberAtLeftmost = leftmostChar >= '0' && leftmostChar <= '9'; } int popupX = popupKey.x + mWindowOffset[0]; int popupY = popupKey.y + mWindowOffset[1]; if (isNumberAtLeftmost) { popupX -= container.getPaddingLeft(); } else { popupX += popupKey.width + getPaddingLeft(); popupX -= container.getMeasuredWidth(); popupX += container.getPaddingRight(); } popupY += getPaddingTop(); popupY -= container.getMeasuredHeight(); popupY += container.getPaddingBottom(); final int x = popupX; final int y = popupY; int adjustedX = x; if (x < 0) { adjustedX = 0; } else if (x > (getMeasuredWidth() - container.getMeasuredWidth())) { adjustedX = getMeasuredWidth() - container.getMeasuredWidth(); } mMiniKeyboardOriginX = adjustedX + container.getPaddingLeft() - mWindowOffset[0]; mMiniKeyboardOriginY = y + container.getPaddingTop() - mWindowOffset[1]; mMiniKeyboard.setPopupOffset(adjustedX, y); mMiniKeyboard.setShifted(isShifted()); // Mini keyboard needs no pop-up key preview displayed. mMiniKeyboard.setPreviewEnabled(false); mMiniKeyboardPopup.setContentView(container); mMiniKeyboardPopup.setWidth(container.getMeasuredWidth()); mMiniKeyboardPopup.setHeight(container.getMeasuredHeight()); mMiniKeyboardPopup.showAtLocation(this, Gravity.NO_GRAVITY, x, y); // Inject down event on the key to mini keyboard. long eventTime = System.currentTimeMillis(); mMiniKeyboardPopupTime = eventTime; MotionEvent downEvent = generateMiniKeyboardMotionEvent(MotionEvent.ACTION_DOWN, popupKey.x + popupKey.width / 2, popupKey.y + popupKey.height / 2, eventTime); mMiniKeyboard.onTouchEvent(downEvent); downEvent.recycle(); invalidateAllKeys(); return true; } private MotionEvent generateMiniKeyboardMotionEvent(int action, int x, int y, long eventTime) { return MotionEvent.obtain(mMiniKeyboardPopupTime, eventTime, action, x - mMiniKeyboardOriginX, y - mMiniKeyboardOriginY, 0); } private PointerTracker getPointerTracker(final int id) { final ArrayList<PointerTracker> pointers = mPointerTrackers; final Key[] keys = mKeys; final OnKeyboardActionListener listener = mKeyboardActionListener; // Create pointer trackers until we can get 'id+1'-th tracker, if needed. for (int i = pointers.size(); i <= id; i++) { final PointerTracker tracker = new PointerTracker(i, mHandler, mKeyDetector, this, mHasDistinctMultitouch); if (keys != null) tracker.setKeyboard(keys, mKeyHysteresisDistance); if (listener != null) tracker.setOnKeyboardActionListener(listener); pointers.add(tracker); } return pointers.get(id); } @Override public boolean onTouchEvent(MotionEvent me) { final int pointerCount = me.getPointerCount(); final int action = me.getActionMasked(); // TODO: cleanup this code into a multi-touch to single-touch event converter class? // If the device does not have distinct multi-touch support panel, ignore all multi-touch // events except a transition from/to single-touch. if (!mHasDistinctMultitouch && pointerCount > 1 && mOldPointerCount > 1) { return true; } // Track the last few movements to look for spurious swipes. mSwipeTracker.addMovement(me); // We must disable gesture detector while mini-keyboard is on the screen. if (mMiniKeyboard == null && mGestureDetector.onTouchEvent(me)) { dismissKeyPreview(); mHandler.cancelKeyTimers(); return true; } final long eventTime = me.getEventTime(); final int index = me.getActionIndex(); final int id = me.getPointerId(index); final int x = (int)me.getX(index); final int y = (int)me.getY(index); // Needs to be called after the gesture detector gets a turn, as it may have // displayed the mini keyboard if (mMiniKeyboard != null) { MotionEvent translated = generateMiniKeyboardMotionEvent(action, x, y, eventTime); mMiniKeyboard.onTouchEvent(translated); translated.recycle(); return true; } if (mHandler.isInKeyRepeat()) { // It will keep being in the key repeating mode while the key is being pressed. if (action == MotionEvent.ACTION_MOVE) { return true; } final PointerTracker tracker = getPointerTracker(id); // Key repeating timer will be canceled if 2 or more keys are in action, and current // event (UP or DOWN) is non-modifier key. if (pointerCount > 1 && !tracker.isModifier()) { mHandler.cancelKeyRepeatTimer(); } // Up event will pass through. } // TODO: cleanup this code into a multi-touch to single-touch event converter class? // Translate mutli-touch event to single-touch events on the device that has no distinct // multi-touch panel. if (!mHasDistinctMultitouch) { // Use only main (id=0) pointer tracker. PointerTracker tracker = getPointerTracker(0); int oldPointerCount = mOldPointerCount; if (pointerCount == 1 && oldPointerCount == 2) { // Multi-touch to single touch transition. // Send a down event for the latest pointer. tracker.onDownEvent(x, y, eventTime); } else if (pointerCount == 2 && oldPointerCount == 1) { // Single-touch to multi-touch transition. // Send an up event for the last pointer. tracker.onUpEvent(tracker.getLastX(), tracker.getLastY(), eventTime); } else if (pointerCount == 1 && oldPointerCount == 1) { tracker.onTouchEvent(action, x, y, eventTime); } else { Log.w(TAG, "Unknown touch panel behavior: pointer count is " + pointerCount + " (old " + oldPointerCount + ")"); } mOldPointerCount = pointerCount; return true; } if (action == MotionEvent.ACTION_MOVE) { for (int i = 0; i < pointerCount; i++) { PointerTracker tracker = getPointerTracker(me.getPointerId(i)); tracker.onMoveEvent((int)me.getX(i), (int)me.getY(i), eventTime); } } else { PointerTracker tracker = getPointerTracker(id); switch (action) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_DOWN: onDownEvent(tracker, x, y, eventTime); break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_POINTER_UP: onUpEvent(tracker, x, y, eventTime); break; case MotionEvent.ACTION_CANCEL: onCancelEvent(tracker, x, y, eventTime); break; } } return true; } private void onDownEvent(PointerTracker tracker, int x, int y, long eventTime) { if (tracker.isOnModifierKey(x, y)) { // Before processing a down event of modifier key, all pointers already being tracked // should be released. mPointerQueue.releaseAllPointersExcept(null, eventTime); } tracker.onDownEvent(x, y, eventTime); mPointerQueue.add(tracker); } private void onUpEvent(PointerTracker tracker, int x, int y, long eventTime) { if (tracker.isModifier()) { // Before processing an up event of modifier key, all pointers already being tracked // should be released. mPointerQueue.releaseAllPointersExcept(tracker, eventTime); } else { int index = mPointerQueue.lastIndexOf(tracker); if (index >= 0) { mPointerQueue.releaseAllPointersOlderThan(tracker, eventTime); } else { Log.w(TAG, "onUpEvent: corresponding down event not found for pointer " + tracker.mPointerId); } } tracker.onUpEvent(x, y, eventTime); mPointerQueue.remove(tracker); } private void onCancelEvent(PointerTracker tracker, int x, int y, long eventTime) { tracker.onCancelEvent(x, y, eventTime); mPointerQueue.remove(tracker); } protected void swipeRight() { mKeyboardActionListener.swipeRight(); } protected void swipeLeft() { mKeyboardActionListener.swipeLeft(); } protected void swipeUp() { mKeyboardActionListener.swipeUp(); } protected void swipeDown() { mKeyboardActionListener.swipeDown(); } public void closing() { if (mPreviewPopup.isShowing()) { mPreviewPopup.dismiss(); } mHandler.cancelAllMessages(); dismissPopupKeyboard(); mBuffer = null; mCanvas = null; mMiniKeyboardCache.clear(); } @Override public void onDetachedFromWindow() { super.onDetachedFromWindow(); closing(); } private void dismissPopupKeyboard() { if (mMiniKeyboardPopup.isShowing()) { mMiniKeyboardPopup.dismiss(); mMiniKeyboard = null; mMiniKeyboardOriginX = 0; mMiniKeyboardOriginY = 0; invalidateAllKeys(); } } public boolean handleBack() { if (mMiniKeyboardPopup.isShowing()) { dismissPopupKeyboard(); return true; } return false; } }
4f9eb11c6a211612d41a96fcb677cef6510d0dcb
b9a51deb97fc6a2dffcc7f36f8aa121541fd1608
/src/main/java/org/docx4j/math/STFType.java
a88bf52cb542db8907ffddb2b7968508f66663fb
[ "Apache-2.0" ]
permissive
vansuca/docx4j
c592ea04e5736edef46a4a3e7ffab84cbc0b206f
72d061bd2606b58b8de7b36d203b58232a552e49
refs/heads/master
2020-12-30T19:23:31.287757
2012-11-28T02:08:47
2012-11-28T02:08:47
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,207
java
/* * Copyright 2010-2012, Plutext Pty Ltd. * * This file is part of pptx4j, a component of docx4j. docx4j is licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.docx4j.math; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlEnumValue; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for ST_FType. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="ST_FType"> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}string"> * &lt;enumeration value="bar"/> * &lt;enumeration value="skw"/> * &lt;enumeration value="lin"/> * &lt;enumeration value="noBar"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "ST_FType") @XmlEnum public enum STFType { /** * Bar Fraction * */ @XmlEnumValue("bar") BAR("bar"), /** * Skewed * */ @XmlEnumValue("skw") SKW("skw"), /** * Linear Fraction * */ @XmlEnumValue("lin") LIN("lin"), /** * No-Bar Fraction (Stack) * */ @XmlEnumValue("noBar") NO_BAR("noBar"); private final String value; STFType(String v) { value = v; } public String value() { return value; } public static STFType fromValue(String v) { for (STFType c: STFType.values()) { if (c.value.equals(v)) { return c; } } throw new IllegalArgumentException(v); } }
d67934e37495dcf3998204d0c54fe2ee5b4810fc
c01c5661c0d30e15c17f5daed235a3c240e224bb
/src/me/cynicalnicole/sleeptracker/Commands/TimeAwake.java
8d6aac9fa108cdea5b52f4f5e8e137772b539757
[]
no_license
Yhumi/SleepTracker
cc63952a1ae1bf07843f90c65a79253562f0cd3b
809c2f843c53f02e63103f5f9d1d557b02356f4b
refs/heads/master
2022-12-21T04:15:29.564359
2020-07-08T00:16:23
2020-07-08T00:16:23
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,390
java
/* * 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 me.cynicalnicole.sleeptracker.Commands; import java.util.HashMap; import java.util.Map; import me.cynicalnicole.sleeptracker.MessageFormatting; import me.cynicalnicole.sleeptracker.Models.PlayerSleepYML; import me.cynicalnicole.sleeptracker.SleepTracker; import org.bukkit.Bukkit; import org.bukkit.World; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; /** * * @author Nicole */ public class TimeAwake implements CommandExecutor { SleepTracker instance; public TimeAwake(SleepTracker instance) { instance.getCommand("timeawake").setExecutor(this); this.instance = instance; } @Override public boolean onCommand(CommandSender cs, Command cmnd, String string, String[] strings) { if (!(cs instanceof Player)) return true; if (!((Player) cs).hasPermission("timeawake.self") && strings.length == 0) { //cs.sendMessage(String.format("%sYou do not have permission to check your days awake.", org.bukkit.ChatColor.RED)); cs.sendMessage(MessageFormatting.getMessageString("messages.errors.timeawake-self")); return true; } Player target = (Player) cs; if (strings.length > 1) { //cs.sendMessage(String.format("%sUnknown command arguments.", org.bukkit.ChatColor.RED)); cs.sendMessage(MessageFormatting.getMessageString("messages.errors.unknown-arguments")); return true; } if (strings.length == 1) { Player player = (Player) cs; if (!player.hasPermission("timeawake.others")) { //cs.sendMessage(String.format("%sYou do not have permission to check awake time for other players.", org.bukkit.ChatColor.RED)); cs.sendMessage(MessageFormatting.getMessageString("messages.errors.timeawake-others")); return true; } target = getOnlinePlayerByName(strings[0]); if (target == null) { //cs.sendMessage(String.format("%sThe specified player does not exist.", org.bukkit.ChatColor.RED)); cs.sendMessage(MessageFormatting.getMessageString("messages.errors.unknown-player")); return true; } if (target == (Player)cs && !((Player) cs).hasPermission("timeawake.self")) { //cs.sendMessage(String.format("%sYou do not have permission to check your days awake.", org.bukkit.ChatColor.RED)); cs.sendMessage(MessageFormatting.getMessageString("messages.errors.timeawake-self")); return true; } } PlayerSleepYML playerSleep = instance.getPlayerSleep(target.getUniqueId().toString()); if (playerSleep == null) { //cs.sendMessage(String.format("%sThere was an error fetching the sleep information for %s.", org.bukkit.ChatColor.RED, target.getName())); Map<MessageFormatting.PlaceholderType, String> variables = new HashMap<MessageFormatting.PlaceholderType, String>(); variables.put(MessageFormatting.PlaceholderType.PLAYER, target.getName()); cs.sendMessage(MessageFormatting.getMessageString("messages.errors.player-info", variables)); return true; } int daysSinceSlept = getMinecraftDaysSinceLastSlept(playerSleep.getLastSleepTick()); Map<MessageFormatting.PlaceholderType, String> variables = new HashMap<MessageFormatting.PlaceholderType, String>(); variables.put(MessageFormatting.PlaceholderType.PLAYER, target.getName()); if (daysSinceSlept > 0) { variables.put(MessageFormatting.PlaceholderType.AWAKE_TIME, String.valueOf(daysSinceSlept)); cs.sendMessage(MessageFormatting.getMessageString("messages.timeawake", variables)); } else { cs.sendMessage(MessageFormatting.getMessageString("messages.timeawake-slept", variables)); } //cs.sendMessage(String.format("%s%s has not slept in %s days", org.bukkit.ChatColor.LIGHT_PURPLE, target.getName(), String.valueOf(daysSinceSlept))); return true; } private Player getOnlinePlayerByName(String playerName) { Player player = instance.getServer().getPlayer(playerName); if (player == null) { for (Player online : instance.getServer().getOnlinePlayers()) { if (online.getDisplayName().equals(playerName)) { player = online; break; } } } return player; } private int getMinecraftDaysSinceLastSlept(long lastSleptTick) { long currentWorldTick = instance.getWorld().getFullTime(); long diff = currentWorldTick - lastSleptTick; //24000 ticks = 1 minecraft day return (int) Math.floor(diff / 24000); } }
26469e35141821568e328fa584a29e8d07a3203d
45456cebbec27684596dc2e932bbccbdde2b9ff2
/src/main/java/io/banditoz/mchelper/regexable/Regexable.java
2893f993ec5117c92edfdd5d40acc3159e5a1349
[ "Apache-2.0" ]
permissive
HeyBanditoz/mchelper
71ee1542b7902ecf8d394aee8039921489bba6d6
717a27e2edb23e9a6fc4c33cc82cdd1c388d03cf
refs/heads/master
2023-09-05T13:58:35.454635
2023-09-05T05:20:52
2023-09-05T05:20:52
227,871,432
0
1
null
null
null
null
UTF-8
Java
false
false
2,293
java
package io.banditoz.mchelper.regexable; import io.banditoz.mchelper.stats.Status; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.HashMap; import java.util.regex.Pattern; public abstract class Regexable { protected abstract Status onRegexCommand(RegexCommandEvent rce) throws Exception; protected abstract Pattern regex(); protected final Logger LOGGER = LoggerFactory.getLogger(getClass()); /** * Return this regexable's <i>channel-wide</i> cooldown in seconds. Override and return what you want the cooldown to be. * * @return The cooldown. */ protected int getCooldown() { return 0; } protected final HashMap<String, Instant> cooldowns = getCooldown() > 0 ? new HashMap<>() : null; /** * Whether or not the passed in String passes regex. * * @param args The args to check against implemented {@link Regexable}'s {@link java.util.regex.Matcher}. * @return Whether or not the regex matches. */ public boolean containsRegexable(String args) { return regex().matcher(args).find(); } /** * Returns the {@link Pattern} associated with this {@link Regexable}. * * @return The {@link Pattern}. */ public Pattern getPattern() { return this.regex(); } /** * Checks if the channel is on cooldown. * * @param id The ID to check. * @return true if the channel are allowed to run the regexable, false if they are still on cooldown. */ protected boolean handleCooldown(String id) { // TODO no copypaste :( if (getCooldown() > 0) { Instant cooldown = cooldowns.get(id); if (cooldown == null) { Instant instant = Instant.now().plus(getCooldown(), ChronoUnit.SECONDS); cooldowns.put(id, instant); return true; } else if (Instant.now().isAfter(cooldown)) { cooldowns.replace(id, Instant.now().plus(getCooldown(), ChronoUnit.SECONDS)); return true; } else { return false; } } else { return true; } } }
7be88bc52a9433c958513ffd9935da273ce455fc
45ee32435c345790cae1f10111e37f860395f1ea
/art-extension/opttests/src/OptimizationTests/ShortLeafMethodsInlining/InvokeVirtual_shr_long_NVS_001/Test.java
efbe5fb59ad84de88eb2df9290e9372463c36c57
[ "Apache-2.0", "NCSA", "LicenseRef-scancode-unknown-license-reference" ]
permissive
android-art-intel/Nougat
b93eb0bc947088ba55d03e62324af88d332c5e93
ea41b6bfe5c6b62a3163437438b21568cc783a24
refs/heads/master
2020-07-05T18:53:19.370466
2016-12-16T04:23:40
2016-12-16T04:23:40
73,984,816
9
1
null
null
null
null
UTF-8
Java
false
false
805
java
/* * Copyright (C) 2016 Intel Corporation * * 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 OptimizationTests.ShortLeafMethodsInlining.InvokeVirtual_shr_long_NVS_001; class Test { public long simple_method(long jj, long kk) { jj = jj >> kk; return jj; } }
54e23c6ef829278fe522beef230b06c27ff6316c
1257e863842c831edc6d05a373cd2b2169df2571
/src/main/java/com/cookmyfood/app/repository/package-info.java
1173db3bc882ed14997f312b59383f835aaf400c
[]
no_license
naru6be/cookmyfood2
9170b013a7a01ee811af9307c7bdaf4b570ffd73
243c6ea625c853a21b88da3b91035021ca1df787
refs/heads/master
2022-12-23T23:26:57.547947
2019-10-05T21:38:24
2019-10-05T21:38:24
211,410,154
0
0
null
2022-12-16T05:03:32
2019-09-27T22:21:33
Java
UTF-8
Java
false
false
80
java
/** * Spring Data JPA repositories. */ package com.cookmyfood.app.repository;
dd9a28f02d3dd1328454094b3b60e936952bd3e7
ff55349eac5e718f9b91072805a5bb0b6b7305c8
/Ftp/src/main/java/Ftp.java
e4e343369fc78db5f4d56f406d2a7cf7b29486d8
[]
no_license
helloBosom/IOCommunication
a794e0822a1882584a6d611044c74691f8acffbf
5d2985ad6ea85a2a3003fb6bc2131345c6ae1f98
refs/heads/master
2021-08-30T18:47:56.428927
2017-12-19T01:43:45
2017-12-19T01:43:45
114,706,037
0
0
null
null
null
null
UTF-8
Java
false
false
142
java
import sun.net.ftp.FtpClient; public class Ftp { FtpClient ftpClient = FtpClient.create(); public static void main(String[] args) { } }
835f1ef337b2be1e0e84294174cbf171a76251c7
08c66abe3bf28755e32145aa49409ed2249f8c47
/Sample Bots/Java/entelect-battleships/src/main/java/net/avdw/battlefight/struct/Direction.java
5c93ae0ca2c7ef001abf98caea32874044cb7f22
[]
no_license
avanderw/jbattlefight
fb8b0e9f3b041dc40661cf8782001cff795f3429
80b603590b5e4c4b37bddd2e0619d510f6dc139f
refs/heads/master
2021-01-20T17:07:18.659616
2017-09-18T08:24:36
2017-09-18T08:24:36
90,862,739
0
0
null
null
null
null
UTF-8
Java
false
false
622
java
package net.avdw.battlefight.struct; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ThreadLocalRandom; public enum Direction { North, South, East, West; static public Direction random() { return Direction.values()[ThreadLocalRandom.current().nextInt(4)]; } static public Direction random(Direction excl) { List<Direction> all = new ArrayList(); all.add(North); all.add(South); all.add(East); all.add(West); all.remove(excl); return all.get(ThreadLocalRandom.current().nextInt(3)); } }
7114615873bf17e0c900d1e5d3891a5e96851640
891520a04ba79fb7e6a2c292785597010d2696d7
/RestClient.java
cde27221add0d1ea9610caf9a76771c4204cf5be
[]
no_license
mrboopathi/restclient
45e1de2d8ceb31be380413f5fd6361f2a41dd0c5
065f339d6dd8609426e91f10c9493257b7fbd8f3
refs/heads/main
2023-01-10T10:07:49.340095
2020-11-16T09:22:59
2020-11-16T09:22:59
313,228,573
0
0
null
null
null
null
UTF-8
Java
false
false
3,278
java
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLEncoder; import java.util.Scanner; import javax.net.ssl.HttpsURLConnection; import org.json.JSONException; import org.json.simple.JSONObject; import org.json.simple.JSONArray; import org.json.simple.parser.JSONParser; import org.json.simple.parser.ParseException; import java.security.cert.Certificate; public class RestClient { public static void main(String[] args) throws IOException, JSONException, ParseException{ Scanner scanner = new Scanner(System.in); String name ="";// scanner.nextLine(); String jsonString = getPersonData(name); JSONParser parser = new JSONParser(); JSONArray array= (JSONArray) parser.parse(jsonString); for(int i=0;i<array.size();i++) { JSONObject jsonobj_1 = (JSONObject)array.get(i); System.out.println("\n title : " +jsonobj_1.get("title")); } scanner.close(); } public static String getPersonData(String id) throws IOException{ String https_url = "https://jsonplaceholder.typicode.com/todos"; URL url = null; url = new URL(https_url); HttpsURLConnection con = (HttpsURLConnection)url.openConnection(); System.out.println("Response Code : " + con.getResponseCode()); System.out.println("Cipher Suite : " + con.getCipherSuite()); System.out.println("\n"); Certificate[] certs = con.getServerCertificates(); for(Certificate cert : certs){ System.out.println("Cert Type : " + cert.getType()); System.out.println("Cert Hash Code : " + cert.hashCode()); System.out.println("Cert Public Key Algorithm : " + cert.getPublicKey().getAlgorithm()); System.out.println("Cert Public Key Format : " + cert.getPublicKey().getFormat()); System.out.println("\n"); } int responseCode = con.getResponseCode(); if(responseCode == 200){ String response = ""; Scanner scanner = new Scanner(con.getInputStream()); while(scanner.hasNextLine()){ response += scanner.nextLine(); response += "\n"; } scanner.close(); return response; } // an error happened return null; } public static void setPersonData(String name, String birthYear, String about,int id) throws IOException{ HttpURLConnection connection = (HttpURLConnection) new URL("https://reqres.in/api/products/" + id).openConnection(); connection.setRequestMethod("POST"); String postData = "name=" + URLEncoder.encode(name); postData += "&about=" + URLEncoder.encode(about); postData += "&birthYear=" + birthYear; connection.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream()); wr.write(postData); wr.flush(); int responseCode = connection.getResponseCode(); if(responseCode == 200){ System.out.println("POST was successful."); } else if(responseCode == 401){ System.out.println("Wrong password."); } } }
26f22de77898c00d402b9ffcec65ae6b31323b1d
2f068faa753720fba699434ba8650650f079f79d
/core_html/src/main/java/at/resch/web/html/elements/LEGEND.java
79ebe4b1aee0f9be34ed9af8f53df78ad82c5d61
[]
no_license
FelixResch/Extensible-Java-Web-Server
558372a6fee804fb071082e2a79eb47c0219c6d3
7420f1d59234da3e1c0a5327971af628d2e26147
refs/heads/master
2021-01-22T09:33:08.023212
2014-08-13T10:56:48
2014-08-13T10:56:48
null
0
0
null
null
null
null
UTF-8
Java
false
false
194
java
package at.resch.web.html.elements; public class LEGEND extends HTMLElement { public LEGEND(Object... children) { super("legend", children); } public LEGEND() { super("legend"); } }
19774eabcdc80cba2a01c9e6d61420678b7dbe16
b8a6ce11d3dc4a00b9d71323e343a083bfc8598d
/src/main/java/com/bravebucks/eve/domain/esi/UniverseName.java
db5071aa3dfe345b93f0e479525dd89f5c367605
[ "MIT" ]
permissive
bahrmichael/brave-bucks
c766ed6fa2ca130aa5063ef1effb2d053326ff6d
69f379b69b8705dac5f35d492ddad7971a49f31f
refs/heads/master
2022-12-07T18:39:36.298233
2020-12-11T17:54:58
2020-12-11T17:54:58
103,058,515
3
4
MIT
2022-12-04T14:05:17
2017-09-10T20:13:04
Java
UTF-8
Java
false
false
723
java
package com.bravebucks.eve.domain.esi; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class UniverseName { @JsonProperty("id") private Integer id; @JsonProperty("name") private String name; public UniverseName() { } public UniverseName(Integer id, String name) { this.id = id; this.name = name; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
ec61dd6ba04a1db46bf45fecb5f35423aadd0174
129b8f2babed41a4684066d41594d93d50bc5ccd
/subprojects/swen221/src/main/java/com/hjwylde/uni/swen221/midterm/minesweeper/moves/ExposeMove.java
4249df6d374b48d3dc396f6f14a0b2e5d16a0bd1
[]
no_license
ltfij/university
4eca16e0b370bf822db21ebd751d3fa927650d37
7aa9a752440fe0288df3de677db3f1d658972db2
refs/heads/master
2021-05-29T19:55:15.109642
2015-08-31T08:16:51
2015-08-31T08:16:51
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,922
java
package com.hjwylde.uni.swen221.midterm.minesweeper.moves; import com.hjwylde.uni.swen221.midterm.minesweeper.Game; import com.hjwylde.uni.swen221.midterm.minesweeper.Position; import com.hjwylde.uni.swen221.midterm.minesweeper.SyntaxError; import com.hjwylde.uni.swen221.midterm.minesweeper.squares.BlankSquare; import com.hjwylde.uni.swen221.midterm.minesweeper.squares.Square; /* * Code for Mid-term Test, SWEN 221 Name: Henry J. Wylde Usercode: wyldehenr ID: 300224283 */ /** * Represents a move that exposes a square. The square may contain a bomb, or be blank. However, it * should not be flagged. * * @author David J. Pearce * */ public class ExposeMove extends Move { /** * Construct an ExposeMove at a given position on the board. * * @param position the position. */ public ExposeMove(Position position) { super(position); } /** * Apply this move to a given game and check it is valid. A square can only be exposed if it is * not already exposed. And, if either a bomb is exposed or there are no remaining unexposed * squares, then this should be an EndGame move. * * @param game --- game to which this move is applied. */ @Override public void apply(Game game) throws SyntaxError { Square square = game.squareAt(position); // Checks if (!square.isHidden() || square.isFlagged()) throw new SyntaxError("Can't click on a flagged or non-hidden square."); // Check for whether this square should trigger a cascade effect. if (game.isWithinBounds(position)) if (square instanceof BlankSquare) if (((BlankSquare) square).getNumberOfBombsAround() == 0) game.cascade(position); square.setHidden(false); // now exposed } @Override public String toString() { return "E" + position; } }
745e88ac1cbc32a25059962df5e6f2e49e5f0620
2c651aecad964a16d548b443d60f2a95cb1a4080
/java/src/main/java/com/longdo/map/MapActivity.java
770086722b070d6a5d0af3cd42cc75e42d5d78eb
[]
no_license
MetamediaTechnology/longdo-map-sdk-android
fdd0d5957a9322c335d3d13e888556bb453153a4
975a3dc463a1e8f57a609f70866f4f7f42cf296e
refs/heads/master
2023-02-27T12:39:21.569297
2021-02-08T05:46:40
2021-02-08T05:46:40
336,962,550
0
0
null
null
null
null
UTF-8
Java
false
false
783
java
package com.longdo.map; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import com.longdo.api.IMapListener; import com.longdo.api.Map; import com.longdo.api.MapGLSurfaceView; import com.longdo.map.java.R; public class MapActivity extends AppCompatActivity implements IMapListener { private Map map; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.map_activity); setupView(); } private void setupView() { setupMap(); } private void setupMap() { ((MapGLSurfaceView) findViewById(R.id.map_view)).setListener(this); } @Override public void onMapCreated(Map map) { this.map = map; } }
e8011db60406fea72d977c107ccbcb4bfbc7c689
e93c383193af084341c7db45acc76818da6a7c16
/1841030CIA/app/src/main/java/com/example/lab4/login.java
a772920a16f8803972ee94efcbeb44ba8c3cd49e
[]
no_license
RGMishan/MobileApplication
c96d27bc7a47fbebb82bd322dbaf58d38aaa0a2a
a4801b4b3956b92838041693d7d518356a390fe6
refs/heads/master
2023-01-07T13:35:21.103353
2020-11-19T13:42:51
2020-11-19T13:42:51
268,712,509
0
2
null
null
null
null
UTF-8
Java
false
false
3,589
java
package com.example.lab4; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.text.TextWatcher; import android.text.method.HideReturnsTransformationMethod; import android.text.method.PasswordTransformationMethod; import android.view.View; import android.widget.EditText; import android.widget.ImageButton; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class login extends AppCompatActivity { private ImageButton submit; private EditText email; private EditText password; private ImageButton toggle; private Boolean showpass=false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); submit=(ImageButton)findViewById(R.id.submit); email=(EditText)findViewById(R.id.email); password=(EditText)findViewById(R.id.password); toggle=(ImageButton)findViewById(R.id.toggle); final String emailPattern = "[a-zA-Z0-9._-]+@[a-z]+\\.+[a-z]+"; toggle.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(showpass==false){ password.setTransformationMethod(HideReturnsTransformationMethod.getInstance()); password.setSelection(password.getText().length()); showpass=true; } else{ password.setTransformationMethod(PasswordTransformationMethod.getInstance()); password.setSelection(password.getText().length()); showpass=false; } } }); email.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } @Override public void afterTextChanged(Editable s) { } }); submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String e=email.getText().toString().trim(); String P=password.getText().toString(); if(e.isEmpty() || P.isEmpty()) { Toast.makeText(login.this,"Input Required in both the fields",Toast.LENGTH_LONG).show(); } else if(!e.matches(emailPattern)){ Toast.makeText(login.this,"Invalid Email",Toast.LENGTH_LONG).show(); email.setText(""); password.setText(""); } else if(e.matches("[email protected]")&&P.matches("12345")){ Intent function = new Intent(login.this, MainActivity.class); function.putExtra("Username","Aastha Narang"); startActivity(function); } else if(e.matches("[email protected]")&&P.matches("sir")){ Intent function = new Intent(login.this, MainActivity.class); function.putExtra("Username","Sir"); startActivity(function); } else{ Toast.makeText(login.this,"User does not exist",Toast.LENGTH_LONG).show(); } } }); } }
a8d95c00a1e91ec5858ef4b09ad9977028660d64
1a738af702bf350e3dbedeaf744c66dddd54cd54
/test/Board/CoupleTest.java
0df433fba0dc0621d97bdc1b6f83de70d5210c4e
[]
no_license
CalvinMT/ProjetS6-Saboteur
458be751a811181cee34d892966b12573ec121ac
85d5a30af9569329d6e6d4750aa2c325c3d83c0b
refs/heads/master
2021-06-21T16:53:37.239371
2017-06-02T09:51:32
2017-06-02T09:51:32
90,044,714
0
0
null
null
null
null
UTF-8
Java
false
false
1,179
java
package Board; import org.junit.Assert; import org.junit.Test; /** * Created by oloar on 09/05/2017. */ public class CoupleTest { @Test public void getX() throws Exception { Couple c = new Couple(1, 2); Assert.assertTrue(c.getLine() == 1); } @Test public void getY() throws Exception { Couple c = new Couple(1, 2); Assert.assertTrue(c.getColumn() == 2); } @Test public void setX() throws Exception { Couple c = new Couple(0, 2); Assert.assertTrue(c.getLine() == 0); c.setLine(1); Assert.assertTrue(c.getLine() == 1); } @Test public void setY() throws Exception { Couple c = new Couple(2, 0); Assert.assertTrue(c.getColumn() == 0); c.setColumn(1); Assert.assertTrue(c.getColumn() == 1); } @Test public void equals() throws Exception { Couple c1 = new Couple(0, 1); Couple c2 = new Couple(2, 3); Assert.assertFalse(c1.equals(c2)); Assert.assertFalse(c2.equals(c1)); c2 = new Couple(0, 1); Assert.assertTrue(c1.equals(c2)); Assert.assertTrue(c2.equals(c1)); } }
c306ea05118f763f5d04c133fa4e624aac1d93f7
9573f936174ccbcda704e1b83d596a3f093f727c
/OPERAcraft New/temp/src/minecraft_server/net/minecraft/src/WorldGenDungeons.java
47740addb28fd64657a5ed0a23c21a9d1aa27799
[]
no_license
operacraft/Minecraft
17466d8538be6253f4d689926d177614c6accf5b
89c4012b11cf5fa118cd5e63b0f51d03ee1ddc09
refs/heads/master
2021-01-10T05:54:10.056575
2016-02-24T15:54:29
2016-02-24T15:54:49
51,405,369
1
2
null
null
null
null
UTF-8
Java
false
false
6,903
java
package net.minecraft.src; import java.util.Random; import net.minecraft.src.Block; import net.minecraft.src.Item; import net.minecraft.src.ItemStack; import net.minecraft.src.Material; import net.minecraft.src.TileEntityChest; import net.minecraft.src.TileEntityMobSpawner; import net.minecraft.src.World; import net.minecraft.src.WorldGenerator; public class WorldGenDungeons extends WorldGenerator { public boolean func_76484_a(World p_76484_1_, Random p_76484_2_, int p_76484_3_, int p_76484_4_, int p_76484_5_) { byte var6 = 3; int var7 = p_76484_2_.nextInt(2) + 2; int var8 = p_76484_2_.nextInt(2) + 2; int var9 = 0; int var10; int var11; int var12; for(var10 = p_76484_3_ - var7 - 1; var10 <= p_76484_3_ + var7 + 1; ++var10) { for(var11 = p_76484_4_ - 1; var11 <= p_76484_4_ + var6 + 1; ++var11) { for(var12 = p_76484_5_ - var8 - 1; var12 <= p_76484_5_ + var8 + 1; ++var12) { Material var13 = p_76484_1_.func_72803_f(var10, var11, var12); if(var11 == p_76484_4_ - 1 && !var13.func_76220_a()) { return false; } if(var11 == p_76484_4_ + var6 + 1 && !var13.func_76220_a()) { return false; } if((var10 == p_76484_3_ - var7 - 1 || var10 == p_76484_3_ + var7 + 1 || var12 == p_76484_5_ - var8 - 1 || var12 == p_76484_5_ + var8 + 1) && var11 == p_76484_4_ && p_76484_1_.func_72799_c(var10, var11, var12) && p_76484_1_.func_72799_c(var10, var11 + 1, var12)) { ++var9; } } } } if(var9 >= 1 && var9 <= 5) { for(var10 = p_76484_3_ - var7 - 1; var10 <= p_76484_3_ + var7 + 1; ++var10) { for(var11 = p_76484_4_ + var6; var11 >= p_76484_4_ - 1; --var11) { for(var12 = p_76484_5_ - var8 - 1; var12 <= p_76484_5_ + var8 + 1; ++var12) { if(var10 != p_76484_3_ - var7 - 1 && var11 != p_76484_4_ - 1 && var12 != p_76484_5_ - var8 - 1 && var10 != p_76484_3_ + var7 + 1 && var11 != p_76484_4_ + var6 + 1 && var12 != p_76484_5_ + var8 + 1) { p_76484_1_.func_94571_i(var10, var11, var12); } else if(var11 >= 0 && !p_76484_1_.func_72803_f(var10, var11 - 1, var12).func_76220_a()) { p_76484_1_.func_94571_i(var10, var11, var12); } else if(p_76484_1_.func_72803_f(var10, var11, var12).func_76220_a()) { if(var11 == p_76484_4_ - 1 && p_76484_2_.nextInt(4) != 0) { p_76484_1_.func_72832_d(var10, var11, var12, Block.field_72087_ao.field_71990_ca, 0, 2); } else { p_76484_1_.func_72832_d(var10, var11, var12, Block.field_71978_w.field_71990_ca, 0, 2); } } } } } var10 = 0; while(var10 < 2) { var11 = 0; while(true) { if(var11 < 3) { label210: { var12 = p_76484_3_ + p_76484_2_.nextInt(var7 * 2 + 1) - var7; int var14 = p_76484_5_ + p_76484_2_.nextInt(var8 * 2 + 1) - var8; if(p_76484_1_.func_72799_c(var12, p_76484_4_, var14)) { int var15 = 0; if(p_76484_1_.func_72803_f(var12 - 1, p_76484_4_, var14).func_76220_a()) { ++var15; } if(p_76484_1_.func_72803_f(var12 + 1, p_76484_4_, var14).func_76220_a()) { ++var15; } if(p_76484_1_.func_72803_f(var12, p_76484_4_, var14 - 1).func_76220_a()) { ++var15; } if(p_76484_1_.func_72803_f(var12, p_76484_4_, var14 + 1).func_76220_a()) { ++var15; } if(var15 == 1) { p_76484_1_.func_72832_d(var12, p_76484_4_, var14, Block.field_72077_au.field_71990_ca, 0, 2); TileEntityChest var16 = (TileEntityChest)p_76484_1_.func_72796_p(var12, p_76484_4_, var14); if(var16 != null) { for(int var17 = 0; var17 < 8; ++var17) { ItemStack var18 = this.func_76544_a(p_76484_2_); if(var18 != null) { var16.func_70299_a(p_76484_2_.nextInt(var16.func_70302_i_()), var18); } } } break label210; } } ++var11; continue; } } ++var10; break; } } p_76484_1_.func_72832_d(p_76484_3_, p_76484_4_, p_76484_5_, Block.field_72065_as.field_71990_ca, 0, 2); TileEntityMobSpawner var19 = (TileEntityMobSpawner)p_76484_1_.func_72796_p(p_76484_3_, p_76484_4_, p_76484_5_); if(var19 != null) { var19.func_98049_a().func_98272_a(this.func_76543_b(p_76484_2_)); } else { System.err.println("Failed to fetch mob spawner entity at (" + p_76484_3_ + ", " + p_76484_4_ + ", " + p_76484_5_ + ")"); } return true; } else { return false; } } private ItemStack func_76544_a(Random p_76544_1_) { int var2 = p_76544_1_.nextInt(12); return var2 == 0?new ItemStack(Item.field_77765_aA):(var2 == 1?new ItemStack(Item.field_77703_o, p_76544_1_.nextInt(4) + 1):(var2 == 2?new ItemStack(Item.field_77684_U):(var2 == 3?new ItemStack(Item.field_77685_T, p_76544_1_.nextInt(4) + 1):(var2 == 4?new ItemStack(Item.field_77677_M, p_76544_1_.nextInt(4) + 1):(var2 == 5?new ItemStack(Item.field_77683_K, p_76544_1_.nextInt(4) + 1):(var2 == 6?new ItemStack(Item.field_77788_aw):(var2 == 7 && p_76544_1_.nextInt(100) == 0?new ItemStack(Item.field_77778_at):(var2 == 8 && p_76544_1_.nextInt(2) == 0?new ItemStack(Item.field_77767_aC, p_76544_1_.nextInt(4) + 1):(var2 == 9 && p_76544_1_.nextInt(10) == 0?new ItemStack(Item.field_77698_e[Item.field_77819_bI.field_77779_bT + p_76544_1_.nextInt(2)]):(var2 == 10?new ItemStack(Item.field_77756_aW, 1, 3):(var2 == 11?Item.field_92105_bW.func_92109_a(p_76544_1_):null))))))))))); } private String func_76543_b(Random p_76543_1_) { int var2 = p_76543_1_.nextInt(4); return var2 == 0?"Skeleton":(var2 == 1?"Zombie":(var2 == 2?"Zombie":(var2 == 3?"Spider":""))); } }
401cb64eb1fb0534266f1788b0a09d89c6981862
ae0b55f2ec0f01d66f936e413e720d118c85962a
/src/main/java/br/com/docproc/processador/ProcessadorTIF.java
b15e5793cd71e9e8d63e0507ae2d767f3621920c
[]
no_license
felipe-sbatista/docProc
f10ec358400a02effbbe3aa9bb623c91627769dd
18a75b33df2728951defd5533e4c5b778e51f217
refs/heads/master
2020-04-02T08:10:55.324391
2018-10-28T20:18:49
2018-10-28T20:18:49
154,232,716
0
0
null
null
null
null
UTF-8
Java
false
false
390
java
package br.com.docproc.processador; import br.com.docproc.mock.MockImagem; import java.io.IOException; import java.util.List; import java.util.Map; public class ProcessadorTIF extends ProcessadorTexto { @Override public List<String> lerArquivo(byte[] conteudo) throws IOException { MockImagem mock = new MockImagem(); return mock.getPalavras(conteudo); } }
b8ecbdd953100a60ec47249690c8a578ace40f09
160e4db09f34a9ca5ed35b9105e8406bee376933
/Labs/AdvancedMazeLab/src/maze/RedMazeFactory.java
947e9fff2890418fe660547798f445c9f00b6048
[]
no_license
bbhandari822/Software-Design-ClassMaterials
8d04c6ddb06640090b17e2794610769ad3c2fb4c
9d31b04fce5f4f1444ef033e0b54666828802746
refs/heads/master
2021-09-01T21:05:43.903502
2017-12-28T15:57:23
2017-12-28T15:57:23
115,635,966
0
0
null
null
null
null
UTF-8
Java
false
false
423
java
package maze; /** * Created by Binod Bhandari on 10/24/17. */ public class RedMazeFactory extends MazeFactory{ public Wall MakeWall(){ return new RedWall(); } public Door MakeDoor(Room room1, Room room2){ return new BrownDoor(room1,room2); } public Room MakeRoom(int id){ return new RedRoom(id); } public Maze MakeMaze() { return new Maze(); } }
d28771f3fc463c5b93f15c804c1ce49ff8462e42
7d71d2fa9297778c3422f4a4a0958edc6f7e781a
/coshandler/src/main/java/com/csjbot/coshandler/core/Robot.java
609de6738c8c5751ef8396188e8967f7c7005a3a
[]
no_license
MiRobotic/csj-new-demo
094ccb7415eb6f92febee1903062df770a0dfe83
a022b29ddbf2240ad6cbe43738fe09b64e91e2c1
refs/heads/master
2020-08-08T17:42:55.450950
2019-10-09T09:46:33
2019-10-09T09:46:33
213,880,253
0
1
null
null
null
null
UTF-8
Java
false
false
37,694
java
package com.csjbot.coshandler.core; import android.content.Context; import android.graphics.Bitmap; import android.text.TextUtils; import com.csjbot.cosclient.CosClientAgent; import com.csjbot.cosclient.entity.CommonPacket; import com.csjbot.cosclient.entity.MessagePacket; import com.csjbot.cosclient.utils.CosLogger; import com.csjbot.coshandler.client_req.custom_service.ICustomServiceReq; import com.csjbot.coshandler.core.interfaces.IAction; import com.csjbot.coshandler.core.interfaces.IActionV2; import com.csjbot.coshandler.core.interfaces.IChassis; import com.csjbot.coshandler.core.interfaces.IExpression; import com.csjbot.coshandler.core.interfaces.IExtraFunction; import com.csjbot.coshandler.core.interfaces.IFace; import com.csjbot.coshandler.core.interfaces.ISpeech; import com.csjbot.coshandler.global.ConnectConstants; import com.csjbot.coshandler.global.REQConstants; import com.csjbot.coshandler.global.RobotContants; import com.csjbot.coshandler.listener.OnArmWaveListener; import com.csjbot.coshandler.listener.OnCameraListener; import com.csjbot.coshandler.listener.OnChargetStateListener; import com.csjbot.coshandler.listener.OnChassisListener; import com.csjbot.coshandler.listener.OnCustomServiceMsgListener; import com.csjbot.coshandler.listener.OnCustomerStateListener; import com.csjbot.coshandler.listener.OnDetectPersonListener; import com.csjbot.coshandler.listener.OnDeviceInfoListener; import com.csjbot.coshandler.listener.OnExpressionListener; import com.csjbot.coshandler.listener.OnFaceListener; import com.csjbot.coshandler.listener.OnFaceSaveListener; import com.csjbot.coshandler.listener.OnGetAllPointsListener; import com.csjbot.coshandler.listener.OnGetVersionListener; import com.csjbot.coshandler.listener.OnHeadTouchListener; import com.csjbot.coshandler.listener.OnHotWordsListener; import com.csjbot.coshandler.listener.OnInitListener; import com.csjbot.coshandler.listener.OnLinuxRobotTypeListener; import com.csjbot.coshandler.listener.OnMakeSessionIdListener; import com.csjbot.coshandler.listener.OnMapListener; import com.csjbot.coshandler.listener.OnMicroVolumeListener; import com.csjbot.coshandler.listener.OnNaviSearchListener; import com.csjbot.coshandler.listener.OnPositionListener; import com.csjbot.coshandler.listener.OnRobotStateListener; import com.csjbot.coshandler.listener.OnSNListener; import com.csjbot.coshandler.listener.OnSetSNListener; import com.csjbot.coshandler.listener.OnShutdownListener; import com.csjbot.coshandler.listener.OnSnapshotoListener; import com.csjbot.coshandler.listener.OnSpeakListener; import com.csjbot.coshandler.listener.OnSpeechErrorListener; import com.csjbot.coshandler.listener.OnSpeechGetResultListener; import com.csjbot.coshandler.listener.OnSpeechListener; import com.csjbot.coshandler.listener.OnSpeedSetListener; import com.csjbot.coshandler.listener.OnSyncFaceListener; import com.csjbot.coshandler.listener.OnUpgradeListener; import com.csjbot.coshandler.listener.OnWakeupListener; import com.csjbot.coshandler.listener.OnWakeupVersionListener; import com.csjbot.coshandler.listener.OnWarningCheckSelfListener; import com.csjbot.coshandler.log.CsjlogProxy; import com.csjbot.coshandler.log.Csjlogger; import com.csjbot.coshandler.tts.ISpeechSpeak; import com.csjbot.coshandler.tts.SpeechFactory; import com.csjbot.coshandler.util.ConfInfoUtil; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import java.util.Locale; import java.util.concurrent.CopyOnWriteArrayList; /** * 对外提供的机器人功能类 * Created by jingwc on 2017/9/5. */ public class Robot implements IFace, IAction, ISpeech, IExpression, IChassis, ICustomServiceReq, IActionV2, IExtraFunction { private volatile static Robot robot; /* 所以基础请求的代理类 */ public ClientReqProxy reqProxy; /* 语音合成类 */ private ISpeechSpeak speechSpeak; private OnSpeechListener speechListener; private CopyOnWriteArrayList<OnFaceListener> faceListeners = new CopyOnWriteArrayList<>(); private OnExpressionListener expressionListener; private OnInitListener initListener; private CopyOnWriteArrayList<OnCameraListener> cameraListeners = new CopyOnWriteArrayList<>(); private OnChassisListener chassisListener; private OnPositionListener positionListener; private CopyOnWriteArrayList<OnSNListener> snListeners = new CopyOnWriteArrayList<>(); private OnDeviceInfoListener deviceInfoListener; private OnRobotStateListener robotStateListener; private OnSnapshotoListener snapshotoListener; private OnFaceSaveListener faceSaveListener; private OnSetSNListener setSNListener; private OnSpeechErrorListener speechErrorListener; private OnMapListener mapListener; private OnGetVersionListener getVersionListener; private CopyOnWriteArrayList<OnWakeupListener> wakeupListeners = new CopyOnWriteArrayList<>(); private OnSpeedSetListener speedSetListener; private OnMicroVolumeListener microVolumeListener; private OnArmWaveListener armWaveListener; private CopyOnWriteArrayList<OnHeadTouchListener> headTouchListeners = new CopyOnWriteArrayList<>(); private OnNaviSearchListener onNaviSearchListener; private OnChargetStateListener onChargetStateListener; private OnDetectPersonListener detectPersonListener; private CopyOnWriteArrayList<OnDetectPersonListener> detectPersonListeners = new CopyOnWriteArrayList<>(); private OnUpgradeListener onUpgradeListener; private OnSpeechGetResultListener onSpeechGetResultListener; private OnCustomServiceMsgListener customServiceMsgListener; private OnWarningCheckSelfListener warningCheckSelfListener; private OnShutdownListener shutdownListener; private OnSyncFaceListener syncFaceListener; private OnMakeSessionIdListener makeSessionIdListener; private OnCustomerStateListener customerStateListener; private OnWakeupVersionListener wakeupVersionListener; /** * 热词监听 */ private OnHotWordsListener hotWordsListener; private OnLinuxRobotTypeListener linuxRobotTypeListener; private CopyOnWriteArrayList<OnPositionListener> positionListeners = new CopyOnWriteArrayList<>(); private CopyOnWriteArrayList<OnNaviSearchListener> naviSearchListeners = new CopyOnWriteArrayList<>(); private OnGetAllPointsListener getAllPointsListener; public static final int SPEECH_ASR_ONLY = 0; public static final int SPEECH_LAST_RESULT = 1; public static final int SPEECH_CUSTOMER_SERVICE = 2; public static String sessionId = "sessionId"; private int hardWareVersion = RobotContants.ROBOT_VERSION.ROBOT_VERSION_1_0; ////////////////////// SN (开始) public static String SN = ConfInfoUtil.getSN(); // public static String SN = "0D0019120001"; public static String NUACNE_DEBUG_SN = "888888888888"; public static void initSN() { CsjlogProxy.getInstance().info("SN: initSN"); getSN(); } public static void setSN(String sn) { CsjlogProxy.getInstance().info("SN: setSN " + sn); ConfInfoUtil.putSn(sn); SN = sn; } public static void getSN() { SN = ConfInfoUtil.getSN(); CsjlogProxy.getInstance().info("SN: getSN= " + SN); } ////////////////////// SN (结束) ////////////////////// 连接状态 (开始) public static boolean isLinuxConnect; public static boolean getConnectState() { return isLinuxConnect; } private void setConnectState(boolean isConnect) { isLinuxConnect = isConnect; } ////////////////////// 连接状态 (结束) public static Robot getInstance() { if (robot == null) { synchronized (Robot.class) { if (robot == null) { robot = new Robot(); } } } return robot; } private Robot() { reqProxy = new ClientReqProxy(); } /** * 初始化语音合成 * * @param context */ @Override public void initSpeak(Context context, int speechType) { speechSpeak = SpeechFactory.createSpeech(context, speechType); } public void setSpeechListener(OnSpeechListener listener) { speechListener = listener; } public void addFaceListener(OnFaceListener listener) { if (listener != null && !faceListeners.contains(listener)) { faceListeners.add(listener); } } public void removeFaceListener(OnFaceListener listener) { if (listener != null && faceListeners.contains(listener)) { faceListeners.remove(listener); } } public void clearFaceListener() { faceListeners.clear(); } public void setExpressionListener(OnExpressionListener listener) { expressionListener = listener; } public void setInitListener(OnInitListener listener) { initListener = listener; } public void addCameraListener(OnCameraListener listener) { if (listener != null && !cameraListeners.contains(listener)) { cameraListeners.add(listener); } } public void removeCameraListener(OnCameraListener listener) { if (listener != null && cameraListeners.contains(listener)) { cameraListeners.remove(listener); } } public void setChassisListener(OnChassisListener listener) { chassisListener = listener; } public void setPositionListener(OnPositionListener listener) { positionListener = listener; } public synchronized void registerPositionListener(OnPositionListener positionListener) { if (positionListener != null && !positionListeners.contains(positionListener)) { positionListeners.add(positionListener); } } public synchronized void unregisterPositionListener(OnPositionListener listener) { if (listener != null && positionListeners.contains(listener)) { positionListeners.remove(listener); } } public void addSnListener(OnSNListener listener) { if (listener != null && !snListeners.contains(listener)) { snListeners.add(listener); } } public void removeSnListener(OnSNListener listener) { if (listener != null && snListeners.contains(listener)) { snListeners.remove(listener); } } public void setDeviceInfoListener(OnDeviceInfoListener listener) { deviceInfoListener = listener; } public void setRobotStateListener(OnRobotStateListener listener) { robotStateListener = listener; } public void setSnapshotoListener(OnSnapshotoListener listener) { snapshotoListener = listener; } public void setFaceSaveListener(OnFaceSaveListener listener) { faceSaveListener = listener; } public void setSpeechErrorListener(OnSpeechErrorListener listener) { speechErrorListener = listener; } public void setMapListener(OnMapListener listener) { mapListener = listener; } public void setGetVersionListener(OnGetVersionListener listener) { getVersionListener = listener; } public void addWakeupListener(OnWakeupListener listener) { if (listener != null && !wakeupListeners.contains(listener)) { wakeupListeners.add(listener); } } public void removeWakeupListener(OnWakeupListener listener) { if (listener != null && wakeupListeners.contains(listener)) { wakeupListeners.remove(listener); } } public void clearWakeupListener() { wakeupListeners.clear(); } public void setSpeedSetListener(OnSpeedSetListener speedSetListener) { this.speedSetListener = speedSetListener; } public void setMicroVolumeListener(OnMicroVolumeListener listener) { this.microVolumeListener = listener; } public void addHeadTouchListener(OnHeadTouchListener listener) { if (listener != null && !headTouchListeners.contains(listener)) { headTouchListeners.add(listener); } } public void removeHeadTouchListener(OnHeadTouchListener listener) { if (listener != null && headTouchListeners.contains(listener)) { headTouchListeners.remove(listener); } } public void setOnNaviSearchListener(OnNaviSearchListener onNaviSearchListener) { this.onNaviSearchListener = onNaviSearchListener; } public void setWarningCheckSelfListener(OnWarningCheckSelfListener listener) { this.warningCheckSelfListener = listener; } public void registerNaviSearchListener(OnNaviSearchListener onNaviSearchListener) { naviSearchListeners.add(onNaviSearchListener); } public void unregisterNaviSearchListener(OnNaviSearchListener onNaviSearchListener) { naviSearchListeners.remove(onNaviSearchListener); } public void setOnChargetStateListener(OnChargetStateListener onChargetStateListener) { this.onChargetStateListener = onChargetStateListener; } public void setDetectPersonListener(OnDetectPersonListener detectPersonListener) { this.detectPersonListener = detectPersonListener; } public void addDetectPersonListener(OnDetectPersonListener detectPersonListener) { if (detectPersonListener != null && !detectPersonListeners.contains(detectPersonListener)) { detectPersonListeners.add(detectPersonListener); } } public void removeDetectPersonListener(OnDetectPersonListener detectPersonListener) { if (detectPersonListener != null && detectPersonListeners.contains(detectPersonListener)) { detectPersonListeners.remove(detectPersonListener); } } public void setOnUpgradeListener(OnUpgradeListener onUpgradeListener) { this.onUpgradeListener = onUpgradeListener; } public void setOnSpeechGetResultListener(OnSpeechGetResultListener onSpeechGetResultListener) { this.onSpeechGetResultListener = onSpeechGetResultListener; } public void setHotWordsListener(OnHotWordsListener listener) { hotWordsListener = listener; } public void setLinuxRobotTypeListener(OnLinuxRobotTypeListener listener) { linuxRobotTypeListener = listener; } public void setShutdownListener(OnShutdownListener listener) { shutdownListener = listener; } public void setSyncFaceListener(OnSyncFaceListener listener) { syncFaceListener = listener; } public void pushSyncFaceResponse(int errorCode) { if (syncFaceListener != null) { syncFaceListener.response(errorCode); } } public void pushSyncFaceCompelte(int errorCode) { if (syncFaceListener != null) { syncFaceListener.complete(errorCode); } } public void pushShutdown() { if (shutdownListener != null) { shutdownListener.response(); } } public void pushCheckSelf(String json) { if (warningCheckSelfListener != null) { warningCheckSelfListener.response(json); } } public void pushSpeechGetResult(String json) { if (onSpeechGetResultListener != null) { onSpeechGetResultListener.response(json); } } public void pushUpgradeCheck(int errorCode) { if (onUpgradeListener != null) { onUpgradeListener.checkRsp(errorCode); } } public void pushUpgrade(int errorCode) { if (onUpgradeListener != null) { onUpgradeListener.upgradeRsp(errorCode); } } public void pushUpgradeProgress(int progress) { if (onUpgradeListener != null) { onUpgradeListener.upgradeProgress(progress); } } public void pushDetectPerson(int state) { if (!detectPersonListeners.isEmpty()) { for (OnDetectPersonListener detectPersonListener : detectPersonListeners) { detectPersonListener.response(state); } } if (detectPersonListener != null) { detectPersonListener.response(state); } } public void pushChargeState(int state) { if (onChargetStateListener != null) { onChargetStateListener.response(state); } } public void pushHeadTouch() { for (OnHeadTouchListener headTouchListener : headTouchListeners) { headTouchListener.response(); } } public void pushMicrolVolume(int volume) { if (microVolumeListener != null) { microVolumeListener.response(volume); } } public void setArmWaveListener(OnArmWaveListener armWaveListener) { this.armWaveListener = armWaveListener; } public void setCustomServiceMsgListener(OnCustomServiceMsgListener listener) { this.customServiceMsgListener = listener; } public void setMakeSessionIdListener(OnMakeSessionIdListener listener) { this.makeSessionIdListener = listener; } public void pushMakeSessionId(String sessionId) { if (getVersionListener != null) { getVersionListener.response(sessionId); } } public void pushWakeup(int angle) { for (OnWakeupListener listener : wakeupListeners) { if (listener != null) { listener.response(angle); } } } public void pushVersion(String version) { if (getVersionListener != null) { getVersionListener.response(version); } } public void pushLoadMap(boolean state) { if (mapListener != null) { mapListener.loadMap(state); } } public void pushSaveMap(boolean state) { if (mapListener != null) { mapListener.saveMap(state); } } public void pushSetSpeed(String json) { try { JSONObject jo = new JSONObject(json); int error_code = jo.optInt("error_code"); if (error_code == 0 && speedSetListener != null) { speedSetListener.setSpeedResult(true); } else if (error_code != 0 && speedSetListener != null) { speedSetListener.setSpeedResult(false); } } catch (JSONException e) { e.printStackTrace(); } } public void pushNaviSearchResult(String json) { if (onNaviSearchListener != null) { onNaviSearchListener.searchResult(json); for (OnNaviSearchListener listener : naviSearchListeners) { listener.searchResult(json); } } } public void pushSpeechError() { if (speechErrorListener != null) { speechErrorListener.response(); } } public void pushFaceSave(String json) { if (faceSaveListener != null) { faceSaveListener.response(json); } } public void pushSnapshoto(String json) { if (snapshotoListener != null) { snapshotoListener.response(json); } } public void setSnListener(OnSetSNListener listener) { if (setSNListener != null) { setSNListener = listener; } } public void pushArmWaveResult(String json) { if (armWaveListener != null) { armWaveListener.start(json); } } public void pushArmStopResult(String json) { if (armWaveListener != null) { armWaveListener.stop(json); } } public void pushCustomServiceMsg(String json) { if (customServiceMsgListener != null) { customServiceMsgListener.onMsg(json); } } /** * 热词 * * @param hotwords */ public void pushHotWords(List<String> hotwords) { if (hotWordsListener != null) { hotWordsListener.hotWords(hotwords); } } /** * linux 机器人类型 * * @param type */ public void pushLinuxRobotType(String type) { if (linuxRobotTypeListener != null) { linuxRobotTypeListener.linuxRobotType(type); } } // public void pushArmStartWaveResult /** * 推送发送 * * @param json */ public void pushMoveToResult(String json) { if (positionListener != null) { positionListener.moveToResult(json); } for (OnPositionListener listener : positionListeners) { listener.moveToResult(json); } } public void pushPosition(String json) { if (positionListener != null) { positionListener.positionInfo(json); } for (OnPositionListener listener : positionListeners) { listener.positionInfo(json); } } public void pushMoveResult(String json) { if (positionListener != null) { positionListener.moveResult(json); } for (OnPositionListener listener : positionListeners) { listener.moveResult(json); } } public void pushCancelTask(String json) { if (positionListener != null) { positionListener.cancelResult(json); } else { Csjlogger.debug("positionListener为空"); } for (OnPositionListener listener : positionListeners) { listener.cancelResult(json); } } /** * 向上推送语音识别结果 * * @param json */ public void pushSpeech(String json, int type) { if (speechListener != null) { speechListener.speechInfo(json, type); } } /** * 向上推送人脸识别信息 * * @param json */ public void pushFace(String json) { for (OnFaceListener listener : faceListeners) { if (listener != null) { listener.personInfo(json); } } } /** * 向上推送人脸检测靠近信息 * * @param person */ public void pushFace(boolean person) { for (OnFaceListener listener : faceListeners) { if (listener != null) { listener.personNear(person); } } } /** * 向上推送人脸数据库信息 * * @param json */ public void pushFaceList(String json) { for (OnFaceListener listener : faceListeners) { if (listener != null) { listener.personList(json); } } } /** * 向上推送当前表情 * * @param expression */ public void pushExpression(int expression) { if (expressionListener != null) { expressionListener.response(expression); } } /** * 向上推送视频流 * * @param bitmap */ public void pushCamera(Bitmap bitmap) { for (OnCameraListener listener : cameraListeners) { listener.response(bitmap); } } /** * 向上推送init状态信息 * * @param type */ public void pushInit(int type) { if (initListener != null) { switch (type) { case ConnectConstants.ConnectStatus.SUCCESS: setConnectState(true); initListener.success(); break; case ConnectConstants.ConnectStatus.FAILD: setConnectState(false); initListener.faild(); break; case ConnectConstants.ConnectStatus.TIMEOUT: setConnectState(false); initListener.timeout(); break; case ConnectConstants.ConnectStatus.DISCONNECT: setConnectState(false); initListener.disconnect(); break; default: break; } } } /** * 向上推送 sn 信息 * * @param sn 机器人 SN */ public void pushSN(String sn) { for (OnSNListener snListener : snListeners) { snListener.response(sn); } } /** * 向上推送机器人上身板等设备信息 * * @param info 设备信息 */ public void pushDeviceInfo(String info) { if (deviceInfoListener != null) { deviceInfoListener.response(info); } } /** * 向上推送设置 SN 信息 */ public void pushSetSnResp(String info) { if (setSNListener != null) { setSNListener.response(info); } } /** * 向上推送机器人电量信息 * * @param battery */ public void pushRobotState(int battery) { if (robotStateListener != null) { robotStateListener.getBattery(battery); } } public void setGetAllPointsListener(OnGetAllPointsListener listener) { getAllPointsListener = listener; } public void pushGetAllPoints() { if (getAllPointsListener != null) { getAllPointsListener.getAllPoints(); } } public void setOnCustomerStateListener(OnCustomerStateListener listener) { customerStateListener = listener; } public void setOnWakeupVersionListener(OnWakeupVersionListener listener) { wakeupVersionListener = listener; } public void pushWakeupVersionListener(String version1, String version2) { if (wakeupVersionListener != null) { wakeupVersionListener.getVersion(version1, version2); } } public void putCustomerState(int type, int state) { if (customerStateListener != null) { customerStateListener.response(type, state); } } @Override public void leftLargeArmUp() { reqProxy.action(REQConstants.BodyPart.LEFT_ARM, REQConstants.BodyAction.LEFT_UP); } @Override public void leftLargeArmDown() { reqProxy.action(REQConstants.BodyPart.LEFT_ARM, REQConstants.BodyAction.RIGHT_DOWN); } @Override public void leftSmallArmUp() { reqProxy.action(REQConstants.BodyPart.LEFT_FOREARM, REQConstants.BodyAction.LEFT_UP); } @Override public void leftSmallArmDown() { reqProxy.action(REQConstants.BodyPart.LEFT_FOREARM, REQConstants.BodyAction.RIGHT_DOWN); } @Override public void righLargeArmUp() { reqProxy.action(REQConstants.BodyPart.RIGHT_ARM, REQConstants.BodyAction.LEFT_UP); } @Override public void rightLargeArmDown() { reqProxy.action(REQConstants.BodyPart.RIGHT_ARM, REQConstants.BodyAction.RIGHT_DOWN); } @Override public void rightSmallArmUp() { reqProxy.action(REQConstants.BodyPart.RIGHT_FOREARM, REQConstants.BodyAction.LEFT_UP); } @Override public void rightSmallArmDown() { reqProxy.action(REQConstants.BodyPart.RIGHT_FOREARM, REQConstants.BodyAction.RIGHT_DOWN); } @Override public void doubleLargeArmUp() { reqProxy.action(REQConstants.BodyPart.DOUBLE_ARM, REQConstants.BodyAction.LEFT_UP); } @Override public void doubleLargeArmDown() { reqProxy.action(REQConstants.BodyPart.DOUBLE_ARM, REQConstants.BodyAction.RIGHT_DOWN); } @Override public void doubleSmallArmUp() { reqProxy.action(REQConstants.BodyPart.DOUBLE_FOREARM, REQConstants.BodyAction.LEFT_UP); } @Override public void doubleSmallArmDown() { reqProxy.action(REQConstants.BodyPart.DOUBLE_FOREARM, REQConstants.BodyAction.RIGHT_DOWN); } @Override public void startWave(int intervalTime) { reqProxy.startWaveHands(intervalTime); } @Override public void stopWave() { reqProxy.stopWaveHands(); } @Override public void snowRightArm() { reqProxy.action(1, 1); } @Override public void snowLeftArm() { reqProxy.action(2, 1); } @Override public void snowDoubleArm() { reqProxy.action(3, 1); } /** * 摇头动作 */ @Override public void denyAction() { reqProxy.action(REQConstants.BodyPart.HEAD, REQConstants.BodyAction.LEFT_THEN_RIGHT); } /** * 点头动作 */ @Override public void nodAction() { new Thread(new Runnable() { @Override public void run() { reqProxy.action(REQConstants.BodyPart.HEAD, REQConstants.BodyAction.DOWN); try { Thread.sleep(1500); } catch (InterruptedException e) { e.printStackTrace(); } reqProxy.action(REQConstants.BodyPart.HEAD, REQConstants.BodyAction.UP); } }).start(); } /** * 重置动作 */ @Override public void resetAction() { reqProxy.action(REQConstants.BodyPart.RESET, REQConstants.BodyAction.NONE); } public void expression(int expression) { reqProxy.setExpression(expression , REQConstants.Expression.NO , REQConstants.Expression.NO); } public void expression(int expression, int once, int time) { reqProxy.setExpression(expression, once, time); } /** * 开心表情 */ @Override public void happy() { expression(REQConstants.Expression.HAPPY); } /** * 悲伤表情 */ @Override public void sadness() { expression(REQConstants.Expression.SADNESS); } /** * 惊讶表情 */ @Override public void surprised() { expression(REQConstants.Expression.SURPRISED); } /** * 微笑表情 */ @Override public void smile() { expression(REQConstants.Expression.SMILE); } /** * 普通表情 */ @Override public void normal() { expression(REQConstants.Expression.NORMAL); } /** * 生气表情 */ @Override public void angry() { expression(REQConstants.Expression.ANGRY); } @Override public void lightning() { expression(REQConstants.Expression.LIGHTNING); } @Override public void sleepiness() { expression(REQConstants.Expression.SLEEPINESS); } //************************************** TTS **************************************/ //************************************** TTS **************************************/ //************************************** TTS **************************************/ /** * 返回tts的发声人列表 * * @param language 语言 * @param country 国家或者地区 * @return tts的发声人列表,只会返回空,永不为null */ public ArrayList<String> getSpeakerNames(String language, String country) { ArrayList<String> list = speechSpeak.getSpeakerNames(language, country); return list == null ? new ArrayList<String>() : list; } @Override public void setVolume(float volume) { speechSpeak.setVolume(volume); } /** * 开始说话 * * @param text * @param listener */ @Override public void startSpeaking(String text, OnSpeakListener listener) { if (speechSpeak != null) { speechSpeak.startSpeaking(text, listener); } } @Override public boolean setSpeakerName(String name) { if (speechSpeak != null) { speechSpeak.setSpeakerName(name); } return false; } @Override public boolean setLanguage(Locale language) { return speechSpeak.setLanguage(language); } /** * 停止说话 */ @Override public void stopSpeaking() { if (speechSpeak != null) { speechSpeak.stopSpeaking(); } } /** * 暂停说话 */ @Override public void pauseSpeaking() { if (speechSpeak != null) { speechSpeak.pauseSpeaking(); } } /** * 重新说话 */ @Override public void resumeSpeaking() { if (speechSpeak != null) { speechSpeak.resumeSpeaking(); } } /************************************** TTS END **************************************/ @Override public boolean isSpeaking() { return speechSpeak != null && speechSpeak.isSpeaking(); } //************************************* TTS END **************************************/ //************************************* TTS END **************************************/ @Override public void turnLeft() { reqProxy.moveAngle(90); } @Override public void turnRight() { reqProxy.moveAngle(-90); } @Override public void moveLeft() { reqProxy.move(REQConstants.MoveDirection.LEFT); } @Override public void moveRight() { reqProxy.move(REQConstants.MoveDirection.RIGHT); } @Override public void moveForward() { reqProxy.move(REQConstants.MoveDirection.FORWARD); } @Override public void moveBack() { reqProxy.move(REQConstants.MoveDirection.BACK); } /** * 透传方法 * * @param json */ public void transparentTransmission(String json) { if (TextUtils.isEmpty(json)) return; CsjlogProxy.getInstance().info(json); try { MessagePacket packet = new CommonPacket(json.getBytes()); CosClientAgent.getRosClientAgent().sendMessage(packet); } catch (Exception e) { CosLogger.error("BaseClientReq:sendReq:e:" + e.toString()); } } /** * 呼叫人工客服 */ @Override public void callHumanService(String sn) { reqProxy.callHumanService(sn); } @Override public void hangUpHumanService(String sn) { reqProxy.hangUpHumanService(sn); } @Override public void sendHumanServiceHeartBeat(String sn) { reqProxy.sendHumanServiceHeartBeat(sn); } /** * 爱丽丝头向上运动 */ @Override public void AliceHeadUp() { reqProxy.action(REQConstants.BodyPartV2.HEAD1, REQConstants.BodyActionV2.HEAD_UP); } /** * 爱丽丝头向下运动 */ @Override public void AliceHeadDown() { reqProxy.action(REQConstants.BodyPartV2.HEAD1, REQConstants.BodyActionV2.HEAD_DOWN); } /** * 爱丽丝头向左运动 */ @Override public void AliceHeadLeft() { reqProxy.action(REQConstants.BodyPartV2.HEAD2, REQConstants.BodyActionV2.HEAD_LEFT); } /** * 爱丽丝头向右运动 */ @Override public void AliceHeadRight() { reqProxy.action(REQConstants.BodyPartV2.HEAD2, REQConstants.BodyActionV2.HEAD_RIGHT); } /** * 爱丽丝头水平重置 */ @Override public void AliceHeadHReset() { reqProxy.action(REQConstants.BodyPartV2.HEAD2, REQConstants.BodyActionV2.HORIZONTAL_RESET); } /** * 爱丽丝左臂抬起 */ @Override public void AliceLeftArmUp() { reqProxy.action(REQConstants.BodyPartV2.LEFT_ARM, REQConstants.BodyActionV2.ARM_UP); } /** * 爱丽丝左臂放下 */ @Override public void AliceLeftArmDown() { reqProxy.action(REQConstants.BodyPartV2.LEFT_ARM, REQConstants.BodyActionV2.ARM_DOWN); } /** * 爱丽丝右臂抬起 */ @Override public void AliceRightArmUp() { reqProxy.action(REQConstants.BodyPartV2.RIGHT_ARM, REQConstants.BodyActionV2.ARM_UP); } /** * 爱丽丝右臂放下 */ @Override public void AliceRightArmDown() { reqProxy.action(REQConstants.BodyPartV2.RIGHT_ARM, REQConstants.BodyActionV2.ARM_DOWN); } /** * 小雪左臂挥动 * * @param count 次数 */ @Override public void SnowLeftArmSwing(int count) { reqProxy.action(REQConstants.SnowBodyActionV2.SNOW_LEFT_ARM_SWING, count); } /** * 小雪右臂挥动 * * @param count 次数 */ @Override public void SnowRightArmSwing(int count) { reqProxy.action(REQConstants.SnowBodyActionV2.SNOW_RIGHT_ARM_SWING, count); } /** * 小雪双臂挥动 * * @param count 次数 */ @Override public void SnowDoubleArmSwing(int count) { reqProxy.action(REQConstants.SnowBodyActionV2.SNOW_DOUBLE_ARM_SWING, count); } public int getHardWareVersion() { return hardWareVersion; } public void setHardWareVersion(String hw) { if (hw.contains("V1")) { hardWareVersion = RobotContants.ROBOT_VERSION.ROBOT_VERSION_1_0; } else { hardWareVersion = RobotContants.ROBOT_VERSION.ROBOT_VERSION_2_0; } } public void setHardWareVersion(int hardWareVersion) { this.hardWareVersion = hardWareVersion; } @Override public void getHotWords() { reqProxy.getHotWords(); } @Override public void setHotWords(List<String> hotwords) { reqProxy.setHotWords(hotwords); } /** * 开始人脸跟随 */ @Override public void startFaceFollow() { reqProxy.startFaceFollow(); } /** * 关闭人脸跟随 */ @Override public void stopFaceFollow() { reqProxy.stopFaceFollow(); } @Override public void sendMessageToLinux(String message, String language) { } }
1895c48dbe86766347e9320b53d4205701d64cbe
d4eff92f94f7481193a7872cd7a7b0fffe6f534c
/src/com/lemu/gui/Dim.java
501f48b263bcb2e18f28b3447961361a9850a006
[]
no_license
renewooller/Leco
d6284d63cc2e7bcca6836c0be696046b0114c645
ac8b886053f641c739a0396a9742137167271fb4
refs/heads/master
2020-03-11T03:01:42.762525
2018-04-16T11:52:51
2018-04-16T11:52:51
129,734,807
0
0
null
null
null
null
UTF-8
Java
false
false
466
java
/* * Created on 2/12/2004 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package com.lemu.gui; import java.awt.Dimension; /** * @author wooller * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class Dim { public static Dimension sqr = new Dimension(40, 40); }
[ "rene" ]
rene
102c62db166737829de9fe69b78f7dcbe2677522
356a626b3b7895f73a61e1203dd26f0ceb519d7d
/src/DemoPack/Lesson12/Abstract/Car.java
552344a71a9e37638ff1b984297760da9f677a55
[]
no_license
alenka134/shecodes_1
51027785a7ceca5f507faa87e1f0441a30dbe225
5404067701761941d5cbd8dda0f81e667ac0f9de
refs/heads/master
2020-04-04T20:50:17.555549
2019-03-18T20:49:31
2019-03-18T20:49:31
156,262,878
0
0
null
null
null
null
UTF-8
Java
false
false
397
java
package DemoPack.Lesson12.Abstract; public class Car extends Machine { @Override public void start() { System.out.println("Starting ignition..."); } @Override public void doStaff() { System.out.println("Do stuff in car. Driving..."); } @Override public void shutdown() { System.out.println("Shutdown car. Switch off ignition."); } }
32b8cefdb2c4aa47baf2550b17c365435cbab1a5
c147e355e360687755926a7833aca24cf4059bef
/src/TestForSet.java
1516cf2f996e151eee1450cb28586a00b6fb8e1c
[ "Apache-2.0" ]
permissive
ferrycore/Thinking_In_Java_code
d2b8dd5d3b836a3531fb133a08c92dd90eae5f38
df7a3ebc065dd142220d520f78b66d5dacd6e6b5
refs/heads/master
2021-07-17T04:22:48.504107
2017-10-05T04:13:00
2017-10-05T04:13:00
104,006,428
0
0
null
null
null
null
UTF-8
Java
false
false
539
java
import java.util.*; public class TestForSet { public static void main(String []args) { Random random =new Random(47); Set<String>set1 =new TreeSet<String>(); Set<String>set2 =new TreeSet<String>(); Collections.addAll(set1, "a b c e f".split(" ")); Collections.addAll(set2, "a b g h j".split(" ")); boolean iscontain =set1.containsAll(set2); if(iscontain) { System.out.println("isok"); } set1.removeAll(set2); System.out.println(set1); //如果想对结果排序,可以使用TreeSet } }
372891c995a34a6590c2770ae3b7a36c1fa21ce8
7fe7e9cc502e2aa0b4bd1b4c612657ed8e4c6c7f
/spring-03-ioc/src/test/java/MyTest.java
f125ca553f177892ccc5bf7c960cfa1c5c63c198
[]
no_license
GiKyouGetsu/spring-study
7cb97d6703395ad2a1e1dcd73e8dc043d424537a
5f55e2af5f77308bc84dfbe588ef62a395854e65
refs/heads/master
2023-03-09T03:43:49.814188
2021-02-20T09:50:23
2021-02-20T09:50:23
340,616,434
0
0
null
null
null
null
UTF-8
Java
false
false
447
java
import com.wei.pojo.UserT; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class MyTest { public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); UserT userT = (UserT) context.getBean("u1"); System.out.println("User is: " + userT.getName()); } }
3e6c5176e716a19da6076f494482a933c7d420f7
f354a979863c54044dac0c5a812ffade6706cdcb
/kodilla-exception/src/main/java/com/kodilla/exception/test/FlightSearcher.java
d26d2f84f2cc9f2afc6bcb6072f86319b7589bce
[]
no_license
Anganor/testing_new_feature
323ce4da3f1f2b9f946d4f70298317f6cea6e379
e29896be179a6499bc64fe6e6d62008ac31c13c0
refs/heads/master
2020-06-28T11:26:48.624197
2020-03-06T17:38:03
2020-03-06T17:38:03
200,221,637
0
0
null
null
null
null
UTF-8
Java
false
false
1,830
java
package com.kodilla.exception.test; import java.util.Collection; import java.util.HashMap; import java.util.Map; public class FlightSearcher { public void findFlight(Flight flight) throws RouteNotFoundException { Map<String, Boolean> availableAirports = new HashMap<>(); availableAirports.put("Poznań", true); availableAirports.put("Kraków", true); availableAirports.put("Warszawa", false); availableAirports.put("Wrocław", false); availableAirports.put("Katowice", true); availableAirports.put("Gdańsk", true); availableAirports.put("Gdynia", true); if (availableAirports.containsKey(flight.arrivalAirport) && availableAirports.containsKey(flight.departureAirport)) { if (!availableAirports.get(flight.arrivalAirport)) { System.out.println("Chosen airport: " + flight.arrivalAirport + ", is currently under maintenance."); } else if (!availableAirports.get(flight.departureAirport)) { System.out.println("Chosen airport: " + flight.departureAirport + ", is currently under maintenance."); } } if (!availableAirports.containsKey(flight.getDepartureAirport()) && !availableAirports.containsKey(flight.getArrivalAirport())) { throw new RouteNotFoundException("Both chosen airports are not on our map."); } if (!availableAirports.containsKey(flight.getArrivalAirport())) { throw new RouteNotFoundException("Your destination airport: " + flight.getArrivalAirport() + ", is not on our map."); } if (!availableAirports.containsKey(flight.getDepartureAirport())) { throw new RouteNotFoundException("Your starting airport: " + flight.getDepartureAirport() + ", is not on our map."); } } }
055edb0bf59fc2b2e5bd3818914bf23bf81c5dca
08859a2cc09c970bb828a90e0b01d37a532def19
/hostsoftware/libjhexabus/src/de/fraunhofer/itwm/hexabus/HexabusEndpoint.java
b937e09178abde8f825de4c162ec3e706c446033
[]
no_license
mysmartgrid/hexabus
c470739cc71a7167f7b8fbb7fcfc6aa0a8202b79
fa61107cefae611b0092229a6b1c2460b4353c51
refs/heads/master
2021-08-22T13:02:19.004285
2015-04-16T12:59:42
2015-04-16T13:00:57
1,978,237
27
9
null
2021-01-20T22:39:51
2011-06-30T14:04:39
C++
UTF-8
Java
false
false
8,142
java
package de.fraunhofer.itwm.hexabus; import java.io.IOException; import java.sql.Timestamp; import java.util.Calendar; public class HexabusEndpoint { private HexabusDevice device; private int eid; private Hexabus.DataType dataType; private String description; public HexabusEndpoint(HexabusDevice device, int eid, Hexabus.DataType dataType, String description) { this.device = device; this.eid = eid; this.dataType = dataType; this.description = description; } public HexabusEndpoint(HexabusDevice device, int eid, Hexabus.DataType dataType) { this.device = device; this.eid = eid; this.dataType = dataType; this.description = ""; } public int getEid() { return eid; } public String getDescription() { return description; } public Hexabus.DataType getDataType() { return dataType; } public String toString() { return eid+" "+description+" "+dataType; } public void writeEndpoint(boolean value) throws Hexabus.HexabusException, IOException { if(dataType != Hexabus.DataType.BOOL) { throw new Hexabus.HexabusException("Wrong data type. "+dataType+" expected."); } HexabusPacket packet = new HexabusWritePacket(eid, value); packet.sendPacket(device.getInetAddress()); } public void writeEndpoint(String value) throws Hexabus.HexabusException, IOException { if(dataType != Hexabus.DataType.STRING) { throw new Hexabus.HexabusException("Wrong data type. "+dataType+" expected"); } HexabusPacket packet = new HexabusWritePacket(eid, value); packet.sendPacket(device.getInetAddress()); } public void writeEndpoint(short value) throws Hexabus.HexabusException, IOException { if(dataType != Hexabus.DataType.UINT8) { throw new Hexabus.HexabusException("Wrong data type. "+dataType+" expected"); } HexabusPacket packet = new HexabusWritePacket(eid, value); packet.sendPacket(device.getInetAddress()); } public void writeEndpoint(float value) throws Hexabus.HexabusException, IOException { if(dataType != Hexabus.DataType.FLOAT) { throw new Hexabus.HexabusException("Wrong data type. "+dataType+" expected"); } HexabusPacket packet = new HexabusWritePacket(eid, value); packet.sendPacket(device.getInetAddress()); } public void writeEndpoint(long value) throws Hexabus.HexabusException, IOException { if(dataType != Hexabus.DataType.UINT32) { throw new Hexabus.HexabusException("Wrong data type. "+dataType+" expected"); } HexabusPacket packet = new HexabusWritePacket(eid, value); packet.sendPacket(device.getInetAddress()); } public void writeEndpoint(Timestamp value) throws Hexabus.HexabusException, IOException { if(dataType != Hexabus.DataType.TIMESTAMP) { throw new Hexabus.HexabusException("Wrong data type. "+dataType+" expected"); } HexabusPacket packet = new HexabusWritePacket(eid, value); packet.sendPacket(device.getInetAddress()); } public void writeEndpoint(Calendar value) throws Hexabus.HexabusException, IOException { if(dataType != Hexabus.DataType.DATETIME) { throw new Hexabus.HexabusException("Wrong data type. "+dataType+" expected"); } HexabusPacket packet = new HexabusWritePacket(eid, value); packet.sendPacket(device.getInetAddress()); } // TODO use setSoTimeout public boolean queryBoolEndpoint() throws Hexabus.HexabusException, IOException { if(dataType != Hexabus.DataType.BOOL) { throw new Hexabus.HexabusException("Wrong data type. "+dataType+" expected."); } HexabusPacket packet = new HexabusQueryPacket(eid); int port = packet.sendPacket(device.getInetAddress()); // Receive reply packet = Hexabus.receivePacket(port); switch(packet.getPacketType()) { case ERROR: throw new Hexabus.HexabusException("Error packet received: "+((HexabusErrorPacket) packet).getErrorCode()); case INFO: return ((HexabusInfoPacket) packet).getBool(); default: throw new Hexabus.HexabusException("Unexpected reply received"); } } public String queryStringEndpoint() throws Hexabus.HexabusException, IOException { if(dataType != Hexabus.DataType.STRING) { throw new Hexabus.HexabusException("Wrong data type. "+dataType+" expected"); } HexabusPacket packet = new HexabusQueryPacket(eid); int port = packet.sendPacket(device.getInetAddress()); // Receive reply packet = Hexabus.receivePacket(port); switch(packet.getPacketType()) { case ERROR: throw new Hexabus.HexabusException("Error packet received: "+((HexabusErrorPacket) packet).getErrorCode()); case INFO: return ((HexabusInfoPacket) packet).getString(); default: throw new Hexabus.HexabusException("Unexpected reply received"); } } public short queryUint8Endpoint() throws Hexabus.HexabusException, IOException { if(dataType != Hexabus.DataType.UINT8) { throw new Hexabus.HexabusException("Wrong data type. "+dataType+" expected"); } HexabusPacket packet = new HexabusQueryPacket(eid); int port = packet.sendPacket(device.getInetAddress()); // Receive reply packet = Hexabus.receivePacket(port); switch(packet.getPacketType()) { case ERROR: throw new Hexabus.HexabusException("Error packet received: "+((HexabusErrorPacket) packet).getErrorCode()); case INFO: return ((HexabusInfoPacket) packet).getUint8(); default: throw new Hexabus.HexabusException("Unexpected reply received"); } } public float queryFloatEndpoint() throws Hexabus.HexabusException, IOException { if(dataType != Hexabus.DataType.FLOAT) { throw new Hexabus.HexabusException("Wrong data type. "+dataType+" expected"); } HexabusPacket packet = new HexabusQueryPacket(eid); int port = packet.sendPacket(device.getInetAddress()); // Receive reply packet = Hexabus.receivePacket(port); switch(packet.getPacketType()) { case ERROR: throw new Hexabus.HexabusException("Error packet received: "+((HexabusErrorPacket) packet).getErrorCode()); case INFO: return ((HexabusInfoPacket) packet).getFloat(); default: throw new Hexabus.HexabusException("Unexpected reply received"); } } public long queryUint32Endpoint() throws Hexabus.HexabusException, IOException { if(dataType != Hexabus.DataType.UINT32) { throw new Hexabus.HexabusException("Wrong data type. "+dataType+" expected"); } HexabusPacket packet = new HexabusQueryPacket(eid); int port = packet.sendPacket(device.getInetAddress()); // Receive reply packet = Hexabus.receivePacket(port); switch(packet.getPacketType()) { case ERROR: throw new Hexabus.HexabusException("Error packet received: "+((HexabusErrorPacket) packet).getErrorCode()); case INFO: return ((HexabusInfoPacket) packet).getUint32(); default: throw new Hexabus.HexabusException("Unexpected reply received"); } } public Timestamp queryTimestampEndpoint() throws Hexabus.HexabusException, IOException { if(dataType != Hexabus.DataType.TIMESTAMP) { throw new Hexabus.HexabusException("Wrong data type. "+dataType+" expected"); } HexabusPacket packet = new HexabusQueryPacket(eid); int port = packet.sendPacket(device.getInetAddress()); // Receive reply packet = Hexabus.receivePacket(port); switch(packet.getPacketType()) { case ERROR: throw new Hexabus.HexabusException("Error packet received: "+((HexabusErrorPacket) packet).getErrorCode()); case INFO: return ((HexabusInfoPacket) packet).getTimestamp(); default: throw new Hexabus.HexabusException("Unexpected reply received"); } } public Calendar queryDatetimeEndpoint() throws Hexabus.HexabusException, IOException { if(dataType != Hexabus.DataType.DATETIME) { throw new Hexabus.HexabusException("Wrong data type. "+dataType+" expected"); } HexabusPacket packet = new HexabusQueryPacket(eid); int port = packet.sendPacket(device.getInetAddress()); // Receive reply packet = Hexabus.receivePacket(port); switch(packet.getPacketType()) { case ERROR: throw new Hexabus.HexabusException("Error packet received: "+((HexabusErrorPacket) packet).getErrorCode()); case INFO: return ((HexabusInfoPacket) packet).getDatetime(); default: throw new Hexabus.HexabusException("Unexpected reply received"); } } }
90dd050f5ca0fc68531cf3dfb47601a669bd7efb
d99c3111584c897265330d97f7fe14fa6e4dc118
/app/src/main/java/com/tv/supersoccer/theop/MainFragment.java
c743bad5ed8efe1f123190a454001e004918d137
[]
no_license
hendradedis/THEOplayer-example
975a018287b7e52fdc7ca793bed4b7a1a8649e31
f3fb1cbdab0842fff4f604e1218c3444112780e0
refs/heads/master
2020-03-23T01:58:45.407262
2018-07-14T13:47:49
2018-07-14T13:47:49
140,944,995
0
0
null
null
null
null
UTF-8
Java
false
false
10,191
java
/* * Copyright (C) 2017 The Android Open Source Project * * 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.tv.supersoccer.theop; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.Handler; import android.support.v17.leanback.app.BackgroundManager; import android.support.v17.leanback.app.BrowseFragment; import android.support.v17.leanback.widget.ArrayObjectAdapter; import android.support.v17.leanback.widget.HeaderItem; import android.support.v17.leanback.widget.ImageCardView; import android.support.v17.leanback.widget.ListRow; import android.support.v17.leanback.widget.ListRowPresenter; import android.support.v17.leanback.widget.OnItemViewClickedListener; import android.support.v17.leanback.widget.OnItemViewSelectedListener; import android.support.v17.leanback.widget.Presenter; import android.support.v17.leanback.widget.Row; import android.support.v17.leanback.widget.RowPresenter; import android.support.v4.app.ActivityOptionsCompat; import android.support.v4.content.ContextCompat; import android.util.DisplayMetrics; import android.util.Log; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import com.bumptech.glide.load.resource.drawable.GlideDrawable; import com.bumptech.glide.request.animation.GlideAnimation; import com.bumptech.glide.request.target.SimpleTarget; import java.util.Collections; import java.util.List; import java.util.Timer; import java.util.TimerTask; public class MainFragment extends BrowseFragment { private static final String TAG = "MainFragment"; private static final int BACKGROUND_UPDATE_DELAY = 300; private static final int GRID_ITEM_WIDTH = 200; private static final int GRID_ITEM_HEIGHT = 200; private static final int NUM_ROWS = 6; private static final int NUM_COLS = 15; private final Handler mHandler = new Handler(); private Drawable mDefaultBackground; private DisplayMetrics mMetrics; private Timer mBackgroundTimer; private String mBackgroundUri; private BackgroundManager mBackgroundManager; @Override public void onActivityCreated(Bundle savedInstanceState) { Log.i(TAG, "onCreate"); super.onActivityCreated(savedInstanceState); prepareBackgroundManager(); setupUIElements(); loadRows(); setupEventListeners(); } @Override public void onDestroy() { super.onDestroy(); if (null != mBackgroundTimer) { Log.d(TAG, "onDestroy: " + mBackgroundTimer.toString()); mBackgroundTimer.cancel(); } } private void loadRows() { List<Movie> list = MovieList.setupMovies(); ArrayObjectAdapter rowsAdapter = new ArrayObjectAdapter(new ListRowPresenter()); CardPresenter cardPresenter = new CardPresenter(); int i; for (i = 0; i < NUM_ROWS; i++) { if (i != 0) { Collections.shuffle(list); } ArrayObjectAdapter listRowAdapter = new ArrayObjectAdapter(cardPresenter); for (int j = 0; j < NUM_COLS; j++) { listRowAdapter.add(list.get(j % 5)); } HeaderItem header = new HeaderItem(i, MovieList.MOVIE_CATEGORY[i]); rowsAdapter.add(new ListRow(header, listRowAdapter)); } HeaderItem gridHeader = new HeaderItem(i, "PREFERENCES"); GridItemPresenter mGridPresenter = new GridItemPresenter(); ArrayObjectAdapter gridRowAdapter = new ArrayObjectAdapter(mGridPresenter); gridRowAdapter.add(getResources().getString(R.string.grid_view)); gridRowAdapter.add(getString(R.string.error_fragment)); gridRowAdapter.add(getResources().getString(R.string.personal_settings)); rowsAdapter.add(new ListRow(gridHeader, gridRowAdapter)); setAdapter(rowsAdapter); } private void prepareBackgroundManager() { mBackgroundManager = BackgroundManager.getInstance(getActivity()); mBackgroundManager.attach(getActivity().getWindow()); mDefaultBackground = ContextCompat.getDrawable(getActivity(), R.drawable.default_background); mMetrics = new DisplayMetrics(); getActivity().getWindowManager().getDefaultDisplay().getMetrics(mMetrics); } private void setupUIElements() { // setBadgeDrawable(getActivity().getResources().getDrawable( // R.drawable.videos_by_google_banner)); setTitle(getString(R.string.browse_title)); // Badge, when set, takes precedent // over title setHeadersState(HEADERS_ENABLED); setHeadersTransitionOnBackEnabled(true); // set fastLane (or headers) background color setBrandColor(ContextCompat.getColor(getActivity(), R.color.fastlane_background)); // set search icon color setSearchAffordanceColor(ContextCompat.getColor(getActivity(), R.color.search_opaque)); } private void setupEventListeners() { setOnSearchClickedListener(new View.OnClickListener() { @Override public void onClick(View view) { Toast.makeText(getActivity(), "Implement your own in-app search", Toast.LENGTH_LONG) .show(); } }); setOnItemViewClickedListener(new ItemViewClickedListener()); setOnItemViewSelectedListener(new ItemViewSelectedListener()); } private void updateBackground(String uri) { int width = mMetrics.widthPixels; int height = mMetrics.heightPixels; Glide.with(getActivity()) .load(uri) .centerCrop() .error(mDefaultBackground) .into(new SimpleTarget<GlideDrawable>(width, height) { @Override public void onResourceReady(GlideDrawable resource, GlideAnimation<? super GlideDrawable> glideAnimation) { mBackgroundManager.setDrawable(resource); } }); mBackgroundTimer.cancel(); } private void startBackgroundTimer() { if (null != mBackgroundTimer) { mBackgroundTimer.cancel(); } mBackgroundTimer = new Timer(); mBackgroundTimer.schedule(new UpdateBackgroundTask(), BACKGROUND_UPDATE_DELAY); } private final class ItemViewClickedListener implements OnItemViewClickedListener { @Override public void onItemClicked(Presenter.ViewHolder itemViewHolder, Object item, RowPresenter.ViewHolder rowViewHolder, Row row) { if (item instanceof Movie) { Movie movie = (Movie) item; Log.d(TAG, "Item: " + item.toString()); Intent intent = new Intent(getActivity(), DetailsActivity.class); intent.putExtra(DetailsActivity.MOVIE, movie); Bundle bundle = ActivityOptionsCompat.makeSceneTransitionAnimation( getActivity(), ((ImageCardView) itemViewHolder.view).getMainImageView(), DetailsActivity.SHARED_ELEMENT_NAME) .toBundle(); getActivity().startActivity(intent, bundle); } else if (item instanceof String) { if (((String) item).contains(getString(R.string.error_fragment))) { Intent intent = new Intent(getActivity(), BrowseErrorActivity.class); startActivity(intent); } else { Toast.makeText(getActivity(), ((String) item), Toast.LENGTH_SHORT).show(); } } } } private final class ItemViewSelectedListener implements OnItemViewSelectedListener { @Override public void onItemSelected( Presenter.ViewHolder itemViewHolder, Object item, RowPresenter.ViewHolder rowViewHolder, Row row) { if (item instanceof Movie) { mBackgroundUri = ((Movie) item).getBackgroundImageUrl(); startBackgroundTimer(); } } } private class UpdateBackgroundTask extends TimerTask { @Override public void run() { mHandler.post(new Runnable() { @Override public void run() { updateBackground(mBackgroundUri); } }); } } private class GridItemPresenter extends Presenter { @Override public ViewHolder onCreateViewHolder(ViewGroup parent) { TextView view = new TextView(parent.getContext()); view.setLayoutParams(new ViewGroup.LayoutParams(GRID_ITEM_WIDTH, GRID_ITEM_HEIGHT)); view.setFocusable(true); view.setFocusableInTouchMode(true); view.setBackgroundColor( ContextCompat.getColor(getActivity(), R.color.default_background)); view.setTextColor(Color.WHITE); view.setGravity(Gravity.CENTER); return new ViewHolder(view); } @Override public void onBindViewHolder(ViewHolder viewHolder, Object item) { ((TextView) viewHolder.view).setText((String) item); } @Override public void onUnbindViewHolder(ViewHolder viewHolder) { } } }
bfce417130b20576db61016190b3521bfa9fa38b
0a9c8d0adbb8048433da7670ea83b51fcaceba31
/app/src/main/java/com/idx/launcher/figure/data/Person.java
05c2f717ee15669ac68d3f912a7f7b0299dc9adb
[]
no_license
sqHayden/Launcher
9d89bfe9fd7dfd1a3713b5beb4c0fbf82fcafb4a
11f9bb5e79525de6f58f4b2849a50ac346c9aa45
refs/heads/master
2020-03-21T14:47:48.944823
2018-06-25T02:09:22
2018-06-25T02:09:22
138,676,131
0
0
null
null
null
null
UTF-8
Java
false
false
188
java
package com.idx.launcher.figure.data; /** * Created by darkmi on 4/26/18. */ public class Person { private String name; public String getName() { return name; } }
227c4db8ab152b4bd4605be13074a560cb74323b
436058ef4e3139ea4d5974128af7a54084defac2
/src/other/LunarLanding.java
f19027b80d1e117b900952a187e2bf9329039d3c
[]
no_license
softposlive/softposcontrol
a2ee4d96406d7b5be9f62941e93ebbdb96dfe6c8
5bcd713ddf3c287edcf87cd74937a06c70c85b21
refs/heads/master
2018-12-28T07:29:32.893639
2014-09-18T09:00:03
2014-09-19T02:01:03
23,983,095
0
1
null
null
null
null
UTF-8
Java
false
false
1,494
java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package other; import java.util.*; public class LunarLanding { public long getElapsedSeconds(GregorianCalendar gc1, GregorianCalendar gc2) { Date d1 = gc1.getTime(); Date d2 = gc2.getTime(); long l1 = d1.getTime(); long l2 = d2.getTime(); long difference = Math.abs(l2 - l1); return difference / 1000; } public void calcHM(long timeInSeconds) { long hours, minutes, seconds; hours = timeInSeconds / 3600; timeInSeconds = timeInSeconds - (hours * 3600); minutes = timeInSeconds / 60; System.out.println(hours + " hour(s) " + minutes + " minute(s)" ); } public static void main(String[] args) { GregorianCalendar lunarLanding = new GregorianCalendar(1969, Calendar.JULY, 20, 16, 17); GregorianCalendar lunarDeparture = new GregorianCalendar(1969, Calendar.JULY, 21, 13, 54); GregorianCalendar startEVA = new GregorianCalendar(1969, Calendar.JULY, 20, 22, 56); GregorianCalendar endEVA = new GregorianCalendar(1969, Calendar.JULY, 21, 1, 9); LunarLanding apollo = new LunarLanding(); long eva = apollo.getElapsedSeconds(startEVA, endEVA); System.out.print("EVA duration = "); apollo.calcHM(eva); long lunarStay = apollo.getElapsedSeconds(lunarLanding, lunarDeparture); System.out.print("Lunar stay = "); apollo.calcHM(lunarStay); } }
53291ddeab33bfdc11bcddf9c8d2e905f1909007
3de9f16fe9a1c7f5aa92cda83d8ca59256d56955
/src/my/shop/member/MemberManager.java
4265422db95b094ea58eaa1f44aec5b5c2db93d0
[]
no_license
ryuat/Basic-WEB-Proejct
a9cda2fea09fca6ddc94d27c6e42df9fc1e0ace8
0bf0d9d4a2fb0e1e6a8bba25f1b407ecf9867cfa
refs/heads/master
2020-03-28T01:17:07.149354
2018-09-11T10:50:19
2018-09-11T10:50:19
147,493,069
0
0
null
null
null
null
UTF-8
Java
false
false
7,841
java
package my.shop.member; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import javax.naming.Context; import javax.naming.InitialContext; import javax.sql.DataSource; public class MemberManager { private Connection conn; private PreparedStatement pstmt; private ResultSet rs; private DataSource ds; public MemberManager() { try { Context context = new InitialContext(); // DB CP(Connection Pooling) ds = (DataSource)context.lookup("java:comp/env/jdbc_maria"); } catch (Exception e) { System.out.println("DBCP Lookup err: " + e); } } public ArrayList<ZipcodeBean> getZip(String area3){ ArrayList<ZipcodeBean> list = new ArrayList<>(); try { conn = ds.getConnection(); String sql = "select * from ziptab where area3 like ?"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, area3 +"%"); rs = pstmt.executeQuery(); while(rs.next()) { // System.out.println(rs.getString(4)); ZipcodeBean bean = new ZipcodeBean(); bean.setZipcode(rs.getString(1)); bean.setArea1(rs.getString(2)); bean.setArea2(rs.getString(3)); bean.setArea3(rs.getString(4)); bean.setArea4(rs.getString(5)); list.add(bean); } } catch (Exception e) { System.out.println("getZip() err: " + e); }finally { try { if(rs != null) rs.close(); if(pstmt != null) pstmt.close(); if(conn != null) conn.close(); } catch (Exception e2) { System.out.println("getZip() finally err: " + e2); } } return list; } public boolean checkId(String id) { boolean result = false; try { String sql = "select id from member where id = ?"; conn = ds.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1, id); rs = pstmt.executeQuery(); if(rs.next()) result = true; } catch (Exception e) { // TODO: handle exception }finally { try { if(rs != null) rs.close(); if(pstmt != null) pstmt.close(); if(conn != null) conn.close(); } catch (Exception e2) { System.out.println("getZip() finally err: " + e2); } } return result; } public boolean memInsert(MemberBean bean) { boolean result = false; String sql = "insert into member values(?,?,?,?,?,?,?,?)"; try { conn = ds.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1, bean.getId()); pstmt.setString(2, bean.getPasswd()); pstmt.setString(3, bean.getName()); pstmt.setString(4, bean.getEmail()); pstmt.setString(5, bean.getPhone()); pstmt.setString(6, bean.getZipcode()); pstmt.setString(7, bean.getAddress()); pstmt.setString(8, bean.getJob()); result = pstmt.executeUpdate() > 0 ? true:false; } catch (Exception e) { System.out.println("memInsert() err: " + e); }finally { try { if(rs != null) rs.close(); if(pstmt != null) pstmt.close(); if(conn != null) conn.close(); } catch (Exception e2) { System.out.println("memInsert() finally err: " + e2); } } return result; } public int loginCheck(String id, String passwd) { int result = 0; // 0: id 틀림, 1: 비밀번호 틀림 String sql = "select id from member where id = ?"; try { conn = ds.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1, id); rs = pstmt.executeQuery(); if(!rs.next()) { return result; } result++; // 아이디 맞으면 1 sql = "select id from member where passwd=?"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, passwd); rs = pstmt.executeQuery(); if(!rs.next()) { return result; } result++; // 비밀번호 맞으면 2 } catch (Exception e) { System.out.println("memInsert() err: " + e); }finally { try { if(rs != null) rs.close(); if(pstmt != null) pstmt.close(); if(conn != null) conn.close(); } catch (Exception e2) { System.out.println("memInsert() finally err: " + e2); } } return result; } public boolean adminLoginChk(String id, String passwd) { boolean result = false; // 0: id 틀림, 1: 비밀번호 틀림 String sql = "select admin_id from admin where admin_id = ? and admin_passwd = ?"; try { conn = ds.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1, id); pstmt.setString(2, passwd); rs = pstmt.executeQuery(); if(rs.next()) { result = true; } System.out.println("result: " + result); } catch (Exception e) { System.out.println("adminLoginChk() err: " + e); }finally { try { if(rs != null) rs.close(); if(pstmt != null) pstmt.close(); if(conn != null) conn.close(); } catch (Exception e2) { System.out.println("adminLoginChk() finally err: " + e2); } } return result; } public MemberBean getMember(String id) { MemberBean bean = null; String sql = "select * from member where id = ?"; try { conn = ds.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1, id); rs = pstmt.executeQuery(); if(rs.next()) { bean = new MemberBean(); bean.setId(rs.getString("id")); bean.setPasswd(rs.getString("passwd")); bean.setName(rs.getString("name")); bean.setEmail(rs.getString("email")); bean.setPhone(rs.getString("phone")); bean.setZipcode(rs.getString("zipcode")); bean.setAddress(rs.getString("address")); bean.setJob(rs.getString("job")); } } catch (Exception e) { System.out.println("getMember() err: " + e); }finally { try { if(rs != null) rs.close(); if(pstmt != null) pstmt.close(); if(conn != null) conn.close(); } catch (Exception e2) { System.out.println("getMember() finally err: " + e2); } } return bean; } public boolean memberUpdate(MemberBean bean, String id) { boolean result = false; String sql = "update member set passwd=?,name=?,email=?,phone=?,zipcode=?,address=?,job=?" + "where id = ?"; try { conn = ds.getConnection(); pstmt = conn.prepareStatement(sql); pstmt.setString(1, bean.getPasswd()); pstmt.setString(2, bean.getName()); pstmt.setString(3, bean.getEmail()); pstmt.setString(4, bean.getPhone()); pstmt.setString(5, bean.getZipcode()); pstmt.setString(6, bean.getAddress()); pstmt.setString(7, bean.getJob()); pstmt.setString(8, bean.getId()); result = pstmt.executeUpdate() > 0 ? true:false; } catch (Exception e) { System.out.println("memberUpdate() err: " + e); }finally { try { if(rs != null) rs.close(); if(pstmt != null) pstmt.close(); if(conn != null) conn.close(); } catch (Exception e2) { System.out.println("memberUpdate() finally err: " + e2); } } return result; } // admin 관련 public ArrayList<MemberBean> getMemeberAll(){ ArrayList<MemberBean> list = new ArrayList<MemberBean>(); try { conn = ds.getConnection(); String sql = "select * from member"; pstmt = conn.prepareStatement(sql); rs = pstmt.executeQuery(); System.out.println("test1"); while(rs.next()) { MemberBean bean = new MemberBean(); bean.setId(rs.getString("id")); bean.setPasswd(rs.getString("passwd")); bean.setName(rs.getString("name")); bean.setEmail(rs.getString("email")); bean.setPhone(rs.getString("phone")); bean.setPasswd(rs.getString("passwd")); bean.setZipcode(rs.getString("zipcode")); bean.setAddress(rs.getString("address")); bean.setJob(rs.getString("job")); list.add(bean); } } catch (Exception e) { System.out.println("getMemeberAll() err: " + e); }finally { try { if(rs != null) rs.close(); if(pstmt != null) pstmt.close(); if(conn != null) conn.close(); } catch (Exception e2) { System.out.println("getMemeberAll() finally err: " + e2); } } return list; } }
2049eef31ce9a549085f03669d4f1582fc910d27
26e611565ce0e9eed154caaf6548a281a829d356
/onvif-ws-client/src/main/java/org/onvif/ver10/advancedsecurity/wsdl/TLSServerCapabilities.java
3baeb507381579e90f0438d7f3fde46b069ab9b3
[ "Apache-2.0" ]
permissive
doniexun/onvif-1
ecb366070dca73781c7baf3b9bcff94dd68001f5
ff9839c099e5f81d877a1753598a508c5c0bfc6b
refs/heads/master
2020-05-27T09:14:42.784064
2017-12-20T18:15:59
2017-12-20T18:15:59
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,978
java
package org.onvif.ver10.advancedsecurity.wsdl; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyAttribute; import javax.xml.bind.annotation.XmlAnyElement; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.namespace.QName; import org.w3c.dom.Element; /** * The capabilities of a TLS server implementation on a device. * * <p>Classe Java per TLSServerCapabilities complex type. * * <p>Il seguente frammento di schema specifica il contenuto previsto contenuto in questa classe. * * <pre> * &lt;complexType name="TLSServerCapabilities"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;any processContents='lax' maxOccurs="unbounded" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;attribute name="TLSServerSupported" type="{http://www.onvif.org/ver10/advancedsecurity/wsdl}TLSVersions" /&gt; * &lt;attribute name="MaximumNumberOfTLSCertificationPaths" type="{http://www.w3.org/2001/XMLSchema}positiveInteger" /&gt; * &lt;attribute name="TLSClientAuthSupported" type="{http://www.w3.org/2001/XMLSchema}boolean" /&gt; * &lt;attribute name="MaximumNumberOfTLSCertificationPathValidationPolicies" type="{http://www.w3.org/2001/XMLSchema}nonNegativeInteger" /&gt; * &lt;anyAttribute processContents='lax'/&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "TLSServerCapabilities", propOrder = { "any" }) public class TLSServerCapabilities { @XmlAnyElement(lax = true) protected List<Object> any; @XmlAttribute(name = "TLSServerSupported") protected List<String> tlsServerSupported; @XmlAttribute(name = "MaximumNumberOfTLSCertificationPaths") @XmlSchemaType(name = "positiveInteger") protected BigInteger maximumNumberOfTLSCertificationPaths; @XmlAttribute(name = "TLSClientAuthSupported") protected Boolean tlsClientAuthSupported; @XmlAttribute(name = "MaximumNumberOfTLSCertificationPathValidationPolicies") @XmlSchemaType(name = "nonNegativeInteger") protected BigInteger maximumNumberOfTLSCertificationPathValidationPolicies; @XmlAnyAttribute private Map<QName, String> otherAttributes = new HashMap<QName, String>(); /** * Gets the value of the any property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the any property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAny().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Element } * {@link Object } * * */ public List<Object> getAny() { if (any == null) { any = new ArrayList<Object>(); } return this.any; } /** * Gets the value of the tlsServerSupported property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the tlsServerSupported property. * * <p> * For example, to add a new item, do as follows: * <pre> * getTLSServerSupported().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getTLSServerSupported() { if (tlsServerSupported == null) { tlsServerSupported = new ArrayList<String>(); } return this.tlsServerSupported; } /** * Recupera il valore della proprietà maximumNumberOfTLSCertificationPaths. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getMaximumNumberOfTLSCertificationPaths() { return maximumNumberOfTLSCertificationPaths; } /** * Imposta il valore della proprietà maximumNumberOfTLSCertificationPaths. * * @param value * allowed object is * {@link BigInteger } * */ public void setMaximumNumberOfTLSCertificationPaths(BigInteger value) { this.maximumNumberOfTLSCertificationPaths = value; } /** * Recupera il valore della proprietà tlsClientAuthSupported. * This getter has been renamed from isTLSClientAuthSupported() to getTLSClientAuthSupported() by cxf-xjc-boolean plugin. * * @return * possible object is * {@link Boolean } * */ public Boolean getTLSClientAuthSupported() { return tlsClientAuthSupported; } /** * Imposta il valore della proprietà tlsClientAuthSupported. * * @param value * allowed object is * {@link Boolean } * */ public void setTLSClientAuthSupported(Boolean value) { this.tlsClientAuthSupported = value; } /** * Recupera il valore della proprietà maximumNumberOfTLSCertificationPathValidationPolicies. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getMaximumNumberOfTLSCertificationPathValidationPolicies() { return maximumNumberOfTLSCertificationPathValidationPolicies; } /** * Imposta il valore della proprietà maximumNumberOfTLSCertificationPathValidationPolicies. * * @param value * allowed object is * {@link BigInteger } * */ public void setMaximumNumberOfTLSCertificationPathValidationPolicies(BigInteger value) { this.maximumNumberOfTLSCertificationPathValidationPolicies = value; } /** * Gets a map that contains attributes that aren't bound to any typed property on this class. * * <p> * the map is keyed by the name of the attribute and * the value is the string value of the attribute. * * the map returned by this method is live, and you can add new attribute * by updating the map directly. Because of this design, there's no setter. * * * @return * always non-null */ public Map<QName, String> getOtherAttributes() { return otherAttributes; } }