text
stringlengths
10
2.72M
package gov.nih.mipav.view.renderer.WildMagic.BallPivoting; import java.util.*; public class TriMesh { /// Set of vertices public Vector<Vertex> vert = new Vector<Vertex>(); /// Real number of vertices public int vn; /// Set of faces public Vector<Face> face = new Vector<Face>(); /// Real number of faces public int fn; /// Bounding box of the mesh public Box3 bbox = new Box3(); /// The incremental mark public int imark; public TriMesh() { fn = 0; vn = 0; imark = 0; } public void setVertex( Vector<Point3> _vert){ // vert = _vert; vn = _vert.size(); vert.setSize(vn); for ( int i = 0; i < vn; i++ ) { float x, y, z; x = ((Point3)_vert.get(i)).x; y = ((Point3)_vert.get(i)).y; z = ((Point3)_vert.get(i)).z; Vertex v = new Vertex(); v.setP(new Point3(x, y, z)); vert.set(i, v); } } public int simplexNumber(){ return fn; } public int vertexNumber(){ return vn; } /// Initialize the imark-system of the faces public final void initFaceIMark() { Face f = null; int f_index = 0; if ( face.size() > 0 ) { for(f_index = 0;f_index <face.size();++f_index) f = face.get(f_index); if( !f.IsD() && f.IsR() && f.IsW() ) f.InitIMark(); } } /// Initialize the imark-system of the vertices public final void initVertexIMark() { Vertex vi = null; int v_index = 0; for(v_index = 0 ;v_index < vert.size();++v_index) vi = vert.get(v_index); if( !vi.isD() && vi.isRW() ) vi.initIMark(); } /** Access function to the incremental mark. */ public final int iMark(){return imark;} /** Check if the vertex incremental mark matches the one of the mesh. @param v Vertex pointer */ public final boolean isMarked( Vertex v ) { return v.imark == imark; } /** Check if the face incremental mark matches the one of the mesh. @param v Face pointer */ public final boolean isMarked( Face f ) { return f.imark == imark; } /** Set the vertex incremental mark of the vertex to the one of the mesh. @param v Vertex pointer */ public final void mark( Vertex v ) { v.imark = imark; } /** Set the face incremental mark of the vertex to the one of the mesh. @param v Vertex pointer */ public final void mark( Face f ) { f.imark = imark; } /// Unmark the mesh public final void unMarkAll() { ++imark; } public final boolean hasPerVertexNormal() { return Vertex.hasNormal() ; } }
package com.tutorialspoint; /** * @author warlord * */ public class TextEditor { private SpellChecker spellChecker; private int numberOfWords; private String textOwner; // public TextEditor(SpellChecker spellChecker, int numberOfWords, String textOwner) { // System.out.println("Inside TextEditor constructor...\n" ); // this.spellChecker = spellChecker; // this.setNumberOfWords(numberOfWords); // this.textOwner = textOwner; // } public void spellCheck() { spellChecker.checkSpelling(); } //A getter method to return spellChecker public SpellChecker getSpellChecker() { return spellChecker; } //A setter method to inject the dependency //This method will be invoked automatically when constructing a TextEditor object public void setSpellChecker(SpellChecker spellChecker) { System.out.println("Inside setSpellChecker...\n"); this.spellChecker = spellChecker; } /** * @return the numberOfWords */ public int getNumberOfWords() { return numberOfWords; } /** * @param numberOfWords the numberOfWords to set */ public void setNumberOfWords(int numberOfWords) { this.numberOfWords = numberOfWords; } /** * @return the textOwner */ public String getTextOwner() { return textOwner; } /** * @param textOwner the textOwner to set */ public void setTextOwner(String textOwner) { this.textOwner = textOwner; } }
/* $Id$ */ package djudge.acmcontester.structures; import java.util.HashMap; import djudge.acmcontester.AuthentificationData; import djudge.utils.xmlrpc.AbstractRemoteTable; import djudge.utils.xmlrpc.HashMapSerializable; public class UserData extends HashMapSerializable { public String id = "-1"; public String username = ""; public String password = ""; public String name = ""; public String role = ""; public UserData() { // TODO Auto-generated constructor stub } public UserData(String username, String password, String name, String role) { this.name = name; this.password = password; this.role = role; this.username = username; } public UserData(String id, String username, String password, String name, String role) { this.id = id; this.name = name; this.password = password; this.role = role; this.username = username; } public UserData(HashMap<String, String> map) { fromHashMap(map); } @Override public HashMap<String, String> toHashMap() { HashMap<String, String> res = new HashMap<String, String>(); res.put("id", id); res.put("username", username); res.put("password", password); res.put("name", name); res.put("role", role); return res; } @SuppressWarnings("unchecked") @Override public void fromHashMap(HashMap map) { id = (String) map.get("id"); username = (String) map.get("username"); password = (String) map.get("password"); name = (String) map.get("name"); role = (String) map.get("role"); } @Override protected int getColumnCount() { return 5; } @Override protected Class<? extends AbstractRemoteTable> getTableClass() { return RemoteTableUsers.class; } @Override protected Object getValueAt(int column) { switch (column) { case 0: return id; case 1: return username; case 2: return password; case 3: return name; case 4: return role; default: return id; } } @Override protected void setValueAt(int column, String value) { switch (column) { case 1: username = value; break; case 2: password = value; break; case 3: name = value; break; case 4: role = value; break; } } @Override protected boolean save() { if (!fDataChanged) return true; AuthentificationData ad = table.getAuthentificationData(); boolean res = table.getConnector().editUser( ad.getUsername(), ad.getPassword(), id, username, password, name, role); fDataChanged = false; return res; } @Override protected boolean create() { AuthentificationData ad = table.getAuthentificationData(); return table.getConnector().addUser( ad.getUsername(), ad.getPassword(), username, password, name, role); } @Override protected boolean delete() { AuthentificationData ad = table.getAuthentificationData(); return table.getConnector().deleteUser( ad.getUsername(), ad.getPassword(), id); } public String toString() { return id + " " + username + " " + password + " " + name + " " + role; } }
/******************************************************************************* * Copyright 2013 SecureKey Technologies Inc. * * 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.openmidaas.library.model.core; public class MIDaaSException extends Exception { private static final long serialVersionUID = 3928915108062731435L; private MIDaaSError mErrorCode; public MIDaaSException(MIDaaSError errorCode) { this.mErrorCode = errorCode; } public MIDaaSError getError() { return mErrorCode; } @Override public String toString() { return (mErrorCode.getErrorCode() + " - " + mErrorCode.getErrorMessage()); } }
/** * Copyright 2017 伊永飞 * * 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.yea.shiro.mgt; import org.apache.shiro.authc.credential.HashedCredentialsMatcher; import org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy; import org.apache.shiro.authc.pam.ModularRealmAuthenticator; import org.apache.shiro.authz.ModularRealmAuthorizer; import org.apache.shiro.authz.permission.WildcardPermissionResolver; import org.apache.shiro.mgt.DefaultSecurityManager; import com.yea.core.remote.AbstractEndpoint; import com.yea.core.shiro.password.EncrytPassword; import com.yea.shiro.credential.RetryLimitHashedCredentialsMatcher; import com.yea.shiro.realm.netty.NettyRealm; /** * * @author yiyongfei * */ public class ShiroSecurityManager extends DefaultSecurityManager{ private HashedCredentialsMatcher credentialsMatcher; public ShiroSecurityManager() { super(); // 设置authenticator ModularRealmAuthenticator authenticator = new ModularRealmAuthenticator(); authenticator.setAuthenticationStrategy(new AtLeastOneSuccessfulStrategy()); setAuthenticator(authenticator); // 设置authorizer ModularRealmAuthorizer authorizer = new ModularRealmAuthorizer(); authorizer.setPermissionResolver(new WildcardPermissionResolver()); setAuthorizer(authorizer); // 设置密码校验Matcher credentialsMatcher = new RetryLimitHashedCredentialsMatcher(); credentialsMatcher.setHashAlgorithmName(EncrytPassword.PASSWORD_HASH); credentialsMatcher.setHashIterations(EncrytPassword.HASH_ITERATIONS); credentialsMatcher.setStoredCredentialsHexEncoded(true); } public void setEndpoint(AbstractEndpoint endpoint){ NettyRealm realm = new NettyRealm(); //设置Netty的客户端 realm.setNettyClient(endpoint); //设置密码校验Matcher realm.setCredentialsMatcher(credentialsMatcher); //设置是否查找权限,为true时,在获取授权时会查找所授予的权限 realm.setPermissionsLookupEnabled(true); //认证信息是否缓存 realm.setAuthenticationCachingEnabled(false); //授权信息是否缓存 realm.setAuthorizationCachingEnabled(false); this.setRealm(realm); } }
package cz.cvut.panskpe1.rssfeeder.activity.main; import android.app.Activity; import android.app.Fragment; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.content.res.Configuration; import android.os.Bundle; import android.os.IBinder; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import cz.cvut.panskpe1.rssfeeder.R; import cz.cvut.panskpe1.rssfeeder.activity.article.ArticleDetailActivity; import cz.cvut.panskpe1.rssfeeder.activity.article.ArticleDetailFragment; import cz.cvut.panskpe1.rssfeeder.activity.feed.FeedActivity; import cz.cvut.panskpe1.rssfeeder.service.AlarmBroadcastReceiver; import cz.cvut.panskpe1.rssfeeder.service.DownloadService; /** * Created by petr on 3/19/16. */ public class MainActivity extends Activity implements ArticlesListFragment.ArticleListFragmentCallback, DownloadService.DownloadServiceCallback { private static final String TAG = "MAIN_ACTIVITY"; private boolean isXlarge; private DownloadService mService; private MenuItem mRefreshMenuItem; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState == null) addMainFragment(); if (findViewById(R.id.detailFragment) != null) { isXlarge = true; addArticleDetailFragment(); } else isXlarge = false; } private void addArticleDetailFragment() { FragmentManager manager = getFragmentManager(); if (manager.findFragmentById(R.id.detailFragment) == null) { FragmentTransaction transaction = manager.beginTransaction(); transaction.add(R.id.detailFragment, createArticleDetailFragment()); transaction.commit(); } } private Fragment createArticleDetailFragment() { return Fragment.instantiate(this, ArticleDetailFragment.class.getName()); } private void addMainFragment() { getFragmentManager().beginTransaction() .add(R.id.containerMainActivity, new ArticlesListFragment()) .commit(); } @Override protected void onStop() { if (mService != null) { unbindService(mConnection); } super.onStop(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); mRefreshMenuItem = menu.findItem(R.id.update_item); return true; } public void refreshingStart() { mRefreshMenuItem.setActionView(R.layout.action_progressbar); mRefreshMenuItem.expandActionView(); } public void refreshingStop() { if (mRefreshMenuItem.getActionView() != null) { mRefreshMenuItem.collapseActionView(); mRefreshMenuItem.setActionView(null); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.feeds_item: Intent intent = new Intent(this, FeedActivity.class); startActivity(intent); return true; case R.id.update_item: AlarmBroadcastReceiver.startService(this); return true; default: return super.onOptionsItemSelected(item); } } @Override protected void onStart() { super.onStart(); Intent intentBind = new Intent(this, DownloadService.class); bindService(intentBind, mConnection, Context.BIND_AUTO_CREATE); initArticleByLastId(); // Toast.makeText(this, getSizeName(this), Toast.LENGTH_LONG).show(); } private String getSizeName() { int screenLayout = this.getResources().getConfiguration().screenLayout; screenLayout &= Configuration.SCREENLAYOUT_SIZE_MASK; switch (screenLayout) { case Configuration.SCREENLAYOUT_SIZE_SMALL: return "small"; case Configuration.SCREENLAYOUT_SIZE_NORMAL: return "normal"; case Configuration.SCREENLAYOUT_SIZE_LARGE: return "large"; case 4: return "xlarge"; default: return "undefined"; } } @Override public void onArticleClick(long id) { Log.i(TAG, "Open Article with ID: " + id); if (isXlarge) { ArticleDetailFragment fragment = (ArticleDetailFragment) getFragmentManager().findFragmentById(R.id.detailFragment); fragment.fillData(id); } else { Intent intent = new Intent(this, ArticleDetailActivity.class); intent.putExtra(ArticleDetailActivity.ENTRY_ID, id); startActivity(intent); } } @Override public void initArticleByLastId() { if (isXlarge) { ArticlesListFragment listFragment = (ArticlesListFragment) getFragmentManager().findFragmentById(R.id.containerMainActivity); ArticleDetailFragment fragment = (ArticleDetailFragment) getFragmentManager().findFragmentById(R.id.detailFragment); fragment.fillData(listFragment.getLastId()); } } @Override public void startRefresh() { Log.d("TAG", "START REFRESH!!!!!!!!!!!!!!!!!"); runOnUiThread(new Runnable() { @Override public void run() { refreshingStart(); } }); } @Override public void notifyDownloadFailed() { Toast.makeText(this, getString(R.string.update_failed), Toast.LENGTH_SHORT).show(); } @Override public void stopRefresh() { Log.d("TAG", "STOP REFRESH!!!!!!!!!!!!!!!!!"); runOnUiThread(new Runnable() { @Override public void run() { refreshingStop(); } }); } ServiceConnection mConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { mService = ((DownloadService.MyBinder) service).getServiceInstance(); mService.registerClient(MainActivity.this); if (mRefreshMenuItem != null && mService.isDownloading()) { refreshingStart(); } } @Override public void onServiceDisconnected(ComponentName name) { mService = null; } }; }
import java.util.Hashtable; import java.util.Iterator; public class Keyframe{ private Hashtable<Long, Control> bookmarks; final long loop_time; public Keyframe(long loop) { this.bookmarks = new Hashtable<Long, Control>(); this.loop_time=loop; } public synchronized void put(long usecs, Control cont){ this.bookmarks.put(usecs, cont); } public synchronized Control get(Timestamp time){ long usecs= time.sec*1000000+time.usec; return this.bookmarks.get(usecs); } public synchronized Control get(long usecs){ return this.bookmarks.get(usecs); } }
package com.jooink.experiments.gwtwebgl.client.tests.params; import com.google.gwt.canvas.client.Canvas; import com.google.gwt.dom.client.CanvasElement; import com.google.gwt.typedarrays.shared.Float32Array; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HasWidgets.ForIsWidget; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.web.bindery.event.shared.EventBus; import com.googlecode.gwtwebgl.client.WebGL; import com.googlecode.gwtwebgl.html.WebGLRenderingContext; import com.googlecode.gwtwebgl.utils.Any; import com.jooink.experiments.gwtwebgl.client.Test; public class Params extends Test { VerticalPanel list = new VerticalPanel(); WebGLRenderingContext ctx; @Override public void execute(ForIsWidget cont, EventBus bus) { cont.clear(); cont.add(list); Canvas canvas = Canvas.createIfSupported(); cont.clear(); cont.add(list); ctx = WebGL.getContext(canvas); CanvasElement canvasElement = canvas.getCanvasElement(); canvasElement.setWidth(64); canvasElement.setHeight(48); ctx.viewport(0, 0, 64, 48); list.add(canvas); //empty tryParam(WebGLRenderingContext.ALIASED_LINE_WIDTH_RANGE,"ALIASED_LINE_WIDTH_RANGE","Float32Array (with 2 elements)"); tryParam(WebGLRenderingContext.ALIASED_POINT_SIZE_RANGE,"ALIASED_POINT_SIZE_RANGE","Float32Array (with 2 elements)"); tryParam(WebGLRenderingContext.ALPHA_BITS,"ALPHA_BITS","GLint"); tryParam(WebGLRenderingContext.ARRAY_BUFFER_BINDING,"ARRAY_BUFFER_BINDING","WebGLBuffer"); tryParam(WebGLRenderingContext.BLEND,"BLEND","GLboolean"); tryParam(WebGLRenderingContext.BLEND_COLOR,"BLEND_COLOR","Float32Array (with 4 values)"); tryParam(WebGLRenderingContext.BLEND_DST_ALPHA,"BLEND_DST_ALPHA","GLenum"); tryParam(WebGLRenderingContext.BLEND_DST_RGB,"BLEND_DST_RGB","GLenum"); tryParam(WebGLRenderingContext.BLEND_EQUATION_ALPHA,"BLEND_EQUATION_ALPHA","GLenum"); tryParam(WebGLRenderingContext.BLEND_EQUATION_RGB,"BLEND_EQUATION_RGB","GLenum"); tryParam(WebGLRenderingContext.BLEND_SRC_ALPHA,"BLEND_SRC_ALPHA","GLenum"); tryParam(WebGLRenderingContext.BLEND_SRC_RGB,"BLEND_SRC_RGB","GLenum"); tryParam(WebGLRenderingContext.BLUE_BITS,"BLUE_BITS","GLint"); tryParam(WebGLRenderingContext.COLOR_CLEAR_VALUE,"COLOR_CLEAR_VALUE","Float32Array (with 4 values)"); tryParam(WebGLRenderingContext.COLOR_WRITEMASK,"COLOR_WRITEMASK","sequence<GLboolean> (with 4 values)"); tryParam(WebGLRenderingContext.COMPRESSED_TEXTURE_FORMATS,"COMPRESSED_TEXTURE_FORMATS","Uint32Array"); tryParam(WebGLRenderingContext.CULL_FACE,"CULL_FACE","GLboolean"); tryParam(WebGLRenderingContext.CULL_FACE_MODE,"CULL_FACE_MODE","GLenum"); tryParam(WebGLRenderingContext.CURRENT_PROGRAM,"CURRENT_PROGRAM","WebGLProgram"); tryParam(WebGLRenderingContext.DEPTH_BITS,"DEPTH_BITS","GLint"); tryParam(WebGLRenderingContext.DEPTH_CLEAR_VALUE,"DEPTH_CLEAR_VALUE","GLfloat"); tryParam(WebGLRenderingContext.DEPTH_FUNC,"DEPTH_FUNC","GLenum"); tryParam(WebGLRenderingContext.DEPTH_RANGE,"DEPTH_RANGE","Float32Array (with 2 elements)"); tryParam(WebGLRenderingContext.DEPTH_TEST,"DEPTH_TEST","GLboolean"); tryParam(WebGLRenderingContext.DEPTH_WRITEMASK,"DEPTH_WRITEMASK","GLboolean"); tryParam(WebGLRenderingContext.DITHER,"DITHER","GLboolean"); tryParam(WebGLRenderingContext.ELEMENT_ARRAY_BUFFER_BINDING,"ELEMENT_ARRAY_BUFFER_BINDING","WebGLBuffer"); tryParam(WebGLRenderingContext.FRAMEBUFFER_BINDING,"FRAMEBUFFER_BINDING","WebGLFramebuffer"); tryParam(WebGLRenderingContext.FRONT_FACE,"FRONT_FACE","GLenum"); tryParam(WebGLRenderingContext.GENERATE_MIPMAP_HINT,"GENERATE_MIPMAP_HINT","GLenum"); tryParam(WebGLRenderingContext.GREEN_BITS,"GREEN_BITS","GLint"); tryParam(WebGLRenderingContext.LINE_WIDTH,"LINE_WIDTH","GLfloat"); tryParam(WebGLRenderingContext.MAX_COMBINED_TEXTURE_IMAGE_UNITS,"MAX_COMBINED_TEXTURE_IMAGE_UNITS","GLint"); tryParam(WebGLRenderingContext.MAX_CUBE_MAP_TEXTURE_SIZE,"MAX_CUBE_MAP_TEXTURE_SIZE","GLint"); tryParam(WebGLRenderingContext.MAX_FRAGMENT_UNIFORM_VECTORS,"MAX_FRAGMENT_UNIFORM_VECTORS","GLint"); tryParam(WebGLRenderingContext.MAX_RENDERBUFFER_SIZE,"MAX_RENDERBUFFER_SIZE","GLint"); tryParam(WebGLRenderingContext.MAX_TEXTURE_IMAGE_UNITS,"MAX_TEXTURE_IMAGE_UNITS","GLint"); tryParam(WebGLRenderingContext.MAX_TEXTURE_SIZE,"MAX_TEXTURE_SIZE","GLint"); tryParam(WebGLRenderingContext.MAX_VARYING_VECTORS,"MAX_VARYING_VECTORS","GLint"); tryParam(WebGLRenderingContext.MAX_VERTEX_ATTRIBS,"MAX_VERTEX_ATTRIBS","GLint"); tryParam(WebGLRenderingContext.MAX_VERTEX_TEXTURE_IMAGE_UNITS,"MAX_VERTEX_TEXTURE_IMAGE_UNITS","GLint"); tryParam(WebGLRenderingContext.MAX_VERTEX_UNIFORM_VECTORS,"MAX_VERTEX_UNIFORM_VECTORS","GLint"); tryParam(WebGLRenderingContext.MAX_VIEWPORT_DIMS,"MAX_VIEWPORT_DIMS","Int32Array (with 2 elements)"); tryParam(WebGLRenderingContext.PACK_ALIGNMENT,"PACK_ALIGNMENT","GLint"); tryParam(WebGLRenderingContext.POLYGON_OFFSET_FACTOR,"POLYGON_OFFSET_FACTOR","GLfloat"); tryParam(WebGLRenderingContext.POLYGON_OFFSET_FILL,"POLYGON_OFFSET_FILL","GLboolean"); tryParam(WebGLRenderingContext.POLYGON_OFFSET_UNITS,"POLYGON_OFFSET_UNITS","GLfloat"); tryParam(WebGLRenderingContext.RED_BITS,"RED_BITS","GLint"); tryParam(WebGLRenderingContext.RENDERBUFFER_BINDING,"RENDERBUFFER_BINDING","WebGLRenderbuffer"); tryParam(WebGLRenderingContext.RENDERER,"RENDERER","DOMString"); tryParam(WebGLRenderingContext.SAMPLE_BUFFERS,"SAMPLE_BUFFERS","GLint"); tryParam(WebGLRenderingContext.SAMPLE_COVERAGE_INVERT,"SAMPLE_COVERAGE_INVERT","GLboolean"); tryParam(WebGLRenderingContext.SAMPLE_COVERAGE_VALUE,"SAMPLE_COVERAGE_VALUE","GLfloat"); tryParam(WebGLRenderingContext.SAMPLES,"SAMPLES","GLint"); tryParam(WebGLRenderingContext.SCISSOR_BOX,"SCISSOR_BOX","Int32Array (with 4 elements)"); tryParam(WebGLRenderingContext.SCISSOR_TEST,"SCISSOR_TEST","GLboolean"); tryParam(WebGLRenderingContext.SHADING_LANGUAGE_VERSION,"SHADING_LANGUAGE_VERSION","DOMString"); tryParam(WebGLRenderingContext.STENCIL_BACK_FAIL,"STENCIL_BACK_FAIL","GLenum"); tryParam(WebGLRenderingContext.STENCIL_BACK_FUNC,"STENCIL_BACK_FUNC","GLenum"); tryParam(WebGLRenderingContext.STENCIL_BACK_PASS_DEPTH_FAIL,"STENCIL_BACK_PASS_DEPTH_FAIL","GLenum"); tryParam(WebGLRenderingContext.STENCIL_BACK_PASS_DEPTH_PASS,"STENCIL_BACK_PASS_DEPTH_PASS","GLenum"); tryParam(WebGLRenderingContext.STENCIL_BACK_REF,"STENCIL_BACK_REF","GLint"); tryParam(WebGLRenderingContext.STENCIL_BACK_VALUE_MASK,"STENCIL_BACK_VALUE_MASK","GLuint"); tryParam(WebGLRenderingContext.STENCIL_BACK_WRITEMASK,"STENCIL_BACK_WRITEMASK","GLuint"); tryParam(WebGLRenderingContext.STENCIL_BITS,"STENCIL_BITS","GLint"); tryParam(WebGLRenderingContext.STENCIL_CLEAR_VALUE,"STENCIL_CLEAR_VALUE","GLint"); tryParam(WebGLRenderingContext.STENCIL_FAIL,"STENCIL_FAIL","GLenum"); tryParam(WebGLRenderingContext.STENCIL_FUNC,"STENCIL_FUNC","GLenum"); tryParam(WebGLRenderingContext.STENCIL_PASS_DEPTH_FAIL,"STENCIL_PASS_DEPTH_FAIL","GLenum"); tryParam(WebGLRenderingContext.STENCIL_PASS_DEPTH_PASS,"STENCIL_PASS_DEPTH_PASS","GLenum"); tryParam(WebGLRenderingContext.STENCIL_REF,"STENCIL_REF","GLint"); tryParam(WebGLRenderingContext.STENCIL_TEST,"STENCIL_TEST","GLboolean"); tryParam(WebGLRenderingContext.STENCIL_VALUE_MASK,"STENCIL_VALUE_MASK","GLuint"); tryParam(WebGLRenderingContext.STENCIL_WRITEMASK,"STENCIL_WRITEMASK","GLuint"); tryParam(WebGLRenderingContext.SUBPIXEL_BITS,"SUBPIXEL_BITS","GLint"); tryParam(WebGLRenderingContext.TEXTURE_BINDING_2D,"TEXTURE_BINDING_2D","WebGLTexture"); tryParam(WebGLRenderingContext.TEXTURE_BINDING_CUBE_MAP,"TEXTURE_BINDING_CUBE_MAP","WebGLTexture"); tryParam(WebGLRenderingContext.UNPACK_ALIGNMENT,"UNPACK_ALIGNMENT","GLint"); tryParam(WebGLRenderingContext.UNPACK_COLORSPACE_CONVERSION_WEBGL,"UNPACK_COLORSPACE_CONVERSION_WEBGL","GLenum"); tryParam(WebGLRenderingContext.UNPACK_FLIP_Y_WEBGL,"UNPACK_FLIP_Y_WEBGL","GLboolean"); tryParam(WebGLRenderingContext.UNPACK_PREMULTIPLY_ALPHA_WEBGL,"UNPACK_PREMULTIPLY_ALPHA_WEBGL","GLboolean"); tryParam(WebGLRenderingContext.VENDOR,"VENDOR","DOMString"); tryParam(WebGLRenderingContext.VERSION,"VERSION","DOMString"); tryParam(42,"error, pname=42","error"); } private void tryParam(int pname, String name, String expected) { Any a = ctx.getParameter(pname); HTML html = new HTML(); String natively = nativelyGetParam(ctx, pname); if(pname == WebGLRenderingContext.COLOR_WRITEMASK) html.setHTML( "<b style=\"color:blue;\">"+ name + "</b>" + " ["+expected+"] {" +natively +"} " + a.getJsArrayBoolean()); else if("GLint".equals(expected)) html.setHTML( "<b>"+ name + "</b>" + " ["+expected+"] {" +natively +"} " + a.getInt()); else if("GLboolean".equals(expected)) html.setHTML( "<b>"+ name + "</b>" + " ["+expected+"] {" +natively +"} " + a.getBoolean()); else if("GLenum".equals(expected)) html.setHTML( "<b>"+ name + "</b>" + " ["+expected+"] {" +natively +"} " + a.getInt()); else if("GLfloat".equals(expected)) html.setHTML( "<b>"+ name + "</b>" + " ["+expected+"] {" +natively +"} " + a.getFloat()); else if("GLuint".equals(expected)) html.setHTML( "<b>"+ name + "</b>" + " ["+expected+"] {" +natively +"} " + a.getDouble()); else if("DOMString".equals(expected)) html.setHTML( "<b>"+ name + "</b>" + " ["+expected+"] {" +natively +"} " + a.get()); else if("WebGLBuffer".equals(expected)) html.setHTML( "<b>"+ name + "</b>" + " ["+expected+"] {" +natively +"} " + a.getWebGLBuffer()); else if("WebGLFramebuffer".equals(expected)) html.setHTML( "<b>"+ name + "</b>" + " ["+expected+"] {" +natively +"} " + a.getWebGLFramebuffer()); else if("WebGLRenderbuffer".equals(expected)) html.setHTML( "<b>"+ name + "</b>" + " ["+expected+"] {" +natively +"} " + a.getWebGLRenderbuffer()); else if("WebGLTexture".equals(expected)) html.setHTML( "<b>"+ name + "</b>" + " ["+expected+"] {" +natively +"} " + a.getWebGLTexture()); else if("WebGLProgram".equals(expected)) html.setHTML( "<b>"+ name + "</b>" + " ["+expected+"] {" +natively +"} " + a.getWebGLProgram()); else if(expected.startsWith("Float32Array")) html.setHTML( "<b>"+ name + "</b>" + " ["+expected+"] {" +natively +"} " + a.getFloat32Array()); else if(expected.startsWith("Uint32Array")) html.setHTML( "<b>"+ name + "</b>" + " ["+expected+"] {" +natively +"} " + a.getUint32Array()); else if(expected.startsWith("Int32Array")) html.setHTML( "<b>"+ name + "</b>" + " ["+expected+"] {" +natively +"} " + a.getInt32Array()); else html.setHTML( "<b style=\"color:red;\">"+ name + "</b>" + " ["+expected+"] {" +natively +"} " + a); list.add(html); } private native String nativelyGetParam(WebGLRenderingContext ctx, int pname) /*-{ var r = ctx.getParameter(pname) return '' + r + " [<b>" + (typeof r) + "</b> isA:" + Array.isArray(r) + "]"; }-*/; private Float32Array getParameter_ALIASED_LINE_WIDTH_RANGE(WebGLRenderingContext ctx) { return ctx.getParameter(WebGLRenderingContext.ALIASED_LINE_WIDTH_RANGE).getFloat32Array(); } @Override public void stop() { // TODO Auto-generated method stub } @Override public String getName() { // TODO Auto-generated method stub return "Parameters"; } }
package com.limefriends.molde.menu_map.report; import com.limefriends.molde.menu_map.entity.MoldeReportEntity; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.FormUrlEncoded; import retrofit2.http.Headers; import retrofit2.http.POST; public interface MoldeReportRestService { @Headers("Content-Type: application/json") @POST(MoldeReportApi.POST_REPORT_API) public Call<MoldeReportEntity> sendReportData(@Body MoldeReportEntity moldeReportEntity); }
package com.netcracker.entities; import com.fasterxml.jackson.annotation.JsonIgnore; import com.netcracker.services.Channels.Deliverable; import org.hibernate.validator.constraints.Range; import org.locationtech.jts.geom.Point; import org.springframework.transaction.annotation.Transactional; import javax.persistence.*; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import java.math.BigDecimal; import java.util.Collection; import java.util.Date; import java.util.Objects; import javax.persistence.*; import java.math.BigDecimal; import java.util.Collection; import java.util.Objects; @Entity @Table(name = "Routes") public class Route extends Recipient { @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "route_id_generator") @SequenceGenerator(name = "route_id_generator", sequenceName = "route_id_seq", allocationSize = 1) @Column(name = "route_id") private Long routeId; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "city_id") private City city; //убрал @Range(min=0, max=90) и заработало, почему? @Column(name = "route_begin") private Point routeBegin; //убрал @Range(min=0, max=90) и заработало, почему? @Column(name = "route_end") private Point routeEnd; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "group_id") private Group group; public Group getGroup() { return group; } public void setGroup(Group group) { this.group = group; } @Column(name = "price") private BigDecimal price; @OneToOne @JoinColumn(name = "driver_id") private User driverId; // @Column(name = "journeys") // @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL) // private Collection<Journey> journeys; public void setUsers(Collection<User> users) { this.users = users; } public Collection<User> getUsers() { return users; } @Column(name = "count_of_places") private Integer countOfPlaces; @JsonIgnore @Column(name = "account_number") private Long accountNumber; @ManyToMany(fetch = FetchType.EAGER ) @JoinTable( name = "passenger_in_route", joinColumns = { @JoinColumn(name = "route_id") }, inverseJoinColumns = { @JoinColumn(name = "user_id") } ) Collection<User> users; public Collection<User> getNotUsers() { return notUsers; } public void setNotUsers(Collection<User> notUsers) { this.notUsers = notUsers; } @ManyToMany(fetch = FetchType.LAZY ) @JoinTable( name = "passenger_not_in_route", joinColumns = { @JoinColumn(name = "route_id") }, inverseJoinColumns = { @JoinColumn(name = "user_id") } ) Collection<User> notUsers; // @Column(name = "start_day") // private Date startDate; public Route() { } public void setCountOfPlaces(Integer countOfPlaces) { this.countOfPlaces = countOfPlaces; } public Integer getCountOfPlaces() { return countOfPlaces; } // public void setStartDate(Date startDate) { // this.startDate = startDate; // } // // public Date getStartDate() { // return startDate; // } //убрал @Range(min=0, max=90) и заработало, почему? public Route( Point routeBegin, Point routeEnd, BigDecimal price, Date startDate, Integer countOfPlaces) { this.routeBegin = routeBegin; this.routeEnd = routeEnd; this.price = price; this.countOfPlaces = countOfPlaces; // this.startDate = startDate; } public Long getRouteId() { return routeId; } public void setRouteId(Long routeId) { this.routeId = routeId; } @JsonIgnore public Long getAccountNumber() { return accountNumber; } public void setAccountNumber(Long accountNumber) { this.accountNumber = accountNumber; } public City getCity() { return city; } public void setCity(City city) { this.city = city; } public Point getRouteBegin() { return routeBegin; } public void setRouteBegin(Point routeBegin) { this.routeBegin = routeBegin; } public Point getRouteEnd() { return routeEnd; } public void setRouteEnd(Point routeEnd) { this.routeEnd = routeEnd; } public BigDecimal getPrice() { return price; } public void setPrice(BigDecimal price) { this.price = price; } public User getDriverId() { return driverId; } public void setDriverId(User driverId) { this.driverId = driverId; } @Override public String toString() { return "Route{" + "routeId=" + routeId + ", city=" + city + ", routeBegin=" + routeBegin + ", routeEnd=" + routeEnd + ", group=" + group + ", price=" + price + ", driverId=" + driverId + ", countOfPlaces=" + countOfPlaces + ", accountNumber=" + accountNumber + ", users=" + users + ", notUsers=" + notUsers + '}'; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Route route = (Route) o; return Objects.equals(getRouteId(), route.getRouteId()) && Objects.equals(getCity(), route.getCity()) && Objects.equals(getRouteBegin(), route.getRouteBegin()) && Objects.equals(getRouteEnd(), route.getRouteEnd()) && Objects.equals(getGroup(), route.getGroup()) && Objects.equals(getPrice(), route.getPrice()) && Objects.equals(getDriverId(), route.getDriverId()) && Objects.equals(getCountOfPlaces(), route.getCountOfPlaces()) && Objects.equals(getAccountNumber(), route.getAccountNumber()) && Objects.equals(getUsers(), route.getUsers()) && Objects.equals(getNotUsers(), route.getNotUsers()); } @Override public int hashCode() { return Objects.hash(getRouteId(), getCity(), getRouteBegin(), getRouteEnd(), getGroup(), getPrice(), getDriverId(), getCountOfPlaces(), getAccountNumber(), getUsers(), getNotUsers()); } }
package com.memory.platform.core.exception; public class ModuleActivatorException extends Exception { /** * */ private static final long serialVersionUID = -1700620098387621128L; }
package com.happyldc.util; import android.annotation.SuppressLint; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.PixelFormat; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.util.Base64; import android.view.View; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; /** * Created by woodman on 2018/3/15. * 转换工具类 */ public final class ConvertUtils { public static final int BYTE = 1; public static final int KB = 1024; public static final int MB = 1048576; public static final int GB = 1073741824; private static final char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; private ConvertUtils() {} /** bytes转换bits * @param bytes 转换的bytes * @return 转换后的bits */ public static String bytes2Bits(final byte[] bytes) { StringBuilder sb = new StringBuilder(); for (byte aByte : bytes) { for (int j = 7; j >= 0; --j) { sb.append(((aByte >> j) & 0x01) == 0 ? '0' : '1'); } } return sb.toString(); } /** bits转bytes * @param bits 转换的bits * @return 转换后的bytes */ public static byte[] bits2Bytes(String bits) { int lenMod = bits.length() % 8; int byteLen = bits.length() / 8; // add "0" until length to 8 times if (lenMod != 0) { for (int i = lenMod; i < 8; i++) { bits = "0" + bits; } byteLen++; } byte[] bytes = new byte[byteLen]; for (int i = 0; i < byteLen; ++i) { for (int j = 0; j < 8; ++j) { bytes[i] <<= 1; bytes[i] |= bits.charAt(i * 8 + j) - '0'; } } return bytes; } /** 将字节数组转换成char数据 * @param bytes 转换的字节数组 * @return 转换后的char数据 */ public static char[] bytes2Chars(final byte[] bytes) { if (bytes == null) return null; int len = bytes.length; if (len <= 0) return null; char[] chars = new char[len]; for (int i = 0; i < len; i++) { chars[i] = (char) (bytes[i] & 0xff); } return chars; } /** 将char数组转换成字节数组 * @param chars 转换的char数据 * @return 转换后的字节数组 */ public static byte[] chars2Bytes(final char[] chars) { if (chars == null || chars.length <= 0) return null; int len = chars.length; byte[] bytes = new byte[len]; for (int i = 0; i < len; i++) { bytes[i] = (byte) (chars[i]); } return bytes; } /** 将字节数组转换成String * @param bytes 转换的字节数组 * @return 转换后的String */ public static String bytes2HexString(final byte[] bytes) { if (bytes == null) return null; int len = bytes.length; if (len <= 0) return null; char[] ret = new char[len << 1]; for (int i = 0, j = 0; i < len; i++) { ret[j++] = hexDigits[bytes[i] >>> 4 & 0x0f]; ret[j++] = hexDigits[bytes[i] & 0x0f]; } return new String(ret); } /** 将字符串转换成字节数组 * @param hexString 转换的字符串 * @return 转换后的字节数组 */ public static byte[] hexString2Bytes(String hexString) { if (isSpace(hexString)) return null; int len = hexString.length(); if (len % 2 != 0) { hexString = "0" + hexString; len = len + 1; } char[] hexBytes = hexString.toUpperCase().toCharArray(); byte[] ret = new byte[len >> 1]; for (int i = 0; i < len; i += 2) { ret[i >> 1] = (byte) (hex2Int(hexBytes[i]) << 4 | hex2Int(hexBytes[i + 1])); } return ret; } /** 将char转换成int * @param hexChar 转换的char * @return */ private static int hex2Int(final char hexChar) { if (hexChar >= '0' && hexChar <= '9') { return hexChar - '0'; } else if (hexChar >= 'A' && hexChar <= 'F') { return hexChar - 'A' + 10; } else { throw new IllegalArgumentException(); } } /** 字节数转合适内存大小 * @param byteSize 转换的字节 * @return 内存大小 */ @SuppressLint("DefaultLocale") public static String byte2FitMemorySize(final long byteSize) { if (byteSize < 0) { return "shouldn't be less than zero!"; } else if (byteSize < KB) { return String.format("%.3fB", (double) byteSize); } else if (byteSize < MB) { return String.format("%.3fKB", (double) byteSize / KB); } else if (byteSize < GB) { return String.format("%.3fMB", (double) byteSize / MB); } else { return String.format("%.3fGB", (double) byteSize / GB); } } /** 将OutputStream转换成ByteArrayInputStream * @param out 转换的OutputStream * @return 转换后的ByteArrayInputStream */ public ByteArrayInputStream output2InputStream(final OutputStream out) { if (out == null) return null; return new ByteArrayInputStream(((ByteArrayOutputStream) out).toByteArray()); } /** 将InputStream对象转换成字节数组 * @param is 转换的InputStream对象 * @return 转换后的字节数组 */ public static byte[] inputStream2Bytes(final InputStream is) { if (is == null) return null; return input2OutputStream(is).toByteArray(); } /** 将InputStream对象转换成为ByteArrayOutputStream * @param is 转换的InputStream * @return 转换后的ByteArrayOutputStream */ public static ByteArrayOutputStream input2OutputStream(final InputStream is) { if (is == null) return null; try { ByteArrayOutputStream os = new ByteArrayOutputStream(); byte[] b = new byte[KB]; int len; while ((len = is.read(b, 0, KB)) != -1) { os.write(b, 0, len); } return os; } catch (IOException e) { e.printStackTrace(); return null; } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } /** 将字节数组转换成InputStream对象 * @param bytes 转换的字节数组 * @return 转换后的InputStream对象 */ public static InputStream bytes2InputStream(final byte[] bytes) { if (bytes == null || bytes.length <= 0) return null; return new ByteArrayInputStream(bytes); } /** 将OutputStream转换成字节数组 * @param out 转换的OutputStream对象 * @return 转换后的字节数组 */ public static byte[] outputStream2Bytes(final OutputStream out) { if (out == null) return null; return ((ByteArrayOutputStream) out).toByteArray(); } /** 将字节数组转换成Stream对象 * @param bytes 转换的字节数组 * @return 转换后的OutputStream对象 */ public static OutputStream bytes2OutputStream(final byte[] bytes) { if (bytes == null || bytes.length <= 0) return null; ByteArrayOutputStream os = null; try { os = new ByteArrayOutputStream(); os.write(bytes); return os; } catch (IOException e) { e.printStackTrace(); return null; } finally { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } /** 将InputStream转换成String * @param is 转换的InputStream对象 * @param charsetName 转换编码格式(如:utf-8) * @return 转换后的String对象 */ public static String inputStream2String(final InputStream is, final String charsetName) { if (is == null || isSpace(charsetName)) return null; try { return new String(inputStream2Bytes(is), charsetName); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } } /** 将String对象转换成InputStream * @param string 转换的String对象 * @param charsetName 转换编码格式 * @return 转换后的InputStream对象 */ public static InputStream string2InputStream(final String string, final String charsetName) { if (string == null || isSpace(charsetName)) return null; try { return new ByteArrayInputStream(string.getBytes(charsetName)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } } /** 将OutputStream对象转换成String对象 * @param out 转换的OutputStream对象 * @param charsetName 转换编码格式 * @return 转换后的String对象 */ public static String outputStream2String(final OutputStream out, final String charsetName) { if (out == null || isSpace(charsetName)) return null; try { return new String(outputStream2Bytes(out), charsetName); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } } /** 将String转换成OutputStream * @param string 转换的String对象 * @param charsetName 转换的编码格式 * @return 转换后的OutputStream对象 */ public static OutputStream string2OutputStream(final String string, final String charsetName) { if (string == null || isSpace(charsetName)) return null; try { return bytes2OutputStream(string.getBytes(charsetName)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } } /** 将bitmap转换成字节数组 * @param bitmap 转换的bitmap对象 * @param format 转换后的字节数组 * @return */ public static byte[] bitmap2Bytes(final Bitmap bitmap, final Bitmap.CompressFormat format) { if (bitmap == null) return null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(format, 100, baos); return baos.toByteArray(); } /** 将字节数组转换成Bitmap * @param bytes 转换的字节数组 * @return 转换后的bitmap */ public static Bitmap bytes2Bitmap(final byte[] bytes) { return (bytes == null || bytes.length == 0) ? null : BitmapFactory.decodeByteArray(bytes, 0, bytes.length); } /** * 图片转字符串 * @param bitmap 图片 * @param quantity 0-100 100表示不压缩 * @return */ public static String bitmap2StringByBase64(Bitmap bitmap, int quantity) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, quantity, bos);//参数100表示不压缩 byte[] bytes = bos.toByteArray(); return Base64.encodeToString(bytes, Base64.DEFAULT); } /** 将drawable转换成Bitmap对象 * @param drawable 转换的drawable * @return 转换后的bitmap */ public static Bitmap drawable2Bitmap(final Drawable drawable) { if (drawable instanceof BitmapDrawable) { BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable; if (bitmapDrawable.getBitmap() != null) { return bitmapDrawable.getBitmap(); } } Bitmap bitmap; if (drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) { bitmap = Bitmap.createBitmap(1, 1, drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565); } else { bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565); } Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; } /** 将Bitmap转换Drawable对象 * @param bitmap 转换的Bitmap * @return 转换后的Drawable */ public static Drawable bitmap2Drawable(final Bitmap bitmap) { return bitmap == null ? null : new BitmapDrawable(Utils.getApp().getResources(), bitmap); } /** 将Drawable对象转换成字节数组 * @param drawable 转换的drawable对象 * @param format 转换的格式 * @return 转换后的字节数组 */ public static byte[] drawable2Bytes(final Drawable drawable, final Bitmap.CompressFormat format) { return drawable == null ? null : bitmap2Bytes(drawable2Bitmap(drawable), format); } /** 字节数组转换Drawable对象 * @param bytes 字节数组 * @return Drawable对象 */ public static Drawable bytes2Drawable(final byte[] bytes) { return bytes == null ? null : bitmap2Drawable(bytes2Bitmap(bytes)); } /** 将View转换为Bitmap * @param view 转换的View对象 * @return Bitmap对象 */ public static Bitmap view2Bitmap(final View view) { if (view == null) return null; Bitmap ret = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(ret); Drawable bgDrawable = view.getBackground(); if (bgDrawable != null) { bgDrawable.draw(canvas); } else { canvas.drawColor(Color.WHITE); } view.draw(canvas); return ret; } /** dp转px * @param dpValue 转换的dp值 * @return 转换后的px值 */ public static int dp2px(final float dpValue) { final float scale = Utils.getApp().getResources().getDisplayMetrics().density; return (int) (dpValue * scale + 0.5f); } /** px转dp * @param pxValue 转换的px值 * @return 转换后的dp值 */ public static int px2dp(final float pxValue) { final float scale = Utils.getApp().getResources().getDisplayMetrics().density; return (int) (pxValue / scale + 0.5f); } /** sp转px * @param spValue 转换的sp值 * @return 转换后的px值 */ public static int sp2px(final float spValue) { final float fontScale = Utils.getApp().getResources().getDisplayMetrics().scaledDensity; return (int) (spValue * fontScale + 0.5f); } /** px转sp * @param pxValue 转换的px值 * @return 转换后的sp值 */ public static int px2sp(final float pxValue) { final float fontScale = Utils.getApp().getResources().getDisplayMetrics().scaledDensity; return (int) (pxValue / fontScale + 0.5f); } /**判断是否为空 * @param s 判断的对象 * @return true==yes */ private static boolean isSpace(final String s) { if (s == null) return true; for (int i = 0, len = s.length(); i < len; ++i) { if (!Character.isWhitespace(s.charAt(i))) { return false; } } return true; } }
package com.zantong.mobilecttx.base.interf; /** * Created by jianghw on 2017/4/26. */ public interface IMvpPresenter { void onSubscribe(); void unSubscribe(); }
/* * Created by Angel Leon (@gubatron), Alden Torres (aldenml) * Copyright (c) 2011-2014,, FrostWire(R). All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.limegroup.gnutella.gui.options.panes; import javax.swing.JCheckBox; import org.limewire.i18n.I18nMarker; import com.limegroup.gnutella.gui.I18n; import com.limegroup.gnutella.gui.LabeledComponent; import com.limegroup.gnutella.settings.ApplicationSettings; /** * @author gubatron * @author aldenml * */ public final class UXStatsPaneItem extends AbstractPaneItem { public final static String TITLE = I18n.tr("Anonymous Usage Statistics"); public final static String LABEL = I18n.tr("Send anonymous usage statistics so that FrostWire can be improved more effectively. No information regarding content searched, shared or played nor any information that can personally identify you will be stored on disk or sent through the network."); public final static String CHECK_BOX_LABEL = I18nMarker.marktr("Send anonymous usage statistics"); private final JCheckBox CHECK_BOX = new JCheckBox(); public UXStatsPaneItem() { super(TITLE, LABEL); LabeledComponent comp = new LabeledComponent(CHECK_BOX_LABEL, CHECK_BOX, LabeledComponent.LEFT_GLUE, LabeledComponent.LEFT); add(comp.getComponent()); } public void initOptions() { CHECK_BOX.setSelected(ApplicationSettings.UX_STATS_ENABLED.getValue()); } public boolean applyOptions() { ApplicationSettings.UX_STATS_ENABLED.setValue(CHECK_BOX.isSelected()); return true; } public boolean isDirty() { return ApplicationSettings.UX_STATS_ENABLED.getValue() != CHECK_BOX.isSelected(); } }
package org.isj.gestionenseignant2.services; import org.isj.gestionenseignant2.repository.Enseignant; import org.isj.gestionenseignant2.repository.EnseignantRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class ServiceImpl implements IService { //injection de l'interface repository @Autowired private EnseignantRepository enseignantRepository; @Override public Enseignant enregistrerEnseignantService(Enseignant enseignant) { return enseignantRepository.save(enseignant); } @Override public List<Enseignant> listEnseignantService() { return enseignantRepository.findAll(); } @Override public List<Enseignant> listEnseignantRecherche(String nom) { return enseignantRepository.findAllByNomLike(nom); } }
package com.sxb.controller; import java.util.Date; import javax.annotation.Resource; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.context.annotation.Scope; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.sxb.model.Comment; import com.sxb.model.RespsonData; import com.sxb.service.CommentService; /** * @description 评论点赞RestController * @author <a href="mailto:ou8zz@sina.com">OLE</a> * @date 2016/06/14 * @version 1.0 */ @RestController @RequestMapping("/comment") @Scope(value="request") public class CommentController { private Log log = LogFactory.getLog(CommentController.class); @Resource(name="commentService") private CommentService commentService; /** * 创建评论addComment http://localhost/sxb/comment/comment_create * @param Comment 评论对象 * 请求示例: {"userphone":"1555223554", "article_uuid":"auid100", "content":"neirong"} * @return RespsonData 成功1或者0失败 */ @RequestMapping(method=RequestMethod.POST, value="/comment_create") public Object addComment(@RequestBody Comment c) { RespsonData rd = new RespsonData("comment_create"); try { c.setCreate_time(new Date()); Object i = commentService.addComment(c); rd.setData(i); } catch (Exception e) { rd.setErrorCode(560); rd.setErrorInfo(e.getMessage()); log.error("addComment error", e); } return rd; } /** * 获取评论或者评论列表getComment http://localhost/sxb/comment/comment_listget * @param Comment 评论对象 * 请求示例:{"article_uuid":100, "userphone":"15966636322", "limit":10, "offset":0} * @return RespsonData 封装MAP返回对象 */ @RequestMapping(method=RequestMethod.POST, value="/comment_listget") public Object getComment(@RequestBody Comment c) { RespsonData rd = new RespsonData("comment_listget"); try { Object m = commentService.getComment(c); rd.setData(m); return rd; } catch (Exception e) { rd.setErrorCode(560); rd.setErrorInfo(e.getMessage()); log.error("getComment error", e); } return rd; } /** * 设置用户点赞,如果该用户已经点赞 http://localhost/sxb/comment/comment_favor_set * @param c 用户信息 * 请求示例: {"userphone":"18625155246", "comment_uuid":15500, "favor":true} * @return RespsonData 返回点赞设置成功或者已经点过赞 */ @RequestMapping(method=RequestMethod.POST, value="/comment_favor_set") public Object setFavor(@RequestBody Comment c) { RespsonData rd = new RespsonData("comment_favor_set"); try { Object m = commentService.setFavor(c); rd.setData(m); } catch (Exception e) { rd.setErrorCode(560); rd.setErrorInfo(e.getMessage()); log.error("setFavor error", e); } return rd; } /** * 收集用户提交的反馈 http://localhost/sxb/comment/feedback * @param c 用户提交的信息 * 请求示例: {"userphone":"18625155246", "content":"这个APP还有XXX需要改进的地方"} * @return RespsonData */ @RequestMapping(method=RequestMethod.POST, value="/feedback") public Object feedback(@RequestBody Comment c) { RespsonData rd = new RespsonData("feedback"); try { Object m = commentService.feedback(c); rd.setData(m); } catch (Exception e) { rd.setErrorCode(560); rd.setErrorInfo(e.getMessage()); log.error("feedback error", e); } return rd; } }
package com.xld.common.redis; import com.xld.common.other.LogUtil; import com.xld.common.other.StrUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import java.util.List; import java.util.concurrent.TimeUnit; /** * Redis操作工具类 * * @author xld */ @Component public class RedisUtil { @Autowired @Qualifier("protoStuffTemplate") private RedisTemplate protoStuffTemplate; /** * 设置过期时间,单位秒 * * @param key 键的名称 * @param timeout 过期时间 * @return 成功:true,失败:false */ public boolean setExpireTime(String key, long timeout) { return protoStuffTemplate.expire(key, timeout, TimeUnit.SECONDS); } /** * 通过键删除一个值 * * @param key 键的名称 */ public void delete(String key) { protoStuffTemplate.delete(key); } /** * 判断key是否存在 * * @param key 键的名称 * @return 存在:true,不存在:false */ public boolean hasKey(String key) { return protoStuffTemplate.hasKey(key); } /** * 数据存储 * * @param key 键 * @param value 值 */ public void set(String key, Object value) { protoStuffTemplate.boundValueOps(key).set(value); } /** * 数据存储的同时设置过期时间 * * @param key 键 * @param value 值 * @param expireTime 过期时间 */ public void set(String key, Object value, Long expireTime) { protoStuffTemplate.boundValueOps(key).set(value, expireTime, TimeUnit.SECONDS); } /** * 数据取值 * * @param key 键 * @return 查询成功:值,查询失败,null */ public Object get(String key) { return protoStuffTemplate.boundValueOps(key).get(); } /** * 新增list并设置失效时间 * @param redisKey redis键,不能为空 * @param value 值 * @param time 时间(秒) time>0 * @return 操作成功:返回true,操作失败:返回false(redisKey为空或time<=0:返回false) */ public boolean addList(String redisKey, Object value, long time) { if (!StrUtil.isNotEmpty(redisKey) || time <= 0) { return false; } try { protoStuffTemplate.opsForList().rightPush(redisKey, value); return setExpire(redisKey, time); } catch (Exception e) { LogUtil.printErrorLog(e); } return false; } /** * 设置redisKey失效时间 * @param redisKey redis键,不能为空 * @param time 时间(秒) time>0 * @return 操作成功:返回true,操作失败:返回false(redisKey为空或time<=0:返回false) */ public boolean setExpire(String redisKey, long time) { if (!StrUtil.isNotEmpty(redisKey) || time <= 0) { return false; } try { protoStuffTemplate.expire(redisKey, time, TimeUnit.SECONDS); return true; } catch (Exception e) { LogUtil.printErrorLog(e); } return false; } /** * 获取list * @param redisKey redis键,不能为空 * @return 查询成功:返回list,查询失败:返回null(redisKey为空则返回null) */ public List<Object> getList(String redisKey){ if (!StrUtil.isNotEmpty(redisKey)) { return null; } try { return protoStuffTemplate.opsForList().range(redisKey, 0, getListSize(redisKey)); } catch (Exception e) { LogUtil.printErrorLog(e); } return null; } /** * 获取list长度大小 * @param redisKey redis键,不能为空 * @return 查询成功:返回list长度大小,查询失败:返回0(redisKey为空则返回0) */ public long getListSize(String redisKey){ if (!StrUtil.isNotEmpty(redisKey)) { return 0; } try { return protoStuffTemplate.opsForList().size(redisKey); } catch (Exception e) { LogUtil.printErrorLog(e); } return 0; } }
package br.com.cleitonkiper.hiperion.interfaces; import java.io.FileNotFoundException; import java.io.InputStream; public interface Builder<T> { T build() throws Exception ; T build(InputStream template) throws Exception ; // withTemplate(InputStream template); }
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.test.web.reactive.server; import java.time.Duration; import java.util.Objects; import java.util.function.Consumer; import org.hamcrest.Matcher; import org.hamcrest.MatcherAssert; import org.springframework.http.ResponseCookie; import org.springframework.test.util.AssertionErrors; import static org.hamcrest.MatcherAssert.assertThat; /** * Assertions on cookies of the response. * * @author Rossen Stoyanchev * @since 5.3 */ public class CookieAssertions { private final ExchangeResult exchangeResult; private final WebTestClient.ResponseSpec responseSpec; public CookieAssertions(ExchangeResult exchangeResult, WebTestClient.ResponseSpec responseSpec) { this.exchangeResult = exchangeResult; this.responseSpec = responseSpec; } /** * Expect a header with the given name to match the specified values. */ public WebTestClient.ResponseSpec valueEquals(String name, String value) { this.exchangeResult.assertWithDiagnostics(() -> { String message = getMessage(name); AssertionErrors.assertEquals(message, value, getCookie(name).getValue()); }); return this.responseSpec; } /** * Assert the first value of the response cookie with a Hamcrest {@link Matcher}. */ public WebTestClient.ResponseSpec value(String name, Matcher<? super String> matcher) { String value = getCookie(name).getValue(); this.exchangeResult.assertWithDiagnostics(() -> { String message = getMessage(name); MatcherAssert.assertThat(message, value, matcher); }); return this.responseSpec; } /** * Consume the value of the response cookie. */ public WebTestClient.ResponseSpec value(String name, Consumer<String> consumer) { String value = getCookie(name).getValue(); this.exchangeResult.assertWithDiagnostics(() -> consumer.accept(value)); return this.responseSpec; } /** * Expect that the cookie with the given name is present. */ public WebTestClient.ResponseSpec exists(String name) { getCookie(name); return this.responseSpec; } /** * Expect that the cookie with the given name is not present. */ public WebTestClient.ResponseSpec doesNotExist(String name) { ResponseCookie cookie = this.exchangeResult.getResponseCookies().getFirst(name); if (cookie != null) { String message = getMessage(name) + " exists with value=[" + cookie.getValue() + "]"; this.exchangeResult.assertWithDiagnostics(() -> AssertionErrors.fail(message)); } return this.responseSpec; } /** * Assert a cookie's maxAge attribute. */ public WebTestClient.ResponseSpec maxAge(String name, Duration expected) { Duration maxAge = getCookie(name).getMaxAge(); this.exchangeResult.assertWithDiagnostics(() -> { String message = getMessage(name) + " maxAge"; AssertionErrors.assertEquals(message, expected, maxAge); }); return this.responseSpec; } /** * Assert a cookie's maxAge attribute with a Hamcrest {@link Matcher}. */ public WebTestClient.ResponseSpec maxAge(String name, Matcher<? super Long> matcher) { long maxAge = getCookie(name).getMaxAge().getSeconds(); this.exchangeResult.assertWithDiagnostics(() -> { String message = getMessage(name) + " maxAge"; assertThat(message, maxAge, matcher); }); return this.responseSpec; } /** * Assert a cookie's path attribute. */ public WebTestClient.ResponseSpec path(String name, String expected) { String path = getCookie(name).getPath(); this.exchangeResult.assertWithDiagnostics(() -> { String message = getMessage(name) + " path"; AssertionErrors.assertEquals(message, expected, path); }); return this.responseSpec; } /** * Assert a cookie's path attribute with a Hamcrest {@link Matcher}. */ public WebTestClient.ResponseSpec path(String name, Matcher<? super String> matcher) { String path = getCookie(name).getPath(); this.exchangeResult.assertWithDiagnostics(() -> { String message = getMessage(name) + " path"; assertThat(message, path, matcher); }); return this.responseSpec; } /** * Assert a cookie's domain attribute. */ public WebTestClient.ResponseSpec domain(String name, String expected) { String path = getCookie(name).getDomain(); this.exchangeResult.assertWithDiagnostics(() -> { String message = getMessage(name) + " domain"; AssertionErrors.assertEquals(message, expected, path); }); return this.responseSpec; } /** * Assert a cookie's domain attribute with a Hamcrest {@link Matcher}. */ public WebTestClient.ResponseSpec domain(String name, Matcher<? super String> matcher) { String domain = getCookie(name).getDomain(); this.exchangeResult.assertWithDiagnostics(() -> { String message = getMessage(name) + " domain"; assertThat(message, domain, matcher); }); return this.responseSpec; } /** * Assert a cookie's secure attribute. */ public WebTestClient.ResponseSpec secure(String name, boolean expected) { boolean isSecure = getCookie(name).isSecure(); this.exchangeResult.assertWithDiagnostics(() -> { String message = getMessage(name) + " secure"; AssertionErrors.assertEquals(message, expected, isSecure); }); return this.responseSpec; } /** * Assert a cookie's httpOnly attribute. */ public WebTestClient.ResponseSpec httpOnly(String name, boolean expected) { boolean isHttpOnly = getCookie(name).isHttpOnly(); this.exchangeResult.assertWithDiagnostics(() -> { String message = getMessage(name) + " httpOnly"; AssertionErrors.assertEquals(message, expected, isHttpOnly); }); return this.responseSpec; } /** * Assert a cookie's sameSite attribute. */ public WebTestClient.ResponseSpec sameSite(String name, String expected) { String sameSite = getCookie(name).getSameSite(); this.exchangeResult.assertWithDiagnostics(() -> { String message = getMessage(name) + " sameSite"; AssertionErrors.assertEquals(message, expected, sameSite); }); return this.responseSpec; } private ResponseCookie getCookie(String name) { ResponseCookie cookie = this.exchangeResult.getResponseCookies().getFirst(name); if (cookie == null) { this.exchangeResult.assertWithDiagnostics(() -> AssertionErrors.fail("No cookie with name '" + name + "'")); } return Objects.requireNonNull(cookie); } private String getMessage(String cookie) { return "Response cookie '" + cookie + "'"; } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.ut.healthelink.dao.impl; import com.ut.healthelink.dao.newsArticleDAO; import com.ut.healthelink.model.newsArticle; import java.util.List; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.SessionFactory; import org.hibernate.criterion.Order; import org.hibernate.criterion.Restrictions; import org.hibernate.exception.SQLGrammarException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; /** * * @author chadmccue */ @Repository public class newsArticleDAOImpl implements newsArticleDAO { @Autowired private SessionFactory sessionFactory; /** * The 'createNewsArticle' function will create a new news article * * @Table newsarticles * * @param article Will hold the news article object from the form * * @return The function will not return anything */ @Override public void createNewsArticle(newsArticle article) throws Exception { sessionFactory.getCurrentSession().save(article); } /** * The 'updateNewsArticle' function will update a passed in news article * * @Table newsarticles * * @param article Will hold the news article object from the form * * @return The function will not return anything */ @Override public void updateNewsArticle(newsArticle article) throws Exception { sessionFactory.getCurrentSession().update(article); } /** * The 'deleteNewsArticle' function will delete the selected news article * * @Table newsarticles * * @param id Will hold the id of the news article to remove * * @return The function will not return anything */ @Override @Transactional public void deleteNewsArticle(int id) throws Exception { //delete provider addresses try { Query deleteProviderAddresses = sessionFactory.getCurrentSession().createQuery("delete from newsarticles where id = :id)"); deleteProviderAddresses.setParameter("id", id); deleteProviderAddresses.executeUpdate(); } catch(SQLGrammarException ex){ throw ex; }; } /** * The 'listAllNewsArticles' function will return all the news articles in the system * * @Table newsarticles * * @return The function will return the news articles */ @Override @Transactional public List<newsArticle> listAllNewsArticles() throws Exception { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(newsArticle.class); return criteria.list(); } /** * The 'listAllActiveNewsArticles' function will return all the active news articles in the system * * @Table newsarticles * * @return The function will return the news articles */ @Override @Transactional public List<newsArticle> listAllActiveNewsArticles() throws Exception { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(newsArticle.class); criteria.add(Restrictions.eq("status", true)); return criteria.list(); } /** * The 'getNewsArticleById' function will return a news article based on the passed Id * * @Table newsarticles * * @param id Will hold the id of the selected news article * * @return The function will return the news article */ @Override @Transactional public newsArticle getNewsArticleById(int id) throws Exception { return (newsArticle) sessionFactory.getCurrentSession().get(newsArticle.class, id); } /** * The 'getNewsArticleByTitle' function will return a news article based on the title passed in. If mutliple * records are found it will return the first. * * @param articleTitle Wil hold the title of the article to be searched. * @return This function will return an newsArticle Object. * @throws Exception */ @Override @Transactional public List<newsArticle> getNewsArticleByTitle(String articleTitle) throws Exception { Criteria criteria = sessionFactory.getCurrentSession().createCriteria(newsArticle.class); criteria.add(Restrictions.eq("status", true)); criteria.add(Restrictions.eq("title", articleTitle)); criteria.addOrder(Order.desc("dateCreated")); return criteria.list(); } }
package com.flyusoft.apps.jointoil.service.impl; import java.util.Calendar; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.flyusoft.apps.jointoil.dao.MonitorDataDao; import com.flyusoft.apps.jointoil.entity.MonitorData; import com.flyusoft.apps.jointoil.service.MonitorDataService; import com.flyusoft.common.orm.Page; import com.flyusoft.common.orm.PropertyFilter; import com.google.common.collect.Lists; @Service @Transactional public class MonitorDataServiceImpl implements MonitorDataService { @Autowired private MonitorDataDao monitorDataDao; @Override public void saveMonitorData(MonitorData monitorData) { monitorDataDao.save(monitorData); } /** * 使用属性过滤条件查询用户. */ @Override @Transactional(readOnly = true) public Page<MonitorData> searchMonitorData(final Page<MonitorData> page, final List<PropertyFilter> filters) { return monitorDataDao.findPage(page, filters); } /** * 查询最近时间的监测数据. */ @Override @Transactional(readOnly = true) public MonitorData searchMonitorDataByLastMonitorTime(String wellNo) { return monitorDataDao.searchMonitorDataByLastMonitorTime(wellNo); } @Override @Transactional(readOnly = true) public Page<MonitorData> getMonitorDataMsg(Page<MonitorData> pageMonitor, String wellNo, Date start_date, Date end_date) { return monitorDataDao.getMonitorDataMsg(pageMonitor, wellNo, start_date, end_date); } @Override @Transactional(readOnly = true) public MonitorData getMonitorDataMsg(String id) { return monitorDataDao.get(id); } /** * 通过时间间隔和井号查询MonitorData */ @Override @Transactional(readOnly = true) public List<MonitorData> getMonitorDataByWellIdAndTimeInterval( String wellNo, int timeInterval) { Calendar nowDate = Calendar.getInstance();// 取得现在时间 Date endDate = nowDate.getTime();// 转成Date nowDate.add(Calendar.MINUTE, -(timeInterval)); Date startDate = nowDate.getTime(); return monitorDataDao.searchMonitorDataByWellIdAndTimeInterval(wellNo, startDate, endDate); } @Override @Transactional(readOnly = true) public MonitorData getMonitorDataClassReport(String wellNo, String reporttime, String time) { //查询一段时间内的信息 List<MonitorData> list = monitorDataDao.getMonitorDataClassReport( wellNo, reporttime, time); MonitorData mon = new MonitorData(); //取出第一个信息 if (list.size() > 0) { mon = list.get(0); }else{ mon.setTemperature(0.0); mon.setPressure(0.00); mon.setInstantaneousFlow(0.00); mon.setAccumulativeFlow(0.00); } return mon; } @Override @Transactional(readOnly = true) public List<MonitorData> searchAllWellLastTimeMonitorData(int _wellNum) { return monitorDataDao.getAllWellLastTimeMonitorData(_wellNum); } @Override public MonitorData getLastTimeMonitorData(String _wellNo, List<MonitorData> _list) { MonitorData md=null; for (MonitorData monitorData : _list) { if(monitorData.getWellNo().equalsIgnoreCase(_wellNo)){ md=monitorData; break; } } return md; } @Override @Transactional(readOnly = true) public List<MonitorData> getAllWellMonitorDataByTimeInterval( int _timeInterval) { Calendar nowDate = Calendar.getInstance();// 取得现在时间 Date endDate = nowDate.getTime();// 转成Date nowDate.add(Calendar.MINUTE, -(_timeInterval)); Date startDate = nowDate.getTime(); return monitorDataDao.getAllWellMonitorDataByTimeInterval(startDate, endDate); } @Override public List<MonitorData> getAllWellMonitorDataByTimeInterval( String _wellNo, int _timeInterval, List<MonitorData> _list) { List<MonitorData> newList=Lists.newArrayList(); for (MonitorData md : _list) { if(md.getWellNo().equalsIgnoreCase(_wellNo)){ newList.add(md); } } return newList; } }
package io.flyingmongoose.brave.fragment; import android.app.Activity; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentActivity; import android.support.v4.view.ViewPager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.EditorInfo; import android.widget.SearchView; import android.widget.Toast; import com.parse.FindCallback; import com.parse.ParseException; import com.parse.ParseObject; import com.parse.ParseQuery; import java.util.List; import io.flyingmongoose.brave.adapter.VPAdaptGroups; import io.flyingmongoose.brave.activity.ActivHome; import io.flyingmongoose.brave.R; import io.flyingmongoose.brave.view.ViewSlidingTabLayout; public class FragManageGroups extends Fragment implements ViewPager.OnPageChangeListener, SearchView.OnQueryTextListener { private FragmentActivity activContext; private ViewPager vpGroupsContent; private ViewSlidingTabLayout stLayManageGroups; private VPAdaptGroups pagerAdapter; private int selectedPage = 0; CharSequence titles[] = {"Public", "Private", "New"}; int numberOfTabs = 3; public static SearchView svGroups; private List<ParseObject> publicSearchResults; private String cached3CharSearchString = null; public FragManageGroups() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_manage_groups, container, false); vpGroupsContent = (ViewPager) view.findViewById(R.id.vpGroupsContent); stLayManageGroups = (ViewSlidingTabLayout) view.findViewById(R.id.stLayManageGroups); svGroups = (SearchView) view.findViewById(R.id.svGroups); initGroupSlidingTab(); return view; } private void initGroupSlidingTab() { svGroups.setOnQueryTextListener(this); //Setup tabs pagerAdapter = new VPAdaptGroups(activContext.getSupportFragmentManager(), titles, numberOfTabs); vpGroupsContent.setAdapter(pagerAdapter); stLayManageGroups.setDistributeEvenly(true); stLayManageGroups.setCustomTabColorizer(new ViewSlidingTabLayout.TabColorizer() { @Override public int getIndicatorColor(int position) { return getResources().getColor(R.color.White); } }); stLayManageGroups.setViewPager(vpGroupsContent); stLayManageGroups.setOnPageChangeListener(this); } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); ((ActivHome)getActivity()).lockDrawer(true); } /*public static void onRefresh() { String currentQuery = svGroups.getQuery().toString(); svGroups.setQuery(currentQuery, true); }*/ public void searchPublicGroup(String searchString) { //Clean up searchString searchString = searchString.trim().replaceAll("\\s+", "").trim().toLowerCase().toString(); Log.i("Searching public group", "cached: %" + cached3CharSearchString + "% searchString: %" + searchString + "%"); if(cached3CharSearchString == null || !cached3CharSearchString.equalsIgnoreCase(searchString)) //only searches for new results set online when doesnt match previous search or is first search { FragGroupsPublicOld.srLaySearchPublicGroups.setRefreshing(true); Log.i("Searching public group", "searching online db"); cached3CharSearchString = searchString; //set new cached search string final Toast msg = Toast.makeText(activContext, "", Toast.LENGTH_LONG); ParseQuery<ParseObject> querySearch = ParseQuery.getQuery("Groups"); querySearch.whereStartsWith("flatValue", searchString).addAscendingOrder("flatValue").whereEqualTo("public", true); FragGroupsPublicOld.loadingAnimate(); querySearch.findInBackground(new FindCallback<ParseObject>() { @Override public void done(List<ParseObject> parseObjects, ParseException e) { if (e == null) { publicSearchResults = parseObjects; if(publicSearchResults != null) FragGroupsPublicOld.populateResultList(activContext, publicSearchResults); FragGroupsPublicOld.srLaySearchPublicGroups.setRefreshing(false); } else { FragGroupsPublicOld.srLaySearchPublicGroups.setRefreshing(false); if (e.getCode() == 100) msg.setText(R.string.error_100_no_internet); //check internet conn else msg.setText("Unsuccessful while searching public groups: " + e.getMessage() + " code: " + e.getCode()); //display msg msg.show(); } } }); } else FragGroupsPublicOld.filterResultList(""); //resets data to have no filter } @Override public void onAttach(Activity activity) { activContext = (FragmentActivity) activity; super.onAttach(activity); } @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { switch (position) { case 0: svGroups.setQueryHint("Search group name"); svGroups.setQuery("", false); svGroups.setImeOptions(EditorInfo.IME_ACTION_DONE); selectedPage = 0; break; case 1: svGroups.setQueryHint("Private group name"); svGroups.setQuery("", false); svGroups.setImeOptions(EditorInfo.IME_ACTION_DONE); selectedPage = 1; break; case 2: svGroups.setQueryHint("New group name"); svGroups.setQuery("", false); svGroups.setImeOptions(EditorInfo.IME_ACTION_DONE); selectedPage = 2; break; default: break; } } @Override public void onPageScrollStateChanged(int state) { } @Override public boolean onQueryTextSubmit(String query) { svGroups.clearFocus(); return false; } @Override public boolean onQueryTextChange(String newText) { if(selectedPage == 0) { //Check for searching if (newText.length() == 3) { searchPublicGroup(newText); } else if (newText.length() > 3) { Log.i("Filtering groups", "filter word: %" + newText + "%"); FragGroupsPublicOld.filterResultList(newText); } else { //Reset filter FragGroupsPublicOld.filterResultList(""); } } return false; } @Override public void onPause() { super.onPause(); ((ActivHome)getActivity()).lockDrawer(false); } }
package Lesson3; import java.util.Random; import java.util.Scanner; public class Bingo { Scanner scanner = new Scanner(System.in); int unknownNumber; int range; int attempt; public static void main(String[] args) { Bingo bingo = new Bingo(); bingo.start(); } public void start() { System.out.println("Выберете максимальное число из диапазона:"); if (scanner.hasNextInt()) { range = scanner.nextInt(); unknownNumber = initGame(range); startGame(); } else { System.out.println("Введено не число. Выход!"); } } private int initGame(int range) { Random random = new Random(); return random.nextInt(range + 1); } private void startGame() { System.out.println("Введите загаданное число:"); while (scanner.hasNext()) { attempt++; if (scanner.hasNext("exit")) { exitGame(); break; } if (scanner.hasNextInt()) { int userNumber = scanner.nextInt(); if (unknownNumber == userNumber) { System.out.println("Bingo! Число " + userNumber + " угадано за " + attempt + " попыток!"); break; } if (range < userNumber) { System.out.println("Введенное число больше загаданного диапазона. Загаданное число в диапазоне от 0 до " + range + "!"); } else if (unknownNumber < userNumber) { System.out.println("Введенное число больше загаданного. Попробуйте еще раз:"); } else { System.out.println("Введенное число меньше загаданного. Попробуйте еще раз:"); } } } } private void exitGame() { System.out.println("Game over!"); scanner.close(); } }
package game.Blackjack; import java.util.ArrayList; import java.util.List; public class Test { public static void main(String[] args) { System.out.println("Test"); Table table = new Table(); table.setup(); table.round(2); } } /* //Freddy's Testing Table if (x == 5 && y == x && z == y && word.equals("ChickEn")) { System.out.println("Hello Freddy"); //TODO make test controls // int selection = Validate.inputInt("What do you want to test?"); // switch (selection) { // default: // System.out.println("Nice"); // break; // } // Test 2 System.out.println(Color.GREEN + "Setting Up" + Color.RESET); setup(); System.out.println(Color.GREEN + "Drawing 2" + Color.RESET); draw(2); System.out.println(Color.GREEN + "Starting test run" + Color.RESET); //added roundisnotover to test if stand/surrender is working while (roundIsNotOver()) { // Hit is working fine // getSelection(getActivePlayer()); turn.pass(actors); } } else { System.out.println("BEGONE"); System.exit(555); } */ /* Freddy's Plan of attack TODO Classes Actor Cards CasinoDealer Main Player Table Test Turn Validation TODO Methods TODO table methods create deck create players/dealer draw bet round turn end results TODO hit method, take another card. TODO stand method, Take no more cards, end your turn TODO doubleDown method, Increase the initial bet by 100% and take exactly one more card. Some games permit the player to increase the bet by amounts smaller than 100%. TODO split method, Create two hands from a starting hand where both cards are the same value. Each new hand gets another card so that the player has two starting hands. This requires an additional bet on the second hand. The two hands are played out independently, and the wager on each hand is won or lost independently. In the case of cards worth 10 points, some casinos only allow splitting when the cards are the same rank. !!Non-controlling players can opt to put up a second bet or not. If they do not, they only get paid or lose on one of the two post-split hands.!! TODO surrender method, Forfeit half the bet and end the hand immediately. TODO research/implement insurance (optional) If the dealer shows an ace, an "insurance" bet is allowed. Insurance is a side bet that the dealer has a blackjack. The dealer asks for insurance bets before the first player plays. Insurance bets of half the player's current bet are placed on the "insurance bar" above player's cards. If the dealer has a blackjack, insurance pays 2 to 1. In most casinos, the dealer looks at the down card and pays off or takes the insurance bet immediately. In other casinos, the payoff waits until the end of the play. In face-down games, if a player has more than one hand, they are allowed to look at all their hands before deciding. This is the only condition where a player can look at multiple hands. */
package net.datacrow.core; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.Properties; import java.util.UUID; import net.datacrow.util.Utilities; public class DataCrowProperties { private static final String _USERDIR = "user.home"; private static final String _CLIENTID = "user.clientid"; private static final File file = new File(System.getProperty("user.home"), "datacrow.properties"); private static Properties properties; public DataCrowProperties() { properties = new Properties(); if (file.exists()) { try { FileInputStream fis = new FileInputStream(file); properties.load(fis); fis.close(); } catch (Exception e) { e.printStackTrace(); // logger not yet available at this stage } } initClientID(); save(); } public File getFile() { return file; } public void save() { try { FileOutputStream fos = new FileOutputStream(file); properties.store(fos, "Data Crow system settings file. Better to leave it right here."); fos.close(); } catch (Exception e) { e.printStackTrace(); // logger not yet available at this stage } } public boolean exists() { return file.exists(); } private void initClientID() { String clientID = properties.getProperty(_CLIENTID); if (clientID == null || clientID.trim().equals("")) properties.setProperty(_CLIENTID, UUID.randomUUID().toString()); } public File getUserDir() { String userDir = (String) properties.get(_USERDIR); return Utilities.isEmpty(userDir) ? null : new File(userDir); } public void setUserDir(String userDir) { properties.setProperty(_USERDIR, userDir); save(); } public String getClientID() { return properties.getProperty(_CLIENTID); } }
package com.orderMaster.model; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.sql.DataSource; public class OrderMasterDAOB implements OrderMasterDAOInterfaceB{ // String driver = "oracle.jdbc.driver.OracleDriver"; // String url = "jdbc:oracle:thin:@localhost:1521:XE"; // String userid = "TEA101G2"; // String passwd = "TEA101G2"; private static DataSource ds = null; static { try { Context ctx = new InitialContext(); ds = (DataSource)ctx.lookup("java:comp/env/jdbc/TEA101G2"); } catch(NamingException e){ e.printStackTrace(); } } private static final String INSERT_STMT = "INSERT INTO ORDER_MASTER VALUES (ORDER_MASTER_ID_SEQ.NEXTVAL,?,?,?,?,?,?)"; private static final String SELECT_ALL_STMT = "SELECT * FROM ORDER_MASTER order by ORDER_MASTER_ID"; private static final String SELECT_ONE_STMT = "SELECT * FROM ORDER_MASTER where ORDER_MASTER_ID = ?"; private static final String DELETE = "DELETE FROM ORDER_MASTER where ORDER_MASTER_ID = ?"; private static final String UPDATE = "UPDATE ORDER_MASTER set MEMBER_ID=?,ORDER_CREATE_DATE=?,ORDER_AMOUNT=?,ORDER_STATUS=?,ORDER_STATUS_EMP=?,ORDER_STATUS_COMM=? where ORDER_MASTER_ID = ?"; // private static final String SELECT_ALL_BY_MEMBERID_STMT = // "SELECT * FROM ORDER_MASTER where MEMBER_ID = ? order by ORDER_MASTER_ID"; @Override public void insert(OrderMasterVO orderMasterVO) { Connection con = null; PreparedStatement ptmt = null; try { // Class.forName(driver); // con = DriverManager.getConnection(url, userid, passwd); con = ds.getConnection(); ptmt = con.prepareStatement(INSERT_STMT); ptmt.setString(1, orderMasterVO.getMemberId()); ptmt.setDate(2, orderMasterVO.getOrderCreateDate()); ptmt.setInt(3, orderMasterVO.getOrderAmount()); ptmt.setString(4, orderMasterVO.getOrderStatus()); ptmt.setString(5, ""); ptmt.setString(6, ""); ptmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); }finally { if (ptmt != null) { try { ptmt.close(); } catch (SQLException se) { se.printStackTrace(System.err); } } if (con != null) { try { con.close(); } catch (Exception e) { e.printStackTrace(System.err); } } } } @Override public void delete(String orderMasterId) { Connection con = null; PreparedStatement ptmt = null; try { // Class.forName(driver); // con = DriverManager.getConnection(url, userid, passwd); con = ds.getConnection(); ptmt = con.prepareStatement(DELETE); ptmt.setString(1, orderMasterId); ptmt.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); }finally { if (ptmt != null) { try { ptmt.close(); } catch (SQLException se) { se.printStackTrace(System.err); } } if (con != null) { try { con.close(); } catch (Exception e) { e.printStackTrace(System.err); } } } } @Override public void update(OrderMasterVO orderMasterVO) { Connection con = null; PreparedStatement ptmt = null; try { // Class.forName(driver); // con = DriverManager.getConnection(url, userid, passwd); con = ds.getConnection(); ptmt = con.prepareStatement(UPDATE); ptmt.setString(1, orderMasterVO.getMemberId()); ptmt.setDate(2, orderMasterVO.getOrderCreateDate()); ptmt.setInt(3, orderMasterVO.getOrderAmount()); ptmt.setString(4, orderMasterVO.getOrderStatus()); ptmt.setString(5, orderMasterVO.getOrderStatusEmp()); ptmt.setString(6, orderMasterVO.getOrderStatusComm()); ptmt.setString(7, orderMasterVO.getOrderMasterId()); ptmt.executeUpdate(); }catch (SQLException e) { e.printStackTrace(); }finally { if (ptmt != null) { try { ptmt.close(); } catch (SQLException se) { se.printStackTrace(System.err); } } if (con != null) { try { con.close(); } catch (Exception e) { e.printStackTrace(System.err); } } } } @Override public OrderMasterVO selectOne(String orderMasterId) { Connection con = null; PreparedStatement ptmt = null; ResultSet rs = null; OrderMasterVO orderMasterVO = new OrderMasterVO(); try { // Class.forName(driver); // con = DriverManager.getConnection(url, userid, passwd); con = ds.getConnection(); ptmt = con.prepareStatement(SELECT_ONE_STMT); ptmt.setString(1, orderMasterId); rs = ptmt.executeQuery(); while (rs.next()) { orderMasterVO.setOrderMasterId(rs.getString("ORDER_MASTER_ID")); orderMasterVO.setMemberId(rs.getString("MEMBER_ID")); orderMasterVO.setOrderCreateDate(rs.getDate("ORDER_CREATE_DATE")); orderMasterVO.setOrderAmount(rs.getInt("ORDER_AMOUNT")); orderMasterVO.setOrderStatus(rs.getString("ORDER_STATUS")); orderMasterVO.setOrderStatusEmp(rs.getString("ORDER_STATUS_EMP")); orderMasterVO.setOrderStatusComm(rs.getString("ORDER_STATUS_COMM")); } } catch (SQLException e) { e.printStackTrace(); }finally { if (rs != null) { try { rs.close(); } catch (SQLException se) { se.printStackTrace(System.err); } } if (ptmt != null) { try { ptmt.close(); } catch (Exception e) { e.printStackTrace(System.err); } }if (con != null) { try { con.close(); } catch (Exception e) { e.printStackTrace(System.err); } } } return orderMasterVO; } @Override public List<OrderMasterVO> selectAll() { Connection con = null; PreparedStatement ptmt = null; ResultSet rs = null; OrderMasterVO orderMasterVO = null; List<OrderMasterVO> list = new ArrayList<OrderMasterVO>();; try { // Class.forName(driver); // con = DriverManager.getConnection(url, userid, passwd); con = ds.getConnection(); ptmt = con.prepareStatement(SELECT_ALL_STMT); rs = ptmt.executeQuery(); while (rs.next()) { orderMasterVO = new OrderMasterVO(); orderMasterVO.setOrderMasterId(rs.getString("ORDER_MASTER_ID")); orderMasterVO.setMemberId(rs.getString("MEMBER_ID")); orderMasterVO.setOrderCreateDate(rs.getDate("ORDER_CREATE_DATE")); orderMasterVO.setOrderAmount(rs.getInt("ORDER_AMOUNT")); orderMasterVO.setOrderStatus(rs.getString("ORDER_STATUS")); orderMasterVO.setOrderStatusEmp(rs.getString("ORDER_STATUS_EMP")); orderMasterVO.setOrderStatusComm(rs.getString("ORDER_STATUS_COMM")); list.add(orderMasterVO); } } catch (SQLException e) { e.printStackTrace(); }finally { if (rs != null) { try { rs.close(); } catch (SQLException se) { se.printStackTrace(System.err); } } if (ptmt != null) { try { ptmt.close(); } catch (Exception e) { e.printStackTrace(System.err); } }if (con != null) { try { con.close(); } catch (Exception e) { e.printStackTrace(System.err); } } } return list; } // @Override // public List<OrderMasterVO> selectAllByMember(String memberId) { // Connection con = null; // PreparedStatement ptmt = null; // ResultSet rs = null; // // OrderMasterVO orderMasterVO = null; // List<OrderMasterVO> list = new ArrayList<OrderMasterVO>();; // // try { // Class.forName(driver); // con = DriverManager.getConnection(url, userid, passwd); // ptmt = con.prepareStatement(SELECT_ALL_BY_MEMBERID_STMT); // // ptmt.setString(1, memberId); // // rs = ptmt.executeQuery(); // while (rs.next()) { // orderMasterVO = new OrderMasterVO(); // orderMasterVO.setOrderMasterId(rs.getString("ORDER_MASTER_ID")); // orderMasterVO.setMemberId(rs.getString("MEMBER_ID")); // orderMasterVO.setOrderCreatDate(rs.getDate("ORDER_CREATE_DATE")); // orderMasterVO.setOrderAmount(rs.getInt("ORDER_AMOUNT")); // orderMasterVO.setOrderStatus(rs.getString("ORDER_STATUS")); // list.add(orderMasterVO); // } // // }catch (ClassNotFoundException e) { // e.printStackTrace(); // } catch (SQLException e) { // e.printStackTrace(); // }finally { // if (rs != null) { // try { // rs.close(); // } catch (SQLException se) { // se.printStackTrace(System.err); // } // } // if (ptmt != null) { // try { // ptmt.close(); // } catch (Exception e) { // e.printStackTrace(System.err); // } // }if (con != null) { // try { // con.close(); // } catch (Exception e) { // e.printStackTrace(System.err); // } // } // } // return list; // } }
package api.block; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.BlockBreakable; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.item.ItemMonsterPlacer; import net.minecraft.util.AxisAlignedBB; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class ModPortalBlock extends BlockBreakable { //going to use meta for rotation, first bit for 2 factor rotation, 0 for east west, 1 for north south private static int frameBlock; private static int portalHeight; private static int portalWidth; private boolean bBorderXPOS = false; private boolean bBorderXNEG = false; private boolean bBorderYPOS = false; private boolean bBorderYNEG = false; private boolean bBorderZPOS = false; private boolean bBorderZNEG = false; private Object tabToDisplayOn; private String texturePath = "mydimensionmod:"; public ModPortalBlock(int par1, String unlocalizedName) { super(par1, unlocalizedName, Material.portal, false); this.setTickRandomly(true); this.setHardness(-1.0F); this.setStepSound(soundGlassFootstep); this.setLightValue(0.75F); texturePath += unlocalizedName; } public void registerIcons(IconRegister iconRegister) { this.blockIcon = iconRegister.registerIcon(texturePath); } @Override public Block setCreativeTab(CreativeTabs par1CreativeTabs) { this.tabToDisplayOn = null; return this; } /** * Ticks the block if it's been scheduled */ public void updateTick(World par1World, int par2, int par3, int par4, Random par5Random) { super.updateTick(par1World, par2, par3, par4, par5Random); } /** * Returns a bounding box from the pool of bounding boxes (this means this * box can change after the pool has been cleared to be reused) */ public AxisAlignedBB getCollisionBoundingBoxFromPool(World par1World, int par2, int par3, int par4) { return null; } /** * Updates the blocks bounds based on its current state. Args: world, x, y, * z */ public void setBlockBoundsBasedOnState(IBlockAccess par1IBlockAccess, int par2, int par3, int par4) { float f; float f1; int meta = par1IBlockAccess.getBlockMetadata(par2, par3, par4); /*if (par1IBlockAccess.getBlockId(par2 - 1, par3, par4) != this.blockID && par1IBlockAccess.getBlockId(par2 + 1, par3, par4) != this.blockID) {*/ if (meta == 1) { f = 0.125F; f1 = 0.5F; this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f1, 0.5F + f, 1.0F, 0.5F + f1); } else { f = 0.5F; f1 = 0.125F; this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f1, 0.5F + f, 1.0F, 0.5F + f1); } } /** * Is this block (a) opaque and (B) a full 1m cube? This determines whether * or not to render the shared face of two adjacent blocks and also whether * the player can attach torches, redstone wire, etc to this block. */ public boolean isOpaqueCube() { return false; } /** * If this block doesn't render as an ordinary block it will return False * (examples: signs, buttons, stairs, etc) */ @Override public boolean renderAsNormalBlock() { return false; } /** * Checks to see if this location is valid to create a portal and will * return True if it does. Args: world, x, y, z */ public boolean tryToCreatePortal(World par1World, int par2, int par3, int par4) { byte b0 = 0; byte b1 = 0; if (par1World.getBlockId(par2 - 1, par3, par4) == frameBlock || par1World.getBlockId(par2 + 1, par3, par4) == frameBlock) { b0 = 1; } if (par1World.getBlockId(par2, par3, par4 - 1) == frameBlock || par1World.getBlockId(par2, par3, par4 + 1) == frameBlock) { b1 = 1; } if (b0 == b1) { return false; } else { if (par1World.isAirBlock(par2 - b0, par3, par4 - b1)) { par2 -= b0; par4 -= b1; } int l; int i1; for (l = -1; l <= 2; ++l) { for (i1 = -1; i1 <= 3; ++i1) { boolean flag = l == -1 || l == 2 || i1 == -1 || i1 == 3; if (l != -1 && l != 2 || i1 != -1 && i1 != 3) { int j1 = par1World.getBlockId(par2 + b0 * l, par3 + i1, par4 + b1 * l); boolean isAirBlock = par1World.isAirBlock(par2 + b0 * l, par3 + i1, par4 + b1 * l); if (flag) { if (j1 != frameBlock) { return false; } } else if (!isAirBlock && (j1 != Block.fire.blockID)) { return false; } } } } for (l = 0; l < 2; ++l) { for (i1 = 0; i1 < 3; ++i1) { par1World.setBlock(par2 + b0 * l, par3 + i1, par4 + b1 * l, this.blockID/*Main.MyPortalBlock_1.blockID*/, 0, 2); } } return true; } } /** * Lets the block know when one of its neighbor changes. Doesn't know which * neighbor changed (coordinates passed are their own) Args: x, y, z, * neighbor blockID */ public void onNeighborBlockChange(World par1World, int par2, int par3, int par4, int par5) { /*byte b0 = 0; byte b1 = 1; if (par1World.getBlockId(par2 - 1, par3, par4) == this.blockID || par1World.getBlockId(par2 + 1, par3, par4) == this.blockID) { b0 = 1; b1 = 0; } int i1; for (i1 = par3; par1World.getBlockId(par2, i1 - 1, par4) == this.blockID; --i1) { ; } if (par1World.getBlockId(par2, i1 - 1, par4) != frameBlock) { par1World.setBlockToAir(par2, par3, par4); } else { int j1; for (j1 = 1; j1 < 4 && par1World.getBlockId(par2, i1 + j1, par4) == this.blockID; ++j1) { ; } if (j1 == 3 && par1World.getBlockId(par2, i1 + j1, par4) == frameBlock) { boolean flag = par1World.getBlockId(par2 - 1, par3, par4) == this.blockID || par1World.getBlockId(par2 + 1, par3, par4) == this.blockID; boolean flag1 = par1World.getBlockId(par2, par3, par4 - 1) == this.blockID || par1World.getBlockId(par2, par3, par4 + 1) == this.blockID; if (flag && flag1) { par1World.setBlockToAir(par2, par3, par4); } else { if ((par1World.getBlockId(par2 + b0, par3, par4 + b1) != frameBlock || par1World.getBlockId(par2 - b0, par3, par4 - b1) != this.blockID) && (par1World.getBlockId(par2 - b0, par3, par4 - b1) != frameBlock || par1World.getBlockId(par2 + b0, par3, par4 + b1) != this.blockID)) { par1World.setBlockToAir(par2, par3, par4); } } } else { par1World.setBlockToAir(par2, par3, par4); } }*/ } @SideOnly(Side.CLIENT) /** * Returns true if the given side of this block type should be rendered, if the adjacent block is at the given * coordinates. Args: blockAccess, x, y, z, side */ public boolean shouldSideBeRendered(IBlockAccess par1IBlockAccess, int par2, int par3, int par4, int par5) { if (par1IBlockAccess.getBlockId(par2, par3, par4) == this.blockID) { return false; } else { boolean flag = par1IBlockAccess.getBlockId(par2 - 1, par3, par4) == this.blockID && par1IBlockAccess.getBlockId(par2 - 2, par3, par4) != this.blockID; boolean flag1 = par1IBlockAccess.getBlockId(par2 + 1, par3, par4) == this.blockID && par1IBlockAccess.getBlockId(par2 + 2, par3, par4) != this.blockID; boolean flag2 = par1IBlockAccess.getBlockId(par2, par3, par4 - 1) == this.blockID && par1IBlockAccess.getBlockId(par2, par3, par4 - 2) != this.blockID; boolean flag3 = par1IBlockAccess.getBlockId(par2, par3, par4 + 1) == this.blockID && par1IBlockAccess.getBlockId(par2, par3, par4 + 2) != this.blockID; boolean flag4 = flag || flag1; boolean flag5 = flag2 || flag3; return flag4 && par5 == 4 ? true : (flag4 && par5 == 5 ? true : (flag5 && par5 == 2 ? true : flag5 && par5 == 3)); } } /** * Returns the quantity of items to drop on block destruction. */ public int quantityDropped(Random par1Random) { return 0; } @SideOnly(Side.CLIENT) /** * Returns which pass should this block be rendered on. 0 for solids and 1 for alpha */ public int getRenderBlockPass() { return 1; } @SideOnly(Side.CLIENT) /** * only called by clickMiddleMouseButton , and passed to inventory.setCurrentItem (along with isCreative) */ public int idPicked(World par1World, int par2, int par3, int par4) { return 0; } public static void setFrameBlock(Block b) { frameBlock = b.blockID; } public static void setPortalSize(int pW, int pH) { portalWidth = pW; portalHeight = pH; } }
package com.gitlab.davinkevin.podcastserver.youtubedl.utils; import java.io.IOException; import java.io.InputStream; public class StreamGobbler extends Thread { private InputStream stream; private StringBuffer buffer; public StreamGobbler(StringBuffer buffer, InputStream stream) { this.stream = stream; this.buffer = buffer; start(); } public void run() { try { int nextChar; while((nextChar = this.stream.read()) != -1) { this.buffer.append((char) nextChar); } } catch (IOException e) { } } }
public class TestModule { public TestModule() { System.out.println("Yes! Just do it."); } public void sayHello() {} }
public class Father extends GrandFa { private int nai = 55; private int house = 1; public String gabo = "황금돼지"; public Father() { System.out.println(""); } public Father(int nai) { this.nai=nai; } public int getNai() { return nai; } public void setNai(int nai) { this.nai = nai; } public int getHouse() { return house; } public void setHouse(int house) { this.house = house; } public String getGabo() { return gabo; } public void setGabo(String gabo) { this.gabo = gabo; } public void show() { System.out.println(this.gabo); System.out.println(super.gahun); System.out.println("아버지의 나이:"+ this.getNai()); System.out.println("할아버지의 나이:" +super.getNai()); } }
package com.example.android.navigationaldrawer2.rest.interfaces; import com.example.android.navigationaldrawer2.models.Flower; import java.util.List; import retrofit2.Call; import retrofit2.http.GET; /** * Created by Andrițchi Alexei on 9/27/16. */ public interface FlowerService { @GET("/feeds/flowers.json") Call<List<Flower>> getFlowers(); }
package PaymentProcessor; public interface ICardDetails { String expDate = null; String accNo = null; String sNo = null; void showCardDetails(); }
package demo.rabbitmq.hello; import com.rabbitmq.client.*; import demo.rabbitmq.SimpleChannelFactory; import java.io.IOException; import java.util.concurrent.TimeoutException; /** * Created by dongsj on 2017/4/11. */ public class Receiver { private static final String QUEUE_NAME = "hello"; public static void main(String[] args) throws IOException, TimeoutException { Channel channel = SimpleChannelFactory.getChannel("hello"); System.out.println(" [C] Waiting for messages. To exit press CTRL+C"); Consumer consumer = new DefaultConsumer(channel){ @Override public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException { String message = new String(body, "UTF-8"); System.out.println(" [C] Received '" + message + "'"); } }; channel.basicConsume(QUEUE_NAME, true, consumer); } }
package com.pooyaco.person.web.controller; import com.pooyaco.gazelle.si.BaseService; import com.pooyaco.gazelle.web.controller.GazelleLazyDataController; import com.pooyaco.person.dto.PersonDto; import com.pooyaco.person.si.PersonService; import org.primefaces.model.SortOrder; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import java.util.List; import java.util.Map; /** * Created by h.rostami on 2015/03/12. */ @Component @Scope("view") public class PersonLazyDataController extends GazelleLazyDataController<PersonDto> { private transient PersonService<PersonDto> personService; public PersonLazyDataController(PersonService personService) { this.personService = personService; } public PersonService<PersonDto> getPersonService() { return personService; } public void setPersonService(PersonService<PersonDto> personService) { this.personService = personService; } @Override public List<PersonDto> load(int first, int pageSize, String sortField, SortOrder sortOrder, Map<String, Object> filters) { return super.load(first, pageSize, sortField, sortOrder, filters); } @Override public BaseService getService() { return getPersonService(); } }
package com.version.SpringOne.service; import com.version.SpringOne.Model.PostObject; import com.version.SpringOne.Repository.PostRepo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class PostService { @Autowired PostRepo postRepo; public PostObject save(PostObject postObject){ return postRepo.save(postObject); } }
package com.avinash.book.Controller; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import com.avinash.book.entity.Book; import com.avinash.book.service.BookService; @RestController public class BookController { @Autowired BookService bookService; @GetMapping("/books") public ResponseEntity<List<Book>> getBooks() { List<Book> books = this.bookService.getAllBooks(); if(books.size()<=0) { return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); } return ResponseEntity.of(Optional.of(books)); } @GetMapping("/books/{id}") public ResponseEntity<Optional<Book>> getBookById(@PathVariable("id") int id) { Optional<Book> book = this.bookService.getBookById(id); if(book == null) { return ResponseEntity.status(HttpStatus.NOT_FOUND).build(); } return ResponseEntity.of(Optional.of(book)); } @PostMapping("/books") public ResponseEntity<Book> createBook(@RequestBody Book book) { try { this.bookService.createBook(book); return ResponseEntity.status(HttpStatus.CREATED).build(); } catch (Exception e) { e.printStackTrace(); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } } @PutMapping("/books/{id}") public ResponseEntity<Book> updateBook(@RequestBody Book book,@PathVariable int id) { try { this.bookService.updateBook(book,id); return ResponseEntity.ok().body(book); } catch (Exception e) { e.printStackTrace(); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } } @DeleteMapping("/books/{id}") public ResponseEntity<Void> deleteBook(@PathVariable("id") int id) { try { this.bookService.deleteBook(id); // return ResponseEntity.ok().build(); return ResponseEntity.status(HttpStatus.NO_CONTENT).build(); } catch (Exception e) { e.printStackTrace(); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } } }
package com.wjfit.anno; //使用注解时,当只有一个属性并且名称为value,此时可以省略value @SuppressWarnings("all") @Deprecated @VIP(name = "xx",age=20, hobby = { "java" }) public class Employee { }
package com.gs.tablasco.spark; import org.apache.spark.api.java.JavaRDD; import java.util.List; /** * A distributed table that can be compared by SparkVerifier */ @SuppressWarnings("WeakerAccess") public class DistributedTable { private final List<String> headers; private final JavaRDD<List<Object>> rows; /** * @param headers table headers (column names) * @param rows An RDD of table rows with a row represented as a list of objects */ public DistributedTable(List<String> headers, JavaRDD<List<Object>> rows) { this.headers = headers; this.rows = rows; } /** * @return the table headers (column names) */ public List<String> getHeaders() { return headers; } /** * @return An RDD of table rows with a row represented as a list of objects */ public JavaRDD<List<Object>> getRows() { return rows; } }
package com.company; public interface manosCalientes { public boolean cocinarPlatillo(boolean i, boolean j); }
import java.awt.BorderLayout; import java.awt.EventQueue; import java.awt.Image; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.ImageIcon; import javax.swing.JButton; import java.awt.event.ActionListener; import java.beans.Statement; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.awt.event.ActionEvent; import javax.swing.JTextField; import javax.swing.JLabel; import javax.swing.JOptionPane; import java.awt.Font; import java.awt.Image; import javax.swing.JCheckBox; import java.awt.Color; public class StarIndia extends JFrame { private JPanel lb3; Connection connectionobject = null; Statement statementobject = null; ResultSet resultsetobject = null; /** * Launch the application. */ public void dbconnection(){ try { Class.forName("oracle.jdbc.driver.OracleDriver"); connectionobject = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","hms","hms"); } catch(Exception e) { System.out.println(e); } } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { StarIndia frame = new StarIndia(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public StarIndia() { dbconnection(); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 1076, 485); lb3 = new JPanel(); lb3.setBackground(new Color(0, 0, 0)); lb3.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(lb3); lb3.setLayout(null); JButton btnMainPage = new JButton("MAIN PAGE"); btnMainPage.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { EathubMainPage mp = new EathubMainPage(); mp.setVisible(true); } }); btnMainPage.setBounds(576, 400, 97, 25); lb3.add(btnMainPage); JCheckBox CG1 = new JCheckBox("GOBI 65\r\n PRICE: 9.99\r\n SIZE: LARGE"); CG1.setBackground(new Color(0, 0, 0)); CG1.setForeground(new Color(255, 255, 255)); CG1.setBounds(170, 246, 315, 25); lb3.add(CG1); JCheckBox CB1 = new JCheckBox("CHEFS BIRYANI SPECIAL\r\n PRICE: 13.01\r\n SIZE: MEDIUM"); CB1.setBackground(new Color(0, 0, 0)); CB1.setForeground(new Color(255, 255, 255)); CB1.setBounds(170, 284, 346, 25); lb3.add(CB1); JCheckBox R1 = new JCheckBox("RASMALAI\r\n PRICE: 6.99\r\n SIZE: SMALL\r\n"); R1.setBackground(new Color(0, 0, 0)); R1.setForeground(new Color(255, 255, 255)); R1.setBounds(170, 322, 315, 25); lb3.add(R1); JCheckBox CB2 = new JCheckBox("CHEFS BIRYANI SPECIAL\r\n PRICE: 11.01\r\n SIZE: SMALL"); CB2.setBackground(new Color(0, 0, 0)); CB2.setForeground(new Color(255, 255, 255)); CB2.setBounds(562, 246, 369, 25); lb3.add(CB2); JCheckBox M2 = new JCheckBox("MALAI KOFTA\r\n PRICE: 7.99\r\n SIZE: SMALL"); M2.setBackground(new Color(0, 0, 0)); M2.setForeground(new Color(255, 255, 255)); M2.setBounds(562, 284, 328, 25); lb3.add(M2); JCheckBox G2 = new JCheckBox("GOBI 65\r\n PRICE: 6.99\r\n SIZE: SMALL"); G2.setBackground(new Color(0, 0, 0)); G2.setForeground(new Color(255, 255, 255)); G2.setBounds(562, 322, 328, 25); lb3.add(G2); JButton btnConfirm = new JButton("CONFIRM"); btnConfirm.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String selection = null; double price1=0.00,price2=0.00,price3=0.00,price4=0.00,price5=0.00,price6=0.00; if(CG1.isSelected()) { price1=9.99; } if(CB1.isSelected()) { price2=13.01; } if(R1.isSelected()) { price3=6.99; } if(CB2.isSelected()) { price4=11.01; } if(M2.isSelected()) { price5=7.99; } if(G2.isSelected()) price6=6.99; double total=price1+price2+price3+price4+price5+price6+10; int dialogResult = JOptionPane.showConfirmDialog(null, "Please confirm your order"); if(dialogResult == JOptionPane.YES_OPTION){ JOptionPane.showMessageDialog(null, "Your Order is confirmed\n Your Order Price:"+total); } else if(dialogResult == JOptionPane.NO_OPTION){ JOptionPane.showMessageDialog(null, "Please order again"); } else if(dialogResult== JOptionPane.CANCEL_OPTION) { JOptionPane.showMessageDialog(null, EXIT_ON_CLOSE); } } }); btnConfirm.setBounds(394, 400, 97, 25); lb3.add(btnConfirm); Image img=new ImageIcon(this.getClass().getResource("/cover.png")).getImage(); JLabel lb2 = new JLabel("New label"); Image img1=new ImageIcon(this.getClass().getResource("/o1.png")).getImage(); lb2.setIcon(new ImageIcon(img1)); lb2.setBounds(4, 13, 572, 216); lb3.add(lb2); } }
package com.appsala.app.services; import java.util.List; import java.util.Optional; import com.appsala.app.entities.Ambiente; import org.springframework.stereotype.Service; import com.appsala.app.repository.AmbienteRepository; import org.springframework.beans.factory.annotation.Autowired; @Service public class AmbienteService { @Autowired private AmbienteRepository ambienteRepository; public AmbienteService() { } public <S extends Ambiente> S create(S entity) { return ambienteRepository.save(entity); } public <S extends Ambiente> S update(S entity) { return ambienteRepository.save(entity); } public void deleteById(Integer id) { ambienteRepository.deleteById(id); } public Ambiente findById(Integer id) { Optional<Ambiente> ambienteOpt = ambienteRepository.findById(id); return ambienteOpt.orElse(null); } public List<Ambiente> findAll() { return ambienteRepository.findAll(); } }
package com.thonline.common; import java.sql.Connection; import java.util.Hashtable; import java.util.Properties; import javax.sql.DataSource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.xnarum.bi.common.PropertyReader; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; public class DatasourceFactory { public static String URL = "url"; public static String USER = "user"; public static String PASSWORD = "password"; public static String DATASOURCE_CLASS = "datasourceClass"; public static String POOL_SIZE = "pool_size"; public static String VALIDATION_QUERY = "validation_query"; private static Logger logger = LoggerFactory.getLogger(DatasourceFactory.class); private static Hashtable<String, DataSource> pools = new Hashtable<String, DataSource>(); public static synchronized DataSource getDataSource( String key, Properties props ) throws Exception { try { DataSource ds = pools.get(key); if ( ds != null ) { if ( logger.isTraceEnabled() ) { logger.trace("Return existing data source {}", ds); } return ds; } logger.info("Create a new data source for {}", key); HikariConfig config = new HikariConfig(); String dsClass = props.getProperty(DATASOURCE_CLASS); if ( dsClass != null && dsClass.trim().length() > 0 ) { config.setDataSourceClassName(dsClass); } config.setJdbcUrl(props.getProperty(URL)); config.setUsername(props.getProperty(USER)); config.setPassword(props.getProperty(PASSWORD)); config.addDataSourceProperty("cachePrepStmts", "true"); config.addDataSourceProperty("prepStmtCacheSize", "250"); config.addDataSourceProperty("prepStmtCacheSqlLimit", "2048"); config.setMaxLifetime(120*1000); config.setLeakDetectionThreshold(60*1000); config.setAutoCommit(false); String poolSize = props.getProperty(POOL_SIZE, "10"); try { int poolSizeInt = Integer.parseInt(poolSize); config.setMaximumPoolSize(poolSizeInt); String validationQuery = props.getProperty(VALIDATION_QUERY); if ( validationQuery != null ) { config.setConnectionTestQuery(validationQuery); } }catch( Exception ex ) { logger.error("Initialization failed", ex); throw new Exception(String.format("Pool size parameter must be number type [%s]", poolSize)); } logger.info("{}", config.getDataSourceProperties()); ds = new HikariDataSource(config); pools.put(key, ds); return ds; }catch( Exception ex ) { throw ex; } } public static void main(String [] args) { System.setProperty("bicom.properties", "/sw/ISMJBOSS/bicom/bicom.properties"); Properties props = new Properties(); String url = String.format("%s;%s", PropertyReader.getProperty("core.db.url"), PropertyReader.getProperty("core.db.properties")); props.setProperty(DatasourceFactory.URL, url); props.setProperty(DatasourceFactory.USER, PropertyReader.getProperty("core.db.user")); props.setProperty(DatasourceFactory.PASSWORD, PropertyReader.getProperty("core.db.password")); props.setProperty(DatasourceFactory.POOL_SIZE, PropertyReader.getProperty("core.db.poolsize")); props.setProperty(DatasourceFactory.VALIDATION_QUERY, PropertyReader.getProperty("core.db.validation")); try { String driverClassName = PropertyReader.getProperty("core.db.driver.class"); if ( driverClassName != null && driverClassName.trim().length() > 0 ) { Class.forName(driverClassName); } DataSource ds = DatasourceFactory.getDataSource("core", props); Thread.sleep(30000); }catch( Exception ex ) { ex.printStackTrace(); } } }
package com.bnrc.ui.rjz; import java.io.UnsupportedEncodingException; import java.lang.reflect.Constructor; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.bouncycastle.crypto.tls.AlertLevel; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.json.XML; import u.aly.aa; import com.ab.global.AbConstant; import com.baidu.location.BDLocation; import com.baidu.mapapi.model.LatLng; import com.bnrc.busapp.PollingService; import com.bnrc.busapp.PollingUtils; import com.bnrc.busapp.R; import com.bnrc.busapp.SearchBuslineView; import com.bnrc.busapp.SubWayActivity; import com.bnrc.busapp.SegmentedGroup; import com.bnrc.busapp.SettingView; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import com.bnrc.network.MyVolley; import com.bnrc.ui.rtBus.Child; import com.bnrc.ui.rtBus.Group; import com.bnrc.ui.rtBus.PinnedHeaderExpandableConcernAdapter; import com.bnrc.ui.rtBus.PinnedHeaderExpandableLocListView; import com.bnrc.util.BuslineDBHelper; import com.bnrc.util.DataBaseHelper; import com.bnrc.util.GetToMarket; import com.bnrc.util.LocationUtil; import com.bnrc.util.SlidingDrawerGridView; import com.bnrc.util.UserDataDBHelper; import com.bnrc.util.collectwifi.Constants; import com.bnrc.util.collectwifi.ScanService; import com.bnrc.util.collectwifi.ServiceUtils; import com.umeng.analytics.MobclickAgent; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.database.SQLException; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.app.FragmentStatePagerAdapter; import android.support.v4.app.FragmentTransaction; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener; import android.text.Html; import android.util.Log; import android.view.Display; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.view.ViewGroup; import android.view.WindowManager; import android.view.View.OnClickListener; import android.view.inputmethod.InputMethodManager; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ExpandableListView; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.RadioGroup; import android.widget.RelativeLayout; import android.widget.ScrollView; import android.widget.TextView; import android.widget.Toast; import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemLongClickListener; import android.widget.RadioGroup.OnCheckedChangeListener; public class ConcernFragment3 extends BaseFragment { private static final String TAG = ConcernFragment3.class.getSimpleName(); private Context mContext; private ImageView refesh = null; private ImageView openAlertView; private Handler mHandler; private String isOpenAlert; private EditText mSearchEdt; private SegmentedGroup segmented; private MyViewPager mPager; private AllConcernFragSwipe mAllFrag; private WorkFragSwipe mWorkFrag; private HomeFragSwipe mHomeFrag; private ArrayList<BaseFragment> mFragmentList; private ImageButton menuSettingBtn;// 菜单呼出按钮 private IPopWindowListener mChooseListener; private MyViewPagerAdapter mPagerAdapter; private UserDataDBHelper mUserDB; private int mLastIndex = 0; private List<Integer> TABLE; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // TODO Auto-generated method stub mContext = (Context) getActivity(); View view = LayoutInflater.from(mContext).inflate( R.layout.zj_near_view2, null); // initAD(); // LatLng myPoint = new LatLng(mBDLocation.getLatitude(), // mBDLocation.getLongitude()); mUserDB = UserDataDBHelper.getInstance(mContext); // mUserDB.AcquireFavInfoWithLocation(myPoint); // initTitleRightLayout(); menuSettingBtn = (ImageButton) view.findViewById(R.id.menu_imgbtn); menuSettingBtn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub mChooseListener.onLoginClick(); } }); refesh = (ImageView) view.findViewById(R.id.refresh); mSearchEdt = (EditText) view.findViewById(R.id.edt_input); mSearchEdt.setOnTouchListener(new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { // TODO Auto-generated method stub /** 加这个判断,防止该事件被执行两次 */ if (event.getAction() == MotionEvent.ACTION_DOWN) { Intent intent = new Intent(getActivity(), SearchBuslineView.class); startActivity(intent); } return false; } }); segmented = (SegmentedGroup) view.findViewById(R.id.segmentedGroup); segmented.setTintColor(getResources().getColor( R.color.radio_button_selected_color)); mAllFrag = new AllConcernFragSwipe(); mWorkFrag = new WorkFragSwipe(); mHomeFrag = new HomeFragSwipe(); mFragmentList = new ArrayList<BaseFragment>(); mFragmentList.add(mAllFrag); mFragmentList.add(mWorkFrag); mFragmentList.add(mHomeFrag); mPager = (MyViewPager) view.findViewById(R.id.content); segmented.setOnCheckedChangeListener(new CheckedChangeListener()); mPagerAdapter = new MyViewPagerAdapter(getFragmentManager()); mPager.setAdapter(mPagerAdapter); mPager.setOnPageChangeListener(new PageChangeListener()); mPager.setOffscreenPageLimit(3); Log.i(TAG, TAG + " onCreateView " + "fraglist.size: " + mFragmentList.size()); segmented.check(R.id.radBtn_all); TABLE = new ArrayList<Integer>(); TABLE.add(0); TABLE.add(1); TABLE.add(2); mSearchEdt.clearFocus(); InputMethodManager imm = (InputMethodManager) mContext .getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(mSearchEdt.getWindowToken(), 0); return view; } public class MyViewPagerAdapter extends FragmentPagerAdapter { private FragmentManager mFragmentManager; private FragmentTransaction mCurTransaction; public MyViewPagerAdapter(FragmentManager fm) { super(fm); // TODO Auto-generated constructor stub this.mFragmentManager = fm; } @Override public Fragment getItem(int position) { Log.i(TAG, "mFragmentList.get(position) " + position); return mFragmentList.get(position); } @Override public int getCount() { return mFragmentList.size(); } @Override public int getItemPosition(Object object) { // TODO Auto-generated method stub return FragmentStatePagerAdapter.POSITION_NONE; } public void destroyAllItem() { int mPosition = mPager.getCurrentItem(); int mPositionMax = mPager.getCurrentItem() + 1; if (TABLE.size() > 0 && mPosition < TABLE.size()) { if (mPosition > 0) { mPosition--; } mPosition = 0; mPositionMax = 3; for (int i = mPosition; i < mPositionMax; i++) { try { Object objectobject = this.instantiateItem(mPager, TABLE.get(i).intValue()); if (objectobject != null) destroyItem(mPager, TABLE.get(i).intValue(), objectobject); } catch (Exception e) { Log.i(TAG, "no more Fragment in FragmentPagerAdapter"); } } } } @Override public void destroyItem(ViewGroup container, int position, Object object) { super.destroyItem(container, position, object); if (position <= getCount()) { // FragmentManager manager = ((Fragment) // object).getFragmentManager(); // FragmentTransaction trans = manager.beginTransaction(); if (mCurTransaction == null) mCurTransaction = mFragmentManager.beginTransaction(); mCurTransaction.remove((Fragment) object); mCurTransaction.commit(); } } } private class CheckedChangeListener implements OnCheckedChangeListener { public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.radBtn_all: mPager.setCurrentItem(0); mLastIndex = 0; break; case R.id.radBtn_work: mPager.setCurrentItem(1); mLastIndex = 1; break; case R.id.radBtn_home: mPager.setCurrentItem(2); mLastIndex = 2; break; } } } // 刷新实时数据 @Override public void refreshConcern() { if (this != null && !this.isDetached() && this.isVisible()) { if (mFragmentList == null) return; for (BaseFragment frag : mFragmentList) frag.refreshConcern(); } } // 刷新实时数据 @Override public void refresh() { if (this != null && !this.isDetached() && this.isVisible()) { if (mFragmentList == null) return; for (BaseFragment frag : mFragmentList) frag.refresh(); } } private class PageChangeListener implements OnPageChangeListener { public void onPageSelected(int position) { switch (position) { case 0: segmented.check(R.id.radBtn_all); break; case 1: segmented.check(R.id.radBtn_work); break; case 2: segmented.check(R.id.radBtn_home); break; } } public void onPageScrollStateChanged(int arg0) { } public void onPageScrolled(int arg0, float arg1, int arg2) { } } private void initAD() { isOpenAlert = "开启提醒功能"; MobclickAgent.updateOnlineConfig(mContext); String value = MobclickAgent.getConfigParams(mContext, "bus_data_version"); JSONObject jsonObj = null; try { jsonObj = new JSONObject(value); String version = jsonObj.getString("version"); String ready = jsonObj.getString("ready"); SharedPreferences mySharedPreferences = mContext .getSharedPreferences("setting", SettingView.MODE_PRIVATE); String oldVersion = mySharedPreferences.getString( "bus_data_version", "1"); if (ready.equalsIgnoreCase("YES") && (version.equalsIgnoreCase(oldVersion) == false)) { AlertDialog.Builder builder = new AlertDialog.Builder(mContext); builder.setMessage("公交数据已经推出了新的版本,您是否要更新?").setTitle("友情提示") .setNegativeButton("取消", null); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // DataBaseHelper.getInstance(mContext) // .DownFileWithUrl( // MobclickAgent.getConfigParams( // mContext, // "bus_data_url")); } }); builder.show(); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } value = MobclickAgent.getConfigParams(mContext, "realtime_bus_data_version"); Log.i("realtime_bus_data_version", value); try { jsonObj = new JSONObject(value); String version = jsonObj.getString("version"); String ready = jsonObj.getString("ready"); SharedPreferences mySharedPreferences = mContext .getSharedPreferences("setting", SettingView.MODE_PRIVATE); String oldVersion = mySharedPreferences.getString( "realtime_bus_data_version", "1"); if (ready.equalsIgnoreCase("YES") && (version.equalsIgnoreCase(oldVersion) == false)) { AlertDialog.Builder builder = new AlertDialog.Builder(mContext); builder.setMessage("实时公交数据有更新,您是否要更新?").setTitle("友情提示") .setNegativeButton("取消", null); builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // BuslineDBHelper // .getInstance(mContext) // .DownFileWithUrl( // MobclickAgent // .getConfigParams( // mContext, // "realtime_bus_data_url")); } }); builder.show(); } } catch ( JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void onStart() { super.onStart(); Log.i(TAG, TAG + " onStart"); } @Override public void onAttach(Activity activity) { // TODO Auto-generated method stub super.onAttach(activity); mContext = (Context) activity; mChooseListener = (IPopWindowListener) activity; Log.i(TAG, TAG + " onAttach"); } @Override public void onDestroy() { super.onDestroy(); // Stop polling service System.out.println("Stop polling service..."); PollingUtils.stopPollingService(mContext, PollingService.class, PollingService.ACTION); ServiceUtils.stopPollingService(mContext.getApplicationContext(), ScanService.class, Constants.SERVICE_ACTION); Log.i(TAG, TAG + " onDestroy"); } @Override public void onActivityCreated(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onActivityCreated(savedInstanceState); Log.i(TAG, TAG + " onActivityCreated"); } @Override public void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); Log.i(TAG, TAG + " onCreate"); } @Override public void onDestroyView() { // TODO Auto-generated method stub super.onDestroyView(); Log.i(TAG, TAG + " onDestroyView"); } @Override public void onDetach() { // TODO Auto-generated method stub super.onDetach(); Log.i(TAG, TAG + " onDetach"); mPagerAdapter.destroyAllItem(); } @Override public void onResume() { // TODO Auto-generated method stub super.onResume(); Log.i(TAG, TAG + " onResume" + " fraglist.size: " + mFragmentList.size()); } @Override public void onStop() { // TODO Auto-generated method stub super.onStop(); Log.i(TAG, TAG + " onStop"); } }
import static org.assertj.core.api.Assertions.assertThat; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.junit.Test; public class SuffixTrieTest { @Test public void testBuildSuffixTrie() throws Exception { SuffixTrie st = new SuffixTrie("banana"); // System.out.println(st.root.children.toString()); // System.out.println(st.root.children.get('a').children.toString()); printSuffixTrieNode(st.root, ""); System.out.println(st.root.getAllLeafNodes().stream().map(n -> n.position).collect(Collectors.toList())); } @Test public void testSearchPattern() throws Exception { SuffixTrie st = new SuffixTrie("banana"); List<Integer> positions; positions = st.searchPattern("a"); assertThat(positions).containsExactlyInAnyOrder(1, 3, 5); positions = st.searchPattern("na"); assertThat(positions).containsExactlyInAnyOrder(2, 4); positions = st.searchPattern("ana"); assertThat(positions).containsExactlyInAnyOrder(1, 3); positions = st.searchPattern("banana"); assertThat(positions).containsExactlyInAnyOrder(0); positions = st.searchPattern("bananana"); assertThat(positions).isEmpty(); } // SuffixTrieNodeを深さ優先でprintしていく関数 public void printSuffixTrieNode(SuffixTrieNode node, String prefix) { for (Map.Entry<Character, SuffixTrieNode> entry : node.children.entrySet()) { System.out.print(prefix + entry.getKey()); if (entry.getValue().isLeaf()) { System.out.print("(" + entry.getValue().position + ")"); } System.out.println(""); printSuffixTrieNode(entry.getValue(), prefix + " "); } } }
package com.citibank.ods.entity.pl.valueobject; /** * @author m.nakamura * * Representação da tabela de Crítica Lógica */ public class TplLogicCritEntityVO extends BaseTplLogicCritEntityVO { }
package me.x1machinemaker1x.shootinggallery.utils; import java.util.HashMap; import java.util.UUID; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Player; public class ScoreManager { private static ScoreManager instance = new ScoreManager(); HashMap<UUID, Integer> scores; public static ScoreManager getInstance() { return instance; } public void onEnable() { this.scores = new HashMap<UUID, Integer>(); ConfigurationSection conf = ConfigManager.getInstance().getScores().getConfigurationSection("Scores"); if (conf != null) { for (String uuid : conf.getKeys(false)) { this.scores.put(UUID.fromString(uuid), Integer.valueOf(conf.getInt(uuid))); } } } public void updateScoresInConfig() { ConfigManager.getInstance().getScores().set("Arenas", null); ConfigManager.getInstance().saveScores(); if (!this.scores.isEmpty()) { ConfigurationSection conf = ConfigManager.getInstance().getScores().createSection("Scores"); for (UUID uuid : this.scores.keySet()) { conf.set(uuid.toString(), this.scores.get(uuid)); } ConfigManager.getInstance().saveScores(); } } public boolean addScore(Player p, int score) { boolean highScore; if (this.scores.containsKey(p.getUniqueId())) { if (scores.get(p.getUniqueId()) < score) { scores.replace(p.getUniqueId(), score); highScore = true; } else { highScore = false; } } else { this.scores.put(p.getUniqueId(), Integer.valueOf(score)); highScore = true; } updateScoresInConfig(); return highScore; } public void resetScores() { this.scores.clear(); ConfigManager.getInstance().getScores().set("Scores", null); ConfigManager.getInstance().saveScores(); } }
package org.team16.team16week5; import java.io.IOException; import java.util.Scanner; import java.util.logging.FileHandler; import java.util.logging.Level; import java.util.logging.Logger; public class AppController { private static final Logger logger = Logger.getLogger(Bill.class.getName()); private FileHandler fileHandler; private Scanner sc; public AppController() { addFileHandler(logger); } public void changeInputData(String inputData) { if(inputData == null) sc = new Scanner(System.in); else sc = new Scanner(inputData); } public boolean run() { while(true) { logger.log(Level.INFO, "\n======================Bill System======================\n1-> " + "Get Result\n2-> Exit"); int choose = sc.nextInt(); if(choose == 1) { if( !getInputUserData()) return false; } else if(choose == 2) { logger.log(Level.INFO, "======================End Program======================"); return true; } else { logger.log(Level.INFO, "\nERROR!!\nWrong menu choosed\n\n"); return false; } } } private boolean getInputUserData() { logger.log(Level.INFO, "Type a sequence. Gold or Silver, Usage of minutes, Usage of lines (ex : Gold 900 1)"); String planType = sc.next(); int usedMinutes = sc.nextInt(); int numberOfLines = sc.nextInt(); if(isValidTypeName(planType) && isValidMinutes(usedMinutes) && isValidLines(numberOfLines)) { Bill newBill = new Bill(planType, usedMinutes, numberOfLines); logger.log(Level.INFO, "\n======================RESULT======================\nPlan : " + planType + "\nTotal Usage Time : " + usedMinutes + "\nUsing Lines : " + numberOfLines + "\n\n" + newBill.drawBill() + "==================================================\n"); return true; } else return false; } private boolean isValidTypeName(String planType) { if( !("Gold".equals(planType) || "Silver".equals(planType))) { logger.log(Level.INFO, "\nERROR!!\nType must be Gold or Silver\n\n"); return false; } return true; } private boolean isValidMinutes(int usedMinutes) { if (usedMinutes <= 0) { logger.log(Level.INFO, "\nERROR!!\nNegative number or Zero cannot be used for minutes\n\n"); return false; } return true; } private boolean isValidLines(int numberOfLines) { if (numberOfLines <= 0) { logger.log(Level.INFO, "\nERROR!!\nNegative number or Zero cannot be used for line number\n\n"); return false; } return true; } private void addFileHandler(Logger logger) { try { fileHandler = new FileHandler(Bill.class.getName() + ".log"); } catch(IOException ioe) { logger.log(Level.SEVERE, null, ioe); } catch(SecurityException sece) { logger.log(Level.SEVERE, null, sece); } logger.addHandler(fileHandler); } }
package com.mycompany.sentenciasdecontrol2; public class SWITCH { public static void main(String[] args) { package sentenciasdecontrol2; import java.util.Scanner; public class Switch { private String nombredelcurso; private int total; private int contadorCalif; private int acuenta; private int bcuenta; private int cCuenta; private int dcuenta; private int fcuenta; public switch (String nombre) { nombredelcurso = nombre; } public void establecernombredelcurso(String nombre) { nombredelcurso=nombre; } public String obtenernombredelcurso () { return nombredelcurso; } public void mostrarmensaje() { System.out.println("Bienvenido al libro de calificaciones "+obtenernombredelcurso() ); } public void introducirCalif() { Scanner entrada = new Scanner (System.in); int calificacion; System.out.println("Escriba las calificaciones enteras en el rango de 0 a 100.","Escriba el indicador de fin de archivo"); while (entrada.hasNext()) { calificaion = entrada.nextInt(); total += calificacion; ++contadorCalif; incrementarContadorCalifLetra(calificacion); } } public void incrementarContadorCalifLetra( int calificacion ) { switch (calificacion / 10) { case 9: case 10: ++acuenta; break; case 8: ++bcuenta; break; case 7: ++cCuenta; break; case 6; ++dcuenta; break; default; ++fcuenta; break; } } public void mostrarreporteCalif() { System.out.println("\nReporte de calificaciones: " ); if (contadorCalif != 00) { double promedio = (double) total / contadorCalif; System.out.println("El total de las %d calificaciones introducidads es %d\n",contadorCalif, total ); System.out.println("El promedio de la clase es %.2f\n", promedio ); System.out.println("%s\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n", "Número de estudiantes que recibieron cada calificación: ", "A: ", acuenta, "B: ", bcuenta, "C: ", cCuenta, "D: ", dcuenta, "F: ", fcuenta); } else System.out.println("No se introdujeron calificaciones"); } } } }
package com.dongh.funplus.view.other; import com.dongh.funplus.di.scope.FragmentScope; import com.dongh.funplus.base.mvp.BaseModel; import javax.inject.Inject; /** * Created by chenxz on 2017/12/3. */ @FragmentScope public class OtherModel extends BaseModel implements OtherContract.Model { @Inject public OtherModel() { } }
package Horners_Rule; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Input_func { // this class will be engaged with console input of the arrays of // coefficients and exponents int coefficient[]; int exponent[]; int x; public void Horner_Input(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int count = 0; System.out.println("please enter the no. of datas to be handled:"); try { count = Integer.parseInt(br.readLine()); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("Please consider your typing error and rerun:"); } // the size of the coefficient[] & exponent[] array is made coefficient = new int[count]; exponent = new int[count]; // input the values of the arrays System.out.println(); System.out.println("input the value of x:\t(integer)\t:"); try { x = Integer.parseInt(br.readLine()); } catch (NumberFormatException e1) { // TODO Auto-generated catch block e1.printStackTrace(); System.out.println("there is error in something"); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); System.out.println("there is error in something"); } System.out.println("input the values of the polynomial"); for (int i = 0; i < count; i++) { System.out.println("Input the coefficient:"); try { coefficient[i] = Integer.parseInt(br.readLine()); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("there is error in something"); } System.out.println(); System.out.println("Input the exponent:"); try { exponent[i] = Integer.parseInt(br.readLine()); } catch (NumberFormatException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("there is error in something"); } System.out.println(); } } }
package bupt.hpcn.onlinestandard.service; import bupt.hpcn.onlinestandard.mapper.StandardMapper; import bupt.hpcn.onlinestandard.domain.StandardDO; import com.alibaba.fastjson.JSONObject; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service("standardService") public class StandardServiceImpl implements StandardService{ @Autowired private StandardMapper standardMapper; @Override public List<StandardDO> getStandardByBusiness(int businessID) throws Exception{ return standardMapper.getStandardByBusiness(businessID); } @Override public StandardDO getStandardDetail(int standardID) throws Exception{ return standardMapper.getStandardDetail(standardID); } @Override public List<JSONObject> getNames(List<Integer> idList) throws Exception{ return standardMapper.getNames(idList); } @Override public List<JSONObject> getAllStandards() throws Exception { return standardMapper.getAllStandards(); } }
/** * Copyright (C) 2014-2017 Philip Helger (www.helger.com) * philip[at]helger[dot]com * * 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.helger.commons.cache; import java.util.function.Function; import javax.annotation.CheckForSigned; import javax.annotation.Nonnull; import javax.annotation.concurrent.ThreadSafe; import com.helger.commons.CGlobal; /** * A special cache that can create the value to be cache automatically from the * key. * * @author Philip Helger * @param <KEYTYPE> * Cache key type * @param <VALUETYPE> * Cache value type */ @ThreadSafe public class CacheWithConversion <KEYTYPE, VALUETYPE> extends AbstractCache <KEYTYPE, VALUETYPE> { public CacheWithConversion (@Nonnull final String sCacheName) { this (CGlobal.ILLEGAL_UINT, sCacheName); } public CacheWithConversion (@CheckForSigned final int nMaxSize, @Nonnull final String sCacheName) { super (nMaxSize, sCacheName); } /** * Get the value from the cache. If no value is yet in the cache, the passed * converter is used to get the value to cache. * * @param aKey * The key of the cached object. May not be <code>null</code>. * @param aValueRetriever * The converter to be used to retrieve the object to cache. May not be * <code>null</code>. This converter may not return <code>null</code> * objects to cache! * @return The cached value. Never <code>null</code>. */ @Nonnull public final VALUETYPE getFromCache (@Nonnull final KEYTYPE aKey, @Nonnull final Function <KEYTYPE, VALUETYPE> aValueRetriever) { // Already in the cache? VALUETYPE aValue = super.getFromCacheNoStats (aKey); if (aValue == null) { // No old value in the cache aValue = m_aRWLock.writeLocked ( () -> { // Read again, in case the value was set between the two locking // sections // Note: do not increase statistics in this second try VALUETYPE aWLValue = super.getFromCacheNoStatsNotLocked (aKey); if (aWLValue == null) { // Get the value to cache aWLValue = aValueRetriever.apply (aKey); // We cannot cache null values! if (aWLValue == null) throw new IllegalStateException ("The converter returned a null object for the key '" + aKey + "'"); super.putInCacheNotLocked (aKey, aWLValue); m_aCacheAccessStats.cacheMiss (); } else m_aCacheAccessStats.cacheHit (); return aWLValue; }); } else m_aCacheAccessStats.cacheHit (); return aValue; } }
package api.militancia; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; import java.util.Optional; @Service @Transactional public class ServicioMilitancia { @Autowired private RepositorioMilitancia repositorioMilitancia; public EntidadMilitancia guardar(EntidadMilitancia militancia) { return repositorioMilitancia.save(militancia); } public Optional<EntidadMilitancia> obtenerPorId(int id) { return repositorioMilitancia.findById(id); } public Optional<EntidadMilitancia> actualizar(int id, EntidadMilitancia militancia) { return obtenerPorId(id).map(record -> { record.setHabilitado(militancia.isHabilitado()); record.setTipo(militancia.getTipo()); return guardar(record); }); } public Optional<EntidadMilitancia> eliminar(int id) { return obtenerPorId(id) .map(record -> { record.setHabilitado(false); return guardar(record); }); } public List<EntidadMilitancia> listarTodos() { return repositorioMilitancia.findAll(); } }
package FactoryPattern; public abstract class Pepperoni { private String name; public Pepperoni(String name) { super(); this.name = name; } public String getName() { return this.name; } }
/** * Time complexity : O(n). We traverse the list containing n elements only once. Each look up in the table costs only O(1) time. * Space complexity : O(n). The extra space required depends on the number of items stored in the hash table, which stores at most n elements. * */ public class Solution { public int[] twoSum(int[] nums, int target) { int result[] = new int[2]; Map<Integer, Integer> map = new HashMap<>(); for (int i = 0; i <= nums.length - 1; i++) { int complement = target - nums[i]; if (map.containsKey(complement)) { result[0] = map.get(complement); result[1] = i; return result; } map.put(nums[i], i); } return result; } }
package java8.optional; import java.util.Optional; public class WithOptional { public static void main(String[] args) { String str[] = new String[10]; //str[5] = "Hello"; Optional<String> checkNull = Optional.ofNullable(str[5]); if(checkNull.isPresent()) { System.out.println(checkNull.get()); } else { System.out.println("No value assigned yet"); } //NoSuchElementExcpetion //System.out.println(checkNull.get()); str[5] = "Hello"; checkNull = Optional.ofNullable(str[5]); /*checkNull.ifPresent(new Consumer<String>() { @Override public void accept(String arg0) { System.out.println(arg0); } });*/ checkNull.ifPresent(System.out::println); System.out.println(checkNull.get()); //str[0] = "Now assigned"; Optional<String> orElseEx = Optional.ofNullable(str[0]); System.out.println("Or Else Value: " + orElseEx.orElse("Else Value, means empty")); } }
package com.itsoul.lab.generalledger.exception; /** * */ public class LedgerAccountException extends BusinessException { private static final long serialVersionUID = -6113857738235916873L; public LedgerAccountException(String accountRef) { super("Ledger does not contain account with reference '" + accountRef + "'"); } }
package com.example.movieapp; import com.example.movieapp.JsonResponse; import com.example.movieapp.JsonResultsResponse; public interface SearchListener { void onSuccessResponse(JsonResponse data); void onErrorResponse(String data); }
package com.aegamesi.mc.soundboard; import java.util.ArrayList; import java.util.Random; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Sound; import org.bukkit.entity.EntityType; import org.bukkit.entity.Firework; import org.bukkit.entity.Player; public class SoundboardPlayer { public int bound = -1; public ArrayList<SoundboardEffect> effects = new ArrayList<SoundboardEffect>(); public int target = TARGET_SELF_ONLY; public String targetPlayer = null; public Location targetLocation = null; public boolean doSelectLocation = false; public int task = -1; public String name; public static final int TARGET_SELF = 1; public static final int TARGET_SELF_ONLY = 2; public static final int TARGET_PLAYER = 3; public static final int TARGET_PLAYER_ONLY = 4; public static final int TARGET_LOCATION = 5; public static final int TARGET_ALL = 6; public SoundboardPlayer(String name) { this.name = name; } public void play() { Player p = Bukkit.getPlayerExact(name); Player t = targetPlayer == null ? null : Bukkit.getPlayerExact(targetPlayer); if (p == null || (t == null && targetPlayer != null && (target == TARGET_PLAYER || target == TARGET_PLAYER_ONLY)) || effects.size() == 0) return; Random r = new Random(); SoundboardEffect eff = effects.get(r.nextInt(effects.size())); switch (eff.type) { case SOUND: Sound sound = eff.sound; switch (target) { case TARGET_SELF: p.getWorld().playSound(p.getLocation(), sound, 1.0f, 1.0f); break; case TARGET_SELF_ONLY: p.playSound(p.getLocation(), sound, 1.0f, 1.0f); break; case TARGET_PLAYER: t.getWorld().playSound(t.getLocation(), sound, 1.0f, 1.0f); break; case TARGET_PLAYER_ONLY: t.playSound(t.getLocation(), sound, 1.0f, 1.0f); break; case TARGET_LOCATION: p.getWorld().playSound(targetLocation, sound, 1.0f, 1.0f); break; case TARGET_ALL: Player[] players = Bukkit.getOnlinePlayers(); for (Player player : players) player.playSound(player.getLocation(), sound, 1.0f, 1.0f); break; } break; case FIREWORK: Firework firework; switch (target) { case TARGET_SELF: case TARGET_SELF_ONLY: firework = (Firework) p.getWorld().spawnEntity(p.getLocation(), EntityType.FIREWORK); firework.setFireworkMeta(eff.fireworkMeta); break; case TARGET_PLAYER: case TARGET_PLAYER_ONLY: firework = (Firework) p.getWorld().spawnEntity(t.getLocation(), EntityType.FIREWORK); firework.setFireworkMeta(eff.fireworkMeta); break; case TARGET_LOCATION: firework = (Firework) p.getWorld().spawnEntity(targetLocation, EntityType.FIREWORK); firework.setFireworkMeta(eff.fireworkMeta); break; case TARGET_ALL: Player[] players = Bukkit.getOnlinePlayers(); for (Player player : players) { firework = (Firework) p.getWorld().spawnEntity(player.getLocation(), EntityType.FIREWORK); firework.setFireworkMeta(eff.fireworkMeta); } break; } break; } } }
public class MissingLCM { public int getMin(int N) { if(N == 1) { return 2; } int max = 0; boolean[] comp = new boolean[N + 1]; for(int i = 2; i < comp.length; ++i) { if(!comp[i]) { int pow = 1; while(i <= N/pow) { pow *= i; } max = Math.max(max, pow * 2); for(int j = i; j < comp.length; j += i) { comp[j] = true; } } } return max; } }
package com.gome.manager.dao; import com.gome.manager.domain.ManagerUserToken; public interface ManagerUserTokenMapper { int deleteByPrimaryKey(Long id); int insert(ManagerUserToken record); int insertSelective(ManagerUserToken record); ManagerUserToken selectByPrimaryKey(Long id); int updateByPrimaryKeySelective(ManagerUserToken record); int updateByPrimaryKey(ManagerUserToken record); ManagerUserToken selectByUserToken(ManagerUserToken record); }
package com.pelephone_mobile.mypelephone.network.rest.pojos; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; /** * Created by Gali.Issachar on 29/01/14. */ @JsonIgnoreProperties(ignoreUnknown = true) public class CatalogItem extends Pojo implements Comparable<CatalogItem>{ // to map to the property in json @JsonProperty("ID") public String id; // to map to the property in json @JsonProperty("Name") public String name; // to map to the property in json @JsonProperty("Description") public String description; // to map to the property in json @JsonProperty("ImageUrl") public String imageUrl; // to map to the property in json @JsonProperty("TmpBoneId") public int tmpBoneId; // to map to the property in json @JsonProperty("Sort") public int sort; // @@ofirbt - If the given object is null, act as if I'm greater @Override public int compareTo(CatalogItem another) { return (another == null) ? 1 : sort - another.sort; } }
package com.infohold.el.base.utils.excel; import org.apache.poi.ss.usermodel.Row; public interface PoiCallback { boolean HandleDataRow(Row row, Object obj) throws Exception; }
import java.util.ArrayList; import java.util.List; public class Test { public static void main(String[] args) { System.out.println("Hello"); /*********************************************************/ //public Seller(String username, String password) //public SellerList(List<Seller> list) String name1 = "seller1"; String name2 = "seller2"; String name3 = "seller3"; String name4 = "seller4"; String name5 = "seller5"; String pw1 = "123one"; String pw2 = "123two"; String pw3 = "123three"; String pw4 = "123four"; String pw5 = "123five"; Seller seller1 = new Seller(name1, pw1); //Seller seller1 = new Seller(name1, pw1, 1); Seller seller2 = new Seller(name2, pw2); //Seller seller2 = new Seller(name2, pw2, 2); Seller seller3 = new Seller(name3, pw3); //Seller seller3 = new Seller(name3, pw3, 3); Seller seller4 = new Seller(name4, pw4); //Seller seller4 = new Seller(name4, pw4, 4); Seller seller5 = new Seller(name5, pw5); //Seller seller5 = new Seller(name5, pw5, 5); List<Seller> slist = new ArrayList<Seller>(); slist.add(seller1); slist.add(seller2); slist.add(seller3); slist.add(seller4); slist.add(seller5); /*********************************************************/ //public Transportation(int type, int load, int speed, int charge) int truck = 0; int train = 1; int plane = 2; int loadZT1 = 5000; int loadZT2 = 100000; int loadZT3 = 15000; int loadSF1 = 6000; int loadSF2 = 90000; int loadSF3 = 16000; int speedZT1 = 50; int speedZT2 = 80; int speedZT3 = 1000; int speedSF1 = 60; int speedSF2 = 100; int speedSF3 = 1200; int chargeZT1 = 5; int chargeZT2 = 8; int chargeZT3 = 100; int chargeSF1 = 6; int chargeSF2 = 10; int chargeSF3 = 120; int p0SF = 2; //SF首重每公斤计价 int mxSF = 50; //SF首重界限 int p0ZT = 3; int mxZT = 40; List<Transportation> transZT = new ArrayList<Transportation>(); List<Transportation> transSF = new ArrayList<Transportation>(); for (int i = 0; i < 10; i++) transZT.add(new Transportation(truck, loadZT1, speedZT1, chargeZT1, 0)); //transZT.add(new Transportation(i, truck, loadZT1, speedZT1, chargeZT1)); for (int i = 0; i < 5; i++) transZT.add(new Transportation(train, loadZT2, speedZT2, chargeZT2, 0)); for (int i = 0; i < 3; i++) transZT.add(new Transportation(plane, loadZT3, speedZT3, chargeZT3, 0)); for (int i = 0; i < 10; i++) transSF.add(new Transportation(truck, loadSF1, speedSF1, chargeSF1, 0)); //transZT.add(new Transportation(i, truck, loadZT1, speedZT1, chargeZT1)); for (int i = 0; i < 5; i++) transSF.add(new Transportation(train, loadSF2, speedSF2, chargeSF2, 0)); for (int i = 0; i < 3; i++) transSF.add(new Transportation(plane, loadSF3, speedSF3, chargeSF3, 0)); /*********************************************************/ //初始化图 char[] vexs = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K'}; int[][] edges = new int[][]{ {0, 1, 3}, {0, 3, 2}, {0, 5, 4}, {1, 2, 5}, {2, 3, 1}, {4, 6, 4}, {3, 6, 5}, {8, 9, 7}, {9, 6, 8}, }; MatrixNDG roadmapSF1 = new MatrixNDG(vexs, edges); MatrixNDG roadmapSF2 = new MatrixNDG(vexs, edges); MatrixNDG roadmapSF3 = new MatrixNDG(vexs, edges); MatrixNDG roadmapZT1 = new MatrixNDG(vexs, edges); MatrixNDG roadmapZT2 = new MatrixNDG(vexs, edges); MatrixNDG roadmapZT3 = new MatrixNDG(vexs, edges); /*********************************************************/ String SF = "ShunFeng"; String ZT = "ZhongTong"; String SFpw = "SF123"; String ZTpw = "ZT123"; List<Delivery> dl = new ArrayList<Delivery>(); dl.add(new Delivery(SF, SFpw, transSF, roadmapSF1, roadmapSF2, roadmapSF3, p0SF, mxSF)); dl.add(new Delivery(ZT, ZTpw, transZT, roadmapZT1, roadmapZT2, roadmapZT3, p0ZT, mxZT)); Logistics system = new Logistics(dl, slist); /*********************************************************/ for(int i = 0; i < 1; i++) { //public Order(int seller_id, int delivery_id, int transportation_id, int status, int type, int weight, int price) 璁㈠崟 //public Order(int seller_id, int delivery_id, int transportation_id, int status, int type, int weight, int price) 鐠併垹宕? //public Request(int order_id, int seller_id, int type, int weight) final double d = Math.random(); final int du = (int) (d * 1000); // Thread.sleep(du); try { Thread.sleep(du); } catch(InterruptedException e) { System.out.println("got interrupted!"); } final double dd = Math.random(); final int ii = (int) (dd * 5); slist.get(ii).makeRequest(system, 0, 20.2, 'A', 'B', false); slist.get(ii).makeRequest(system, 0, 50.2, 'A', 'B', false); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Controller.Client; import Business.AccountBAL; import Business.RoleBAL; import Entity.Account; import Utility.MD5; import javax.faces.bean.ManagedBean; import javax.faces.bean.RequestScoped; /** * * @author emo */ @ManagedBean(name = "userManagementClient") @RequestScoped public class UserManagerClient { /** Creates a new instance of UserManagerClient */ public UserManagerClient() { } private String redirect = "?faces-redirect=true"; private static Account account; private String roleName; private String errorMessage = "none"; public Account getAccount() { return account; } public void setAccount(Account account) { UserManagerClient.account = account; } public String getErrorMessage() { return errorMessage; } public String addAccount() { account.setPassword(MD5.getInstance().HashMD5(account.getPassword())); account.setRole(RoleBAL.getInstance().getRoleByRoleName(roleName)); if (AccountBAL.getInstance().addAccount(account)) { return "Home" + redirect; } errorMessage = "block"; return "UserManagement" + redirect; } }
package com.defalt.lelangonline.data.items.edit; import android.os.AsyncTask; import androidx.annotation.NonNull; import com.defalt.lelangonline.data.RestApi; import com.defalt.lelangonline.ui.SharedFunctions; import com.defalt.lelangonline.ui.items.edit.ItemsEditActivity; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import okhttp3.MediaType; import okhttp3.RequestBody; import okhttp3.ResponseBody; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class ItemByIDTask extends AsyncTask<String, Void, Void> { private int success; private ItemsEditActivity.ItemsEditUI itemsEditUI; public ItemByIDTask(ItemsEditActivity.ItemsEditUI itemsEditUI) { this.itemsEditUI = itemsEditUI; } protected Void doInBackground(String... args) { RestApi server = SharedFunctions.getRetrofit().create(RestApi.class); RequestBody itemID = RequestBody.create(MediaType.parse("text/plain"), args[0]); Call<ResponseBody> req = server.getItemByID(itemID); req.enqueue(new Callback<ResponseBody>() { @Override public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) { try { if (response.body() != null) { JSONObject json = new JSONObject(response.body().string()); success = json.getInt("success"); if (success == 1) { itemsEditUI.updateEditText(json.getString("itemName"), json.getString("itemCat"), json.getDouble("itemValue"), json.getString("itemDesc"), json.getString("itemImg")); } else { itemsEditUI.showConnError(); } } else { itemsEditUI.showConnError(); } } catch (JSONException | IOException e) { e.printStackTrace(); itemsEditUI.showConnError(); } } @Override public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) { t.printStackTrace(); itemsEditUI.showConnError(); } }); return null; } }
package com.allthelucky.share.sdk; import org.json.JSONObject; import android.app.Activity; import android.os.Bundle; /** * 测试程序 * * @author savant-pan * */ public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ShareErrUtils.init(this); testSina(); // testTecent(); } /** * 新浪微博测试 */ protected void testSina() { boolean flag = ShareManager.hasAuth(MainActivity.this, ShareWebo.SINA); if (flag) {// 如果未授权,测进入授权界面,否则发布新微博 ShareParams shareParams = new ShareParams(); shareParams.put("status", "hello,world"); ShareManager.addWeibo(MainActivity.this, ShareWebo.SINA, shareParams, new ShareListener() { @Override public void onStart() { } @Override public void onResult(int code, String result) { System.out.println("status:" + code + ",result:" + result); JSONObject object = Utils.stringToJSONObject(result); if (object != null) { ShareErrUtils.getMessage(ShareWebo.SINA, object.optInt("error_code")); } else { //failed } } }); } } /** * QQ微博测试 */ protected void testTecent() { boolean flag = ShareManager.hasAuth(MainActivity.this, ShareWebo.TECENT); if (flag) {// 如果未授权,测进入授权界面,否则发布新微博 ShareParams shareParams = new ShareParams(); shareParams.put("content", "hello,world"); shareParams.put("format", "json"); ShareManager.addWeibo(MainActivity.this, ShareWebo.TECENT, shareParams, new ShareListener() { @Override public void onStart() { } @Override public void onResult(int code, String result) { System.out.println("status:" + code + ",result:" + result); JSONObject object = Utils.stringToJSONObject(result); if (object != null) { ShareErrUtils.getMessage(ShareWebo.TECENT, object.optInt("error_code")); } } }); } } }
import java.util.ArrayList; import java.util.Random; import static java.lang.Math.exp; import static java.lang.Math.pow; public class Populacao { public ArrayList<Individuos> individuos; public Populacao() { this.individuos=new ArrayList<>(); } public double fun(double X, double Y){ return (0.97 * exp(-(pow(X + 3,2) + pow(Y + 3,2)) / 5) + 0.98 * exp(-(pow(X + 3,2) + pow(Y - 3,2)) / 5) + 0.99 * exp(-(pow(X - 3,2) + pow(Y + 3,2))/ 5) + 1.0 * exp(-(pow(X - 3 , 2) + pow(Y - 3,2))/ 5)); } public Populacao(int qtd, double max, double min){ this.individuos = new ArrayList<>(); for (int i=0;i<qtd;i++){ Random gerador = new Random(); double x = min + (Math.random() * (max - min)); double y = min + (Math.random() * (max - min)); this.individuos.add(new Individuos(x,y,fun(x,y))); } } public void printPopulaca(){ int c=0; for (Individuos i:this.individuos) { System.out.println(c+" "+i.x+" "+i.y+" "+i.resp); c++; } } public double var(){ calc c= new calc(); return c.variancia(this.individuos); } }
package com.huaxiao47.just4fun.ui.home.recommend; import androidx.appcompat.widget.LinearLayoutCompat; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProviders; import android.app.Activity; import android.content.Context; import android.graphics.Rect; import android.os.Bundle; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.swiperefreshlayout.widget.SwipeRefreshLayout; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.huaxiao47.just4fun.R; //推荐主界面 public class HomeRecommendFragment extends Fragment { private static final String TAG ="HomeRecommendFragment"; private HomeRecommendViewModel mViewModel; private SwipeRefreshLayout mRefreshLayout; private RecommendRecyclerViewAdapter adapter; private RecyclerView mRecyclerView; private Context mContext; public static HomeRecommendFragment newInstance() { return new HomeRecommendFragment(); } @Override public void onAttach(@NonNull Context context) { super.onAttach(context); mContext = context; } @Override public void onDetach() { super.onDetach(); mContext = null; } @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View root = inflater.inflate(R.layout.home_recommend_fragment, container, false); mRefreshLayout = root.findViewById(R.id.swipe_refresh); mRecyclerView = root.findViewById(R.id.recycler_view); initRefreshLayout(); initRecyclerView(); return root; } private void initRefreshLayout() { mRefreshLayout.setColorSchemeResources( R.color.materialBlue, R.color.colorAccent, R.color.colorPrimary); mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { } }); } private void initRecyclerView() { LinearLayoutManager manager = new LinearLayoutManager(mContext); manager.setOrientation(LinearLayoutManager.VERTICAL); GridLayoutManager gridLayoutManager = new GridLayoutManager(mContext,2); gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() { @Override public int getSpanSize(int position) { if (position ==0) return 2; return 1; } }); mRecyclerView.setLayoutManager(gridLayoutManager); mRecyclerView.addItemDecoration(new SpacesItemDecoration(10)); adapter = new RecommendRecyclerViewAdapter(); mRecyclerView.setAdapter(adapter); mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); } }); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mViewModel = ViewModelProviders.of(this).get(HomeRecommendViewModel.class); } @Override public void onResume() { super.onResume(); mViewModel.getInfos().observe(this, new Observer<RecommendInfo>() { @Override public void onChanged(RecommendInfo recommendInfo) { adapter.setNewData(recommendInfo); Log.d(TAG, "onChanged: "+recommendInfo.items.size()); } }); mViewModel.loadData(); } class SpacesItemDecoration extends RecyclerView.ItemDecoration { private int space; public SpacesItemDecoration(int space) { this.space = space; } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { outRect.left = space; outRect.right = space; outRect.bottom = space; // Add top margin only for the first item to avoid double space between items if (parent.getChildLayoutPosition(view) == 0) { outRect.top = space; } else { outRect.top = 0; } } } }
package com.example.bob.health_helper; import android.app.Application; import android.content.Context; import android.os.Build; import com.example.bob.health_helper.Base.AppConstant; import com.iflytek.cloud.SpeechConstant; import com.iflytek.cloud.SpeechUtility; import com.lifesense.ble.LsBleManager; import com.orhanobut.logger.AndroidLogAdapter; import com.orhanobut.logger.Logger; import com.tencent.imsdk.TIMManager; import com.tencent.imsdk.session.SessionWrapper; import com.tencent.qcloud.uikit.BaseUIKitConfigs; import com.tencent.qcloud.uikit.IMEventListener; import com.tencent.qcloud.uikit.TUIKit; import com.tencent.qcloud.uikit.common.utils.UIUtils; import com.tencent.tauth.Tencent; import com.xiaomi.mipush.sdk.MiPushClient; import java.util.Locale; import static com.example.bob.health_helper.Constants.MI_PUSH_APP_ID; import static com.example.bob.health_helper.Constants.MI_PUSH_APP_KEY; public class MyApplication extends Application { private static Context context; private static Tencent tencent; @Override public void onCreate() { super.onCreate(); //方便一般类获取上下文 context=getApplicationContext(); //qq登录初始化 tencent=Tencent.createInstance(AppConstant.QQ_APPID,context); //科大讯飞 SpeechUtility.createUtility(this, SpeechConstant.APPID+"="+AppConstant.IFLYKE_APPID); //Logger Logger.addLogAdapter(new AndroidLogAdapter()); registerPush(); //初始化 SDK 基本配置 //判断是否是在主线程 if (SessionWrapper.isMainProcess(getApplicationContext())) { /** * TUIKit的初始化函数 * * @param context 应用的上下文,一般为对应应用的ApplicationContext * @param sdkAppID 您在腾讯云注册应用时分配的sdkAppID * @param configs TUIKit的相关配置项,一般使用默认即可,需特殊配置参考API文档 */ long current = System.currentTimeMillis(); TUIKit.init(this, Constants.sdkAppId, BaseUIKitConfigs.getDefaultConfigs()); System.out.println(">>>>>>>>>>>>>>>>>>"+(System.currentTimeMillis()-current)); //添加自定初始化配置 customConfig(); System.out.println(">>>>>>>>>>>>>>>>>>"+(System.currentTimeMillis()-current)); // 设置离线推送监听器 TIMManager.getInstance().setOfflinePushListener(notification -> notification.doNotify(getApplicationContext(), R.drawable.ic_launcher)); } //init LsBleManager LsBleManager.getInstance().initialize(getApplicationContext()); //register bluetooth broadacst receiver LsBleManager.getInstance().registerBluetoothBroadcastReceiver(getApplicationContext()); //register message service if need LsBleManager.getInstance().registerMessageService(); } public static Context getContext(){ return context; } public static Tencent getTencent(){return tencent;} private void customConfig() { if (TUIKit.getBaseConfigs() != null) { //注册IM事件回调,这里示例为用户被踢的回调,更多事件注册参考文档 TUIKit.getBaseConfigs().setIMEventListener(new IMEventListener() { @Override public void onForceOffline() { UIUtils.toastLongMessage("您的账号已在其它终端登录"); } }); } } public void registerPush(){ String vendor = Build.MANUFACTURER; if(vendor.toLowerCase(Locale.ENGLISH).contains("xiaomi")) { //注册小米推送服务 MiPushClient.registerPush(this, MI_PUSH_APP_ID, MI_PUSH_APP_KEY); }else if(vendor.toLowerCase(Locale.ENGLISH).contains("huawei")) { //请求华为推送设备 token //PushManager.requestToken(this); } } }
package br.com.lucro.server.controller; import java.util.Calendar; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.ResponseStatus; import br.com.lucro.server.model.WebResponse; import br.com.lucro.server.model.WebResponseException; import br.com.lucro.server.util.enums.EnumWebResponse; /** * This controller manage and handle any exceptions from the base package * @author Georjuan Taylor * */ @ControllerAdvice(basePackages="br.com.lucro.server") public class ExceptionController { @SuppressWarnings("unused") @Autowired private HttpSession session; @Autowired private HttpServletRequest request; private static final Logger logger = Logger.getLogger(ExceptionController.class); @ResponseBody @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(WebResponseException.class) public WebResponse handleError(WebResponseException exception) { //Log logError(exception); //Create web response object WebResponse web = new WebResponse(); web.setDatetime(Calendar.getInstance().getTime()); web.setStatus(exception.getResponseType()); web.setMessage(exception.getMessage()); return web; } @ResponseBody @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(Exception.class) public WebResponse handleError(Exception exception) { //Log logError(exception); //Create web response object WebResponse web = new WebResponse(); web.setDatetime(Calendar.getInstance().getTime()); web.setStatus(EnumWebResponse.ERROR); web.setMessage(exception.getMessage()); return web; } private void logError(Exception e){ try{ Class<?> eClass = Class.forName(e.getStackTrace()[0].getClassName()); if(eClass.getPackage().getName().startsWith("br.com.expark.webcontrol")){ //It's exception from this project, just log //From here logger.error("Request: " + request.getRequestURL() + " raised: " + e); }else{ //It's exception from external library, log from external library, and from here //From external LoggerFactory.getLogger(Class.forName(e.getStackTrace()[0].getClassName())) .error("Request: " + request.getRequestURL() + " raised: " + e); //From here logger.error("Request: " + request.getRequestURL() + " raised: " + e); } }catch(Exception ex){ logger.error(e.getMessage()); } } private void logError(WebResponseException e){ try{ Class<?> eClass = Class.forName(e.getStackTrace()[0].getClassName()); if(eClass.getPackage().getName().startsWith("br.com.expark.webcontrol")){ //It's exception from this project, just log //From here logger.error("Request: " + request.getRequestURL() + " raised: " + e.getResponseType() + " - " + e); }else{ //It's exception from external library, log from external library, and from here //From external LoggerFactory.getLogger(Class.forName(e.getStackTrace()[0].getClassName())) .error("Request: " + request.getRequestURL() + " raised: " + e.getResponseType() + " - " + e); //From here logger.error("Request: " + request.getRequestURL() + " raised: " + e.getResponseType() + " - " + e); } }catch(Exception ex){ logger.error(e.getMessage()); } } }
package com.git.cloud.appmgt.model; /** * 应用管理的枚举类 * @author liangshuang * @date 2014-9-23 下午5:25:33 * @version v1.0 * */ public enum AppMgtEnum { DIC_TYPE_CODE_DU_SERVICE_TYPE("DU_SEV_TYPE"),//服务器角色服务类型 DIC_TYPE_CODE_USE_STATUS("USE_STATUS");//服务器角色服务状态 private final String value; private AppMgtEnum(String value){ this.value=value; } public String getValue() { return value; } public static AppMgtEnum fromString(String value ) { if (value != null) { for (AppMgtEnum c : AppMgtEnum.values()) { if (value.equalsIgnoreCase(c.value)) { return c; } } } return null; } }
package alien4cloud.json.deserializer; import alien4cloud.model.components.AbstractPropertyValue; import alien4cloud.model.components.ComplexPropertyValue; import alien4cloud.model.components.FunctionPropertyValue; import alien4cloud.model.components.ListPropertyValue; import alien4cloud.model.components.ScalarPropertyValue; import com.fasterxml.jackson.databind.node.JsonNodeType; /** * Custom deserializer to handle multiple IOperationParameter types. */ public class PropertyValueDeserializer extends AbstractDiscriminatorPolymorphicDeserializer<AbstractPropertyValue> { public PropertyValueDeserializer() { super(AbstractPropertyValue.class); addToRegistry("function", FunctionPropertyValue.class); addToRegistry("value", JsonNodeType.STRING.toString(), ScalarPropertyValue.class); addToRegistry("value", JsonNodeType.ARRAY.toString(), ListPropertyValue.class); addToRegistry("value", JsonNodeType.OBJECT.toString(), ComplexPropertyValue.class); setValueStringClass(ScalarPropertyValue.class); } }
package com.csalazar.formularioventas.holder; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.csalazar.formularioventas.R; /** * Created by csalazar on 28/09/2017. */ public class ItemHolderCliente extends RecyclerView.ViewHolder { private ImageView imageView; private TextView textViewNombre; private TextView textViewDireccion; private TextView textViewTelefono; private String numeroFormulario; public ItemHolderCliente(View itemView) { super(itemView); imageView = itemView.findViewById(R.id.iv_imagen_cliente); textViewNombre = itemView.findViewById(R.id.tv_nombre_cliente); textViewDireccion = itemView.findViewById(R.id.tv_direccion_cliente); textViewTelefono = itemView.findViewById(R.id.tv_telefono_cliente); } public void setDataCliente(String numFormulario, String labelNombre, String labelDireccion, String labelTelefono){ numeroFormulario = numFormulario; textViewNombre.setText(labelNombre); textViewDireccion.setText(labelDireccion); textViewTelefono.setText(labelTelefono); } }
package com.foodaholic.asyncTask; import android.os.AsyncTask; import com.foodaholic.interfaces.FoodofthedayListener; import com.foodaholic.items.ItemMenu; import com.foodaholic.items.ItemRestaurant; import com.foodaholic.utils.Constant; import com.foodaholic.utils.JsonUtils; import org.json.JSONArray; import org.json.JSONObject; import java.util.ArrayList; public class LoadFoodoftheday extends AsyncTask<String, String, Boolean> { private FoodofthedayListener foodofthedayListener; private ArrayList<ItemMenu> foods; public LoadFoodoftheday(FoodofthedayListener foodofthedayListener) { this.foodofthedayListener = foodofthedayListener; this.foods = new ArrayList<>(); } @Override protected void onPreExecute() { super.onPreExecute(); foodofthedayListener.onStart(); } @Override protected Boolean doInBackground(String... strings) { String url = strings[0]; String json = JsonUtils.okhttpGET(url); try { JSONObject jOb = new JSONObject(json); JSONArray jsonArray = jOb.getJSONArray(Constant.TAG_ROOT); for (int j = 0; j < jsonArray.length(); j++) { JSONObject jsonObject = jsonArray.getJSONObject(j); String menu_id = jsonObject.getString(Constant.TAG_MENU_ID); String menu_name = jsonObject.getString(Constant.TAG_MENU_NAME); String menu_type = jsonObject.getString(Constant.TAG_MENU_TYPE); String desc = jsonObject.getString(Constant.TAG_MENU_DESC); String price = jsonObject.getString(Constant.TAG_MENU_PRICE); String menu_image = jsonObject.getString(Constant.TAG_MENU_IMAGE); String cat_id = ""; String res_id = jsonObject.getString(Constant.TAG_MENU_REST_ID); JSONObject rest_obj = jsonObject.getJSONObject(Constant.TAG_REST_ROOT); String rest_id = rest_obj.getString(Constant.TAG_ID); String name = rest_obj.getString(Constant.TAG_REST_NAME); String address = rest_obj.getString(Constant.TAG_REST_ADDRESS); String rest_image = rest_obj.getString(Constant.TAG_REST_IMAGE); String type = rest_obj.getString(Constant.TAG_REST_TYPE); float avg_Rate = Float.parseFloat(rest_obj.getString(Constant.TAG_REST_AVG_RATE)); int total_rate = Integer.parseInt(rest_obj.getString(Constant.TAG_REST_TOTAL_RATE)); String cat_name = ""; String open = rest_obj.getString(Constant.TAG_REST_OPEN); ItemRestaurant itemRestaurant = new ItemRestaurant(rest_id,name,rest_image,type,address,avg_Rate,total_rate, cat_name, open); ItemMenu itemMenu = new ItemMenu(menu_id, menu_name, menu_type, menu_image, desc, price, res_id, cat_id, itemRestaurant); foods.add(itemMenu); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } @Override protected void onPostExecute(Boolean aBoolean) { super.onPostExecute(aBoolean); foodofthedayListener.onEnd(String.valueOf(aBoolean), foods); } }
package src.modulo2.exercicios; import com.sun.opengl.util.Animator; import java.awt.Frame; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import javax.media.opengl.GL; import javax.media.opengl.GLAutoDrawable; import javax.media.opengl.GLCanvas; import javax.media.opengl.GLEventListener; import javax.media.opengl.glu.GLU; /** * Exercicio03.java <BR> * author: Brian Paul (converted to Java by Ron Cemer and Sven Goethel) <P> * * This version is equal to Brian Paul's version 1.2 1999/10/21 */ public class Exercicio03 implements GLEventListener { public static void main(String[] args) { Frame frame = new Frame("Exercicio 03 - Grafico"); GLCanvas canvas = new GLCanvas(); canvas.addGLEventListener(new Exercicio03()); frame.add(canvas); frame.setSize(640, 480); final Animator animator = new Animator(canvas); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { // Run this on another thread than the AWT event queue to // make sure the call to Animator.stop() completes before // exiting new Thread(new Runnable() { public void run() { animator.stop(); System.exit(0); } }).start(); } }); // Center frame frame.setLocationRelativeTo(null); frame.setVisible(true); animator.start(); } public void init(GLAutoDrawable drawable) { // Use debug pipeline // drawable.setGL(new DebugGL(drawable.getGL())); GL gl = drawable.getGL(); System.err.println("INIT GL IS: " + gl.getClass().getName()); // Enable VSync gl.setSwapInterval(1); // Setup the drawing area and shading mode gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f); //Cor de fundo branco gl.glColor3f(0.0f, 0.0f, 0.0f); //Cor do desenho gl.glPointSize(4.0f); //um ponto eh 4 x 4 pixels gl.glLineWidth(2.0f); gl.glShadeModel(GL.GL_FLAT); } public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) { GL gl = drawable.getGL(); GLU glu = new GLU(); if (height <= 0) { // avoid a divide by zero error! height = 1; } final float h = (float) width / (float) height; gl.glViewport(0, 0, width, height); gl.glMatrixMode(GL.GL_PROJECTION); gl.glLoadIdentity(); glu.gluOrtho2D(0.0f, 640.0f, 0.0f, 480.0f); gl.glMatrixMode(GL.GL_MODELVIEW); gl.glLoadIdentity(); } public void display(GLAutoDrawable drawable) { GL gl = drawable.getGL(); // Clear the drawing area gl.glClear(GL.GL_COLOR_BUFFER_BIT); // Reset the current matrix to the "identity" gl.glLoadIdentity(); gl.glBegin(GL.GL_LINE_STRIP); //GL_POINTS ,GL_LINE_STRIP for(double x = 0; x < 640 ; x++) { //GL.GL_DOUBLE func = 0.25*(x-319)*(x-319); System.out.println("x - " + x + " - func(x) = " + function(x)); gl.glVertex2d(x, function(x) + 200); } gl.glEnd(); gl.glBegin(GL.GL_LINES); //GL_POINTS ,GL_LINE_STRIP gl.glVertex2d(0,200); gl.glVertex2d(640,200); gl.glEnd(); // Flush all drawing operations to the graphics card gl.glFlush(); } public double function(double x){ System.out.println("(150 * " + Math.sin(2 * 3.14 * x * 15 / 640)); //return (int) (0.25*(x-319)*(x-319)); return (double) (150 * Math.sin(2 * 3.14 * x * 15 / 640)); } public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) { } }
import java.io.BufferedReader; import java.io.InputStreamReader; class Stack { private char[] stackArray = null; private int maxSize = 5; private int top; public Stack() { this.stackArray = new char[maxSize]; top = -1; } public Stack(int maxSize) { this.maxSize = maxSize; this.stackArray = new char[maxSize]; top = -1; } public void push(char data) { if (!isFull()) { stackArray[++top] = data; System.out.println("[INFO]: " + data + " pushed onto the stack"); return; } else { System.out.println("[INFO]: Pushing " + data); System.err.println("\n[ERROR]: StackOverflow : " + data + " couldn't be pushed because stack size is maximum " + maxSize + ".\n"); } } public char peek() { try { return stackArray[top]; } catch (Exception e) { System.out.println(e.getMessage()); return '\0'; } } public char pop() { // System.out.println("top = " + top); char poppedElement = '\0'; if (!(isEmpty())) { // System.out.println("[INFO]: Poping " + peek() + " from the stack"); poppedElement = stackArray[top--]; System.out.println("[INFO]: popped element : " + poppedElement); } else { System.out.println("[INFO]: poping from the stack"); System.err.println("[ERROR]: Stack Underflow - not able to pop, stack is already empty"); } return poppedElement; } public int stackSize() { return top + 1; } public boolean isFull() { return (top + 1 == maxSize); } public boolean isEmpty() { return (top == -1); } public void displayStack() { System.out.println("\nCURRENT STACK VIEW"); System.out.println("----------------------------------------"); System.out.print("TOP > "); if (!isEmpty()) { for (int i = top; i >= 0; i--) { System.out.print(stackArray[i]); System.out.print(" "); } System.out.println("> BOTTOM"); return; } System.out.println("Stack is empty. Nothing to display :( "); } public String convertToString() { String str = ""; if (!isEmpty()) { for (int i = top; i >= 0; i--) { // System.out.print(stackArray[i]); str += stackArray[i]; } } return str; } } public class BracketChecker { public static void main(String[] args) { // String str = "a{b[c(f)}]d}e("; String str = "((2+4)*7)+3*(9–5)"; char[] delimiters = { '{', '}', '[', ']', '(', ')' }; char[] delimitersOpening = { '{', '[', '(' }; char[] delimitersClosing = { '}', ']', ')' }; int strLen = str.length(); Stack stack1 = new Stack(str.length()); char ch, poppedChar; for (int i = 0; i < strLen; i++) { ch = str.charAt(i); if (new String(delimitersOpening).indexOf(ch) != -1) { stack1.push(ch); } if (new String(delimitersClosing).indexOf(ch) != -1) { System.out.println("[INFO]: next character in string is " + ch); poppedChar = stack1.pop(); int dIndex = new String(delimitersOpening).indexOf(poppedChar); // System.out.println(dIndex); if(!stack1.isEmpty()){ if (ch == delimitersClosing[dIndex] && poppedChar == delimitersOpening[dIndex]) { System.out.println("[INFO]: " + delimitersOpening[dIndex] + " and " + delimitersClosing[dIndex] + " matched"); } else { System.err.println("\n[ERROR]: Should be " + delimitersClosing[dIndex] + " but " + ch + " found \n" ); } } } } stack1.displayStack(); if (!stack1.isEmpty()) System.out.println("\nBad String because good string keeps stack empty in the end!"); else System.out.println("\nGOOD STRING."); } public static String getString() { String str = ""; try { InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); str = br.readLine(); } catch (Exception e) { System.err.println(e.getMessage()); } return str; } }
package com.csc.capturetool.myapplication.utils.xml; public interface XmlEditorInter { /** * 保存 key-value键值 */ public EditorInter edit(); /** * 获取key对应的int值 * @param key 数值key名称 * @param defaultValue int默认值 * @return key对应的int值 */ public int getInt(String key, int defaultValue); /** * 获取key对应的String值 * @param key 数值key名称 * @return key对应的String值 */ public String getString(String key); /** * 获取key对应的bool值 * @param key 数值key名称 * @param defaultValue bool默认值 * @return key对应的boolean值 */ public boolean getBoolean(String key, boolean defaultValue); /** * 获取key对应的long值 * @param key 数值key名称 * @param defaultValue long默认值 * @return key对应的long值 */ public long getLong(String key, long defaultValue); /** * 获取key对应的float值 * @param key 数值key名称 * @param defaultValue float默认值 * @return key对应的float值 */ public float getFloat(String key, float defaultValue); /** * 获取key对应的double值 * @param key 数值key名称 * @param defaultValue double默认值 * @return key对应的double值 */ public double getDouble(String key, double defaultValue); }
package com.xh.image; import java.net.URL; import android.graphics.Bitmap; import android.view.View; import com.xh.image.display.XhScreenDisplay; import com.xh.util.XhImageUtile; import com.xh.util.XhLog; /** * @version 创建时间:2017-11-20 下午3:04:57 项目:XhlackAD-eclipse 包名:com.Xhlack.tv.image * 文件名:XhViewAware.java 作者:lhl 说明:普通视图处理器,用于背景处理 */ public class XhViewAware extends XhAware { public XhViewAware(View view, URL url, int width, int height, String savePath, long savaTime) { super(view, url, width, height, savePath, savaTime); // TODO Auto-generated constructor stub } @Override void setViewBitmap(Bitmap bitmap) { // TODO Auto-generated method stub View view = getView(); if (view == null) return; if (display instanceof XhScreenDisplay) { XhScreenDisplay screenDisplay = (XhScreenDisplay) display; int height = getHeight(); int width = getWidth(); screenDisplay.setHeight(height); screenDisplay.setWidth(width); view.setBackground(XhImageUtile.bitmap2drawable(display .deal(screenDisplay.deal(bitmap)))); } else view.setBackground(XhImageUtile.bitmap2drawable(display .deal(bitmap))); } }
package me.sh4rewith.persistence.mongo; import static me.sh4rewith.persistence.mongo.mappers.AbstractMongoDocumentMapper.MONGO_DOC_ID; import static me.sh4rewith.persistence.mongo.mappers.RawFileInfoMapper.CONTENT_TYPE; import static me.sh4rewith.persistence.mongo.mappers.RawFileInfoMapper.INFO_SUFFIX; import static me.sh4rewith.persistence.mongo.mappers.RawFileInfoMapper.ORIGINAL_FILE_NAME; import static me.sh4rewith.persistence.mongo.mappers.RawFileInfoMapper.RAW_FILE_INFO_STORENAME; import static me.sh4rewith.persistence.mongo.mappers.RawFileInfoMapper.SIZE; import static me.sh4rewith.persistence.mongo.mappers.RawFileMapper.STORAGE_COORDINATES; import static me.sh4rewith.persistence.mongo.mappers.RawFileMapper.RAW_FILE_STORENAME; import static me.sh4rewith.persistence.mongo.mappers.SharedFileFootprintMapper.CREATION_DATE; import static me.sh4rewith.persistence.mongo.mappers.SharedFileFootprintMapper.EXPIRATION_DATE; import static me.sh4rewith.persistence.mongo.mappers.SharedFileFootprintMapper.RAW_FILE_ID; import static me.sh4rewith.persistence.mongo.mappers.SharedFileFootprintMapper.SHARED_FILE_FOOTPRINT_STORENAME; import static me.sh4rewith.persistence.mongo.mappers.SharedFileFootprintMapper.SHARED_FILE_INFO_ID; import static me.sh4rewith.persistence.mongo.mappers.SharedFileInfoMapper.BUDDIES_LIST; import static me.sh4rewith.persistence.mongo.mappers.SharedFileInfoMapper.DESCRIPTION; import static me.sh4rewith.persistence.mongo.mappers.SharedFileInfoMapper.OWNER; import static me.sh4rewith.persistence.mongo.mappers.SharedFileInfoMapper.PRIVACY_TYPE; import static me.sh4rewith.persistence.mongo.mappers.SharedFileInfoMapper.SHARED_FILE_INFO_STORENAME; import java.util.Arrays; import java.util.Date; import java.util.List; import javax.annotation.Nullable; import me.sh4rewith.domain.Privacy; import me.sh4rewith.domain.Privacy.Type; import me.sh4rewith.domain.RawFile; import me.sh4rewith.domain.RawFileInfo; import me.sh4rewith.domain.SharedFile; import me.sh4rewith.domain.SharedFileDescriptor; import me.sh4rewith.domain.SharedFileFootprint; import me.sh4rewith.domain.SharedFileInfo; import me.sh4rewith.persistence.SharedFilesRepository; import me.sh4rewith.persistence.mongo.mappers.RawFileInfoMapper; import me.sh4rewith.persistence.mongo.mappers.RawFileMapper; import me.sh4rewith.persistence.mongo.mappers.SharedFileFootprintMapper; import me.sh4rewith.persistence.mongo.mappers.SharedFileInfoMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Profile; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Order; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.stereotype.Service; import com.google.common.base.Function; import com.google.common.collect.Lists; @Service @Profile("init-mongo,wipe-mongo,local-mongo,prod-mongo,remote-mongo") public class MongoSharedFileRepository implements SharedFilesRepository { @Autowired MongoTemplate mongo; @Override public void store(SharedFile sharedFile) { saveRawFile(sharedFile.getRawFile()); saveRawFileInfo(sharedFile.getRawFileInfo()); saveSharedFileInfo(sharedFile.getInfo()); saveFootprint(sharedFile.getFootprint()); } @Override public List<SharedFile> findAll() { SharedFileFootprintMapper footprintMapper = new SharedFileFootprintMapper(); mongo.executeQuery(new Query(Criteria.where(MONGO_DOC_ID).regex(".*")), SHARED_FILE_FOOTPRINT_STORENAME, footprintMapper); List<SharedFileFootprint> footPrints = footprintMapper .getFootprintList(); return Lists.transform(footPrints, new Function<SharedFileFootprint, SharedFile>() { @Override public SharedFile apply( @Nullable SharedFileFootprint footPrint) { if (footPrint == null) return null; SharedFile sharedFile = getSharedFileFromFootprint(footPrint); return sharedFile; } }); } @Override public List<SharedFileDescriptor> findAllDescriptors() { SharedFileFootprintMapper footprintMapper = new SharedFileFootprintMapper(); Query query = new Query(Criteria.where(MONGO_DOC_ID).regex(".*")); query.sort().on(CREATION_DATE, Order.DESCENDING); mongo.executeQuery(query, SHARED_FILE_FOOTPRINT_STORENAME, footprintMapper); List<SharedFileFootprint> footPrints = footprintMapper .getFootprintList(); return Lists.transform(footPrints, new Function<SharedFileFootprint, SharedFileDescriptor>() { @Override public SharedFileDescriptor apply( @Nullable SharedFileFootprint footPrint) { if (footPrint == null) return null; SharedFileDescriptor sharedFileDescriptor = getSharedFileDescriptorFromFootprint(footPrint); return sharedFileDescriptor; } }); } @Override public SharedFile getSharedFileByFootprintId(String footprintId) { SharedFileFootprintMapper footprintMapper = new SharedFileFootprintMapper(); mongo.executeQuery( new Query(Criteria.where(MONGO_DOC_ID).is(footprintId)), SHARED_FILE_FOOTPRINT_STORENAME, footprintMapper); SharedFile doc = getSharedFileFromFootprint(footprintMapper .getFootprint()); return doc; } @Override public void deleteByFootprintId(String footprint) { SharedFileFootprintMapper footprintMapper = new SharedFileFootprintMapper(); final Query footprintQuery = new Query(Criteria.where(MONGO_DOC_ID).is( footprint)); mongo.executeQuery(footprintQuery, SHARED_FILE_FOOTPRINT_STORENAME, footprintMapper); SharedFileFootprint sharedFileFootprint = footprintMapper .getFootprint(); final Query rawFileQuery = new Query(Criteria.where(MONGO_DOC_ID).is( sharedFileFootprint.getRawFileId())); final Query rawFileInfoQuery = new Query(Criteria.where(MONGO_DOC_ID) .is(sharedFileFootprint.getRawFileId() + "-info")); final Query sharedFileInfoQuery = new Query(Criteria .where(MONGO_DOC_ID).is( sharedFileFootprint.getSharedFileInfoId())); mongo.remove(rawFileQuery, RAW_FILE_STORENAME); mongo.remove(rawFileInfoQuery, RAW_FILE_INFO_STORENAME); mongo.remove(sharedFileInfoQuery, SHARED_FILE_INFO_STORENAME); mongo.remove(footprintQuery, SHARED_FILE_FOOTPRINT_STORENAME); } @Override public List<SharedFileDescriptor> getPublicStream(String buddyId) { SharedFileInfoMapper sharedFileInfoMapper = new SharedFileInfoMapper(); Query query = new Query(Criteria.where(MONGO_DOC_ID).regex(".*") .and(PRIVACY_TYPE).is(Privacy.Type.PUBLIC.name())); mongo.executeQuery(query, SHARED_FILE_INFO_STORENAME, sharedFileInfoMapper); List<SharedFileInfo> infoList = sharedFileInfoMapper .getSharedFileInfoList(); return Lists.transform(infoList, new Function<SharedFileInfo, SharedFileDescriptor>() { @Override public SharedFileDescriptor apply( @Nullable SharedFileInfo sharedFileInfo) { if (sharedFileInfo == null) return null; SharedFileFootprintMapper footprintMapper = new SharedFileFootprintMapper(); final Query footprintQuery = new Query(Criteria.where( SHARED_FILE_INFO_ID).is(sharedFileInfo.getId())); footprintQuery.sort().on(CREATION_DATE, Order.DESCENDING); mongo.executeQuery(footprintQuery, SHARED_FILE_FOOTPRINT_STORENAME, footprintMapper); SharedFileDescriptor sharedFileDescriptor = getSharedFileDescriptorFromFootprint(footprintMapper .getFootprint()); return sharedFileDescriptor; } }); } @Override public List<SharedFileDescriptor> getPersonalStream(String buddyId) { SharedFileInfoMapper sharedFileInfoMapper = new SharedFileInfoMapper(); Query query = new Query( new Criteria().andOperator( Criteria.where(MONGO_DOC_ID).regex(".*") .and(PRIVACY_TYPE) .ne(Privacy.Type.PUBLIC.name()), new Criteria().orOperator( Criteria.where(OWNER).is(buddyId), Criteria.where(BUDDIES_LIST).is(buddyId)) )); mongo.executeQuery(query, SHARED_FILE_INFO_STORENAME, sharedFileInfoMapper); List<SharedFileInfo> infoList = sharedFileInfoMapper .getSharedFileInfoList(); return Lists.transform(infoList, new Function<SharedFileInfo, SharedFileDescriptor>() { @Override public SharedFileDescriptor apply( @Nullable SharedFileInfo sharedFileInfo) { if (sharedFileInfo == null) return null; SharedFileFootprintMapper footprintMapper = new SharedFileFootprintMapper(); final Query footprintQuery = new Query(Criteria.where( SHARED_FILE_INFO_ID).is(sharedFileInfo.getId())); footprintQuery.sort().on(CREATION_DATE, Order.DESCENDING); mongo.executeQuery(footprintQuery, SHARED_FILE_FOOTPRINT_STORENAME, footprintMapper); SharedFileDescriptor sharedFileDescriptor = getSharedFileDescriptorFromFootprint(footprintMapper .getFootprint()); return sharedFileDescriptor; } }); } @Override public SharedFileInfo findSharedFileInfoById(String sharedFileInfoId) { SharedFileInfoMapper mapper = new SharedFileInfoMapper(); mongo.executeQuery( new Query(Criteria.where(MONGO_DOC_ID).is(sharedFileInfoId)), SHARED_FILE_INFO_STORENAME, mapper); return mapper.getSharedFileInfo(); } @Override public void turnPublic(SharedFileInfo sharedFileInfo) { turn(Privacy.Type.PUBLIC, sharedFileInfo); } @Override public void turnPrivate(SharedFileInfo sharedFileInfo) { turn(Privacy.Type.PRIVATE, sharedFileInfo); } @Override public void turnProtected(SharedFileInfo sharedFileInfo) { turn(Privacy.Type.PROTECTED, sharedFileInfo); } @Override public SharedFileInfo findSharedFileInfoByFootprintId( String sharedFileFootprintId) { SharedFileFootprintMapper footprintMapper = new SharedFileFootprintMapper(); final Query footprintQuery = new Query(Criteria.where(MONGO_DOC_ID).is( sharedFileFootprintId)); mongo.executeQuery(footprintQuery, SHARED_FILE_FOOTPRINT_STORENAME, footprintMapper); SharedFileFootprint sharedFileFootprint = footprintMapper .getFootprint(); return getSharedFileDescriptorFromFootprint(sharedFileFootprint) .getInfo(); } @Override public Long countAll() { return mongo.count(new Query(Criteria.where(MONGO_DOC_ID).regex(".*")), SHARED_FILE_FOOTPRINT_STORENAME); } private void saveFootprint(SharedFileFootprint footprint) { final Query footPrintQuery = new Query(Criteria.where(MONGO_DOC_ID).is( footprint.getId())); mongo.upsert(footPrintQuery, new Update().set(MONGO_DOC_ID, footprint.getId()), SHARED_FILE_FOOTPRINT_STORENAME); mongo.upsert(footPrintQuery, new Update().set(SharedFileFootprintMapper.RAW_FILE_ID, footprint.getRawFileId()), SHARED_FILE_FOOTPRINT_STORENAME); mongo.upsert( footPrintQuery, new Update().set(SHARED_FILE_INFO_ID, footprint.getSharedFileInfoId()), SHARED_FILE_FOOTPRINT_STORENAME); mongo.upsert(footPrintQuery, new Update().set( SharedFileFootprintMapper.CREATION_DATE, footprint.getCreationDate()), SHARED_FILE_FOOTPRINT_STORENAME); mongo.upsert(footPrintQuery, new Update().set( SharedFileFootprintMapper.EXPIRATION_DATE, footprint.getExpirationDate()), SHARED_FILE_FOOTPRINT_STORENAME); } private void saveSharedFileInfo(SharedFileInfo sharedFileInfo) { final Query metadataQuery = new Query(Criteria.where(MONGO_DOC_ID).is( sharedFileInfo.getId())); mongo.upsert(metadataQuery, new Update().set(MONGO_DOC_ID, sharedFileInfo.getId()), SHARED_FILE_INFO_STORENAME); mongo.upsert( metadataQuery, new Update().set(CREATION_DATE, sharedFileInfo.getCreationDate()), SHARED_FILE_INFO_STORENAME); mongo.upsert( metadataQuery, new Update().set(EXPIRATION_DATE, sharedFileInfo.getExpirationDate()), SHARED_FILE_INFO_STORENAME); mongo.upsert(metadataQuery, new Update().set(DESCRIPTION, sharedFileInfo.getDescription()), SHARED_FILE_INFO_STORENAME); mongo.upsert(metadataQuery, new Update().set(OWNER, sharedFileInfo.getOwner()), SHARED_FILE_INFO_STORENAME); mongo.upsert(metadataQuery, new Update().set(PRIVACY_TYPE, sharedFileInfo.getPrivacy().getType()), SHARED_FILE_INFO_STORENAME); if (sharedFileInfo.getPrivacy().getType() == Privacy.Type.PRIVATE) { mongo.upsert( metadataQuery, new Update().set( BUDDIES_LIST, Arrays.asList(sharedFileInfo.getPrivacy() .getBuddies().toArray())), SHARED_FILE_INFO_STORENAME); } } private void saveRawFile(RawFile rawFile) { final Query contentQuery = new Query(Criteria.where(MONGO_DOC_ID).is( rawFile.getId())); mongo.upsert(contentQuery, new Update().set(MONGO_DOC_ID, rawFile.getId()), RAW_FILE_STORENAME); mongo.upsert( contentQuery, new Update().set(STORAGE_COORDINATES, rawFile.getStorageCoordinates()), RAW_FILE_STORENAME); } private void saveRawFileInfo(RawFileInfo rawFileInfo) { final Query contentQuery = new Query(Criteria.where(MONGO_DOC_ID).is( rawFileInfo.getRawFileId() + INFO_SUFFIX)); mongo.upsert(contentQuery, new Update().set(CONTENT_TYPE, rawFileInfo.getContentType()), RAW_FILE_INFO_STORENAME); mongo.upsert( contentQuery, new Update().set(ORIGINAL_FILE_NAME, rawFileInfo.getOriginalFileName()), RAW_FILE_INFO_STORENAME); mongo.upsert(contentQuery, new Update().set(SIZE, rawFileInfo.getSize()), RAW_FILE_INFO_STORENAME); mongo.upsert(contentQuery, new Update().set(RAW_FILE_ID, rawFileInfo.getRawFileId()), RAW_FILE_INFO_STORENAME); } private SharedFile getSharedFileFromFootprint(SharedFileFootprint footPrint) { RawFileInfoMapper rawFileInfoMapper = new RawFileInfoMapper(); mongo.executeQuery( new Query(Criteria.where(MONGO_DOC_ID).is( footPrint.getRawFileId() + INFO_SUFFIX)), RAW_FILE_INFO_STORENAME, rawFileInfoMapper); RawFileMapper rawFileMapper = new RawFileMapper(); mongo.executeQuery( new Query(Criteria.where(MONGO_DOC_ID).is( footPrint.getRawFileId())), RAW_FILE_STORENAME, rawFileMapper); SharedFileInfoMapper sharedFileInfoMapper = new SharedFileInfoMapper(); mongo.executeQuery( new Query(Criteria.where(MONGO_DOC_ID).is( footPrint.getSharedFileInfoId())), SHARED_FILE_INFO_STORENAME, sharedFileInfoMapper); SharedFile sharedFile = new SharedFile.Builder() .setRawFile(rawFileMapper.getRawFile()) .setRawFileInfo(rawFileInfoMapper.getRawFileInfo()) .setSharedFileInfo(sharedFileInfoMapper.getSharedFileInfo()) .build(); return sharedFile; } private SharedFileDescriptor getSharedFileDescriptorFromFootprint( SharedFileFootprint footPrint) { RawFileInfoMapper rawFileInfoMapper = new RawFileInfoMapper(); mongo.executeQuery( new Query(Criteria.where(MONGO_DOC_ID).is( footPrint.getRawFileId() + INFO_SUFFIX)), RAW_FILE_INFO_STORENAME, rawFileInfoMapper); SharedFileInfoMapper sharedFileInfoMapper = new SharedFileInfoMapper(); mongo.executeQuery( new Query(Criteria.where(MONGO_DOC_ID).is( footPrint.getSharedFileInfoId())), SHARED_FILE_INFO_STORENAME, sharedFileInfoMapper); SharedFileDescriptor descriptor = new SharedFileDescriptor.Builder() .setRawFileInfo(rawFileInfoMapper.getRawFileInfo()) .setSharedFileInfo(sharedFileInfoMapper.getSharedFileInfo()) .build(); return descriptor; } private void turn(Type privacyType, SharedFileInfo sharedFileInfo) { final Query metadataQuery = new Query(Criteria.where(MONGO_DOC_ID).is( sharedFileInfo.getId())); mongo.upsert(metadataQuery, new Update().set(PRIVACY_TYPE, privacyType), SHARED_FILE_INFO_STORENAME); if (privacyType == Privacy.Type.PRIVATE) { mongo.upsert( metadataQuery, new Update().set( BUDDIES_LIST, Arrays.asList(sharedFileInfo.getPrivacy() .getBuddies().toArray())), SHARED_FILE_INFO_STORENAME); } } @Override public Integer deleteOlderThan(Date expirationDate) { SharedFileFootprintMapper footprintMapper = new SharedFileFootprintMapper(); final Query footprintQuery = new Query(Criteria.where(EXPIRATION_DATE) .lt(expirationDate)); mongo.executeQuery(footprintQuery, SHARED_FILE_FOOTPRINT_STORENAME, footprintMapper); // SharedFileFootprint sharedFileFootprint = // footprintMapper.getFootprint(); List<SharedFileFootprint> shareFilesToBeDeleted = footprintMapper .getFootprintList(); for (SharedFileFootprint cur : shareFilesToBeDeleted) { final Query rawFileQuery = new Query(Criteria.where(MONGO_DOC_ID) .is(cur.getRawFileId())); final Query rawFileInfoQuery = new Query(Criteria.where( MONGO_DOC_ID).is(cur.getRawFileId() + "-info")); final Query sharedFileInfoQuery = new Query(Criteria.where( MONGO_DOC_ID).is(cur.getSharedFileInfoId())); mongo.remove(rawFileQuery, RAW_FILE_STORENAME); mongo.remove(rawFileInfoQuery, RAW_FILE_INFO_STORENAME); mongo.remove(sharedFileInfoQuery, SHARED_FILE_INFO_STORENAME); mongo.remove(footprintQuery, SHARED_FILE_FOOTPRINT_STORENAME); } return shareFilesToBeDeleted.size(); } @Override public void appendBuddyToSharedFileInfoById(String sharedFileInfoId, String buddy) { final Query metadataQuery = new Query(Criteria.where(MONGO_DOC_ID).is( sharedFileInfoId)); mongo.upsert(metadataQuery, new Update().addToSet(BUDDIES_LIST, buddy), SHARED_FILE_INFO_STORENAME); } }
package jikanganai.server; import org.hibernate.boot.model.naming.Identifier; import org.hibernate.boot.model.naming.PhysicalNamingStrategy; import org.hibernate.engine.jdbc.env.spi.JdbcEnvironment; import java.util.regex.Pattern; public class CamelCasePhysicalNamingStrategy implements PhysicalNamingStrategy { @Override public Identifier toPhysicalCatalogName( Identifier name, JdbcEnvironment jdbcEnvironment ) { return name; } @Override public Identifier toPhysicalSchemaName( Identifier name, JdbcEnvironment jdbcEnvironment ) { return name; } @Override public Identifier toPhysicalTableName( Identifier name, JdbcEnvironment jdbcEnvironment ) { return name; } @Override public Identifier toPhysicalSequenceName( Identifier name, JdbcEnvironment jdbcEnvironment ) { return name; } @Override public Identifier toPhysicalColumnName( Identifier name, JdbcEnvironment jdbcEnvironment ) { // This has been such a pain to figure out 😖. Postgres didn't like // createdAt without wrapping it around double quotes. case sensitivity if (Pattern.compile("[A-Z]+").matcher(name.getText()).find()) { return Identifier.toIdentifier("\"" + name.getText() + "\""); } else { return name; } } }
package com.smartlead.api.user.security; import com.smartlead.common.vo.UserVO; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.userdetails.User; import java.util.Collection; import java.util.List; public class SecUser extends User { private int userId; private String firstName; private String lastName; private String email; private String mobile; private int orgId; private List<String> roles; public SecUser(String username, String password, Collection<? extends GrantedAuthority> authorities) { super(username, password, authorities); } public SecUser(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities) { super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities); } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile; } public int getOrgId() { return orgId; } public void setOrgId(int orgId) { this.orgId = orgId; } public List<String> getRoles() { return roles; } public void setRoles(List<String> roles) { this.roles = roles; } public UserVO getUserVO() { UserVO userVO = new UserVO(); userVO.setUserId(getUserId()); userVO.setUsername(getUsername()); userVO.setOrgId(getOrgId()); userVO.setEmail(getEmail()); userVO.setFirstName(getFirstName()); userVO.setLastName(getLastName()); userVO.setMobile(getMobile()); userVO.setRoles(getRoles()); return userVO; } @Override public String toString() { return "UserVO{" + "userId=" + userId + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + ", mobile='" + mobile + '\'' + ", orgId=" + orgId + ", roles=" + roles + '}'; } }
package com.yuneec.test; import android.os.Handler; import android.util.Log; import com.yuneec.uartcontroller.UARTController; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.net.Socket; import org.json.JSONObject; public class Transfer implements Runnable { private static final int MAX_BUFFER_BYTES = 128; public static final int TYPE_DATA_FLIGHT = 1001; public static final int TYPE_DATA_GPS = 1002; public static final int TYPE_DATA_TELE = 1003; private Socket client; private int dataLength = 0; private BufferedInputStream mRece = null; private BufferedOutputStream mSend = null; private UARTController mUBSUARTController = null; private Handler mUSBHandler = null; private byte[] outBytesBuf = null; byte[] tmpByte = new byte[4]; private boolean transferRunning = true; public Transfer(Socket client) { this.client = client; } public void stopTransfer() { this.transferRunning = false; } public void setUARTService(UARTController mUARTController) { this.mUBSUARTController = mUARTController; } public void setData(byte[] sendBuf, int typeData) { if (sendBuf.length >= 123) { Log.i("TEST", "ERROR setData length is over 256 bytes, is " + sendBuf.length); } else if (this.mSend == null || this.mRece == null || this.outBytesBuf == null) { Log.i("TEST", "ERROR setData mSend == null || mRece == null || outBytesBuf == null"); } else { this.tmpByte[0] = (byte) 100; this.tmpByte[1] = (byte) sendBuf.length; if (typeData < 1001 || typeData > TYPE_DATA_TELE) { Log.i("TEST", "ERROR setData typeData=" + typeData); return; } if (typeData == 1001) { this.tmpByte[2] = (byte) 1; } else if (typeData == 1002) { this.tmpByte[2] = (byte) 2; } else if (typeData == TYPE_DATA_TELE) { this.tmpByte[2] = (byte) 3; } byte crcNum = generateCRC8(sendBuf, sendBuf.length); System.arraycopy(this.tmpByte, 0, this.outBytesBuf, 0, 3); System.arraycopy(sendBuf, 0, this.outBytesBuf, 3, sendBuf.length); this.outBytesBuf[sendBuf.length + 3] = crcNum; this.dataLength = sendBuf.length + 4; try { this.mSend.write(this.outBytesBuf, 0, this.dataLength); this.mSend.flush(); Thread.sleep(10); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e2) { e2.printStackTrace(); } } } static byte generateCRC8(byte[] buffer, int len) { byte crci = (byte) 119; for (byte b : buffer) { crci = (byte) ((b & 119) ^ crci); for (int i = 0; i < 8; i++) { if ((crci & 1) != 0) { crci = (byte) (((byte) (crci >> 1)) ^ 119); } else { crci = (byte) (crci >> 1); } } } return crci; } private String rtnStrResult(boolean result) { String tmpString = ""; if (result) { return "REQ_OK"; } return "REQ_ERROR"; } public void run() { try { this.mSend = new BufferedOutputStream(this.client.getOutputStream()); this.mRece = new BufferedInputStream(this.client.getInputStream()); this.outBytesBuf = new byte[144]; while (this.transferRunning) { byte[] tempbuffer = new byte[128]; try { if (!this.client.isConnected()) { Log.i("TEST", "TEST Service socket is Disconnected"); break; } String strFormsocket = new String(tempbuffer, 0, this.mRece.read(tempbuffer, 0, tempbuffer.length), "utf-8"); Log.i("TEST", "TEST Rece Data:[" + strFormsocket + "]"); if (this.mUBSUARTController != null) { JSONObject jsonObj = new JSONObject(strFormsocket); String type = jsonObj.getString("type"); if (type == null) { Log.i("TEST", "TEST ERROR read data is wrong!"); } else if (type.equals("setting")) { tmpBool = this.mUBSUARTController.writeTransmitRate(jsonObj.getInt("rf_power")); Log.i("TEST", "TEST send Data setting : [" + tmpBool + "]"); this.mSend.write(rtnStrResult(tmpBool).getBytes(), 0, rtnStrResult(tmpBool).getBytes().length); this.mSend.flush(); } else if (type.equals("getting")) { String tmpString = String.valueOf(this.mUBSUARTController.readTransmitRate()); Log.i("TEST", "TEST send Data getting : [" + tmpString + "]"); this.mSend.write(tmpString.getBytes(), 0, tmpString.getBytes().length); this.mSend.flush(); } else if (type.equals("enter")) { tmpBool = this.mUBSUARTController.PCenterTestRF(jsonObj.getInt("rf_channel"), jsonObj.getInt("rf_mode")); Log.i("TEST", "TEST send Data enter : [" + tmpBool + "]"); this.mSend.write(rtnStrResult(tmpBool).getBytes(), 0, rtnStrResult(tmpBool).getBytes().length); this.mSend.flush(); } else if (type.equals("exit")) { tmpBool = this.mUBSUARTController.enterRun(true); Log.i("TEST", "TEST send Data exit : [" + tmpBool + "]"); this.mSend.write(rtnStrResult(tmpBool).getBytes(), 0, rtnStrResult(tmpBool).getBytes().length); this.mSend.flush(); } else { Log.i("TEST", "TEST ERROR read type is wrong!"); } } else { Log.i("TEST", "TEST ERROR mUBSUARTController is null!"); Thread.sleep(1000); } } catch (Exception e) { e.printStackTrace(); this.transferRunning = false; Log.i("TEST", "TEST Exception!!! " + e); } } if (this.mUSBHandler != null) { this.mUSBHandler = null; } if (this.mSend != null) { this.mSend.close(); } if (this.mRece != null) { this.mRece.close(); } if (this.mRece != null) { this.outBytesBuf = null; } if (this.tmpByte != null) { this.tmpByte = null; } } catch (Exception e2) { e2.printStackTrace(); } } public void sendData(byte[] dataByte, int offset, int length) throws IOException { if (this.mSend != null) { this.mSend.write(dataByte, offset, length); this.mSend.flush(); } } }
package com.jpa.servises; import com.jpa.entity.Ticket; import javax.persistence.EntityManager; import javax.persistence.Persistence; import javax.persistence.TypedQuery; import java.util.List; /** * Created by Дарья on 09.03.2015. */ public class TicketServices { public EntityManager em = Persistence.createEntityManagerFactory("COLIBRI").createEntityManager(); public Ticket add(Ticket stopStation){ em.getTransaction().begin(); Ticket trainFromDB = em.merge(stopStation); em.getTransaction().commit(); return trainFromDB; } public void delete(long id){ em.getTransaction().begin(); em.remove(get(id)); em.getTransaction().commit(); } public Ticket get(long id){ return em.find(Ticket.class, id); } public void update(Ticket stopStation){ em.getTransaction().begin(); em.merge(stopStation); em.getTransaction().commit(); } public List<Ticket> getAll(){ TypedQuery<Ticket> namedQuery = em.createNamedQuery("Ticket.getAll", Ticket.class); return namedQuery.getResultList(); } }
package somani.siddharth.tophawkstraining; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.Toast; import com.firebase.client.ChildEventListener; import com.firebase.client.DataSnapshot; import com.firebase.client.Firebase; import com.firebase.client.FirebaseError; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import java.util.ArrayList; import java.util.List; public class Tests extends AppCompatActivity { String url,c,testname=""; private RecyclerView recyclerView; private RecyclerView.Adapter adapter; private List<TestsPojo> uploads; Firebase mDatabase,mDatabase3,mDatabase2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tests); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); Firebase.setAndroidContext(this); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); //testname=CustomSwipeAdapter.testname; //final Bundle extras=getIntent().getExtras(); recyclerView = (RecyclerView) findViewById(R.id.recyclerView); recyclerView.setHasFixedSize(true); recyclerView.setLayoutManager(new LinearLayoutManager(this)); uploads = new ArrayList<>(); FirebaseAuth auth; auth = FirebaseAuth.getInstance(); final FirebaseUser user = auth.getCurrentUser(); mDatabase3 = new Firebase("https://occupation-fc1fb.firebaseio.com/Users"); mDatabase3.addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(com.firebase.client.DataSnapshot dataSnapshot, String s) { String email=dataSnapshot.child("email").getValue(String.class); if(email.equals(user.getEmail())) {c=dataSnapshot.getKey(); mDatabase = new Firebase("https://occupation-fc1fb.firebaseio.com/Users").child(c).child("Tests"); mDatabase.addChildEventListener(new ChildEventListener() { @Override public void onChildAdded(com.firebase.client.DataSnapshot dataSnapshot, String s) { // progressDialog.dismiss(); url = dataSnapshot.child("pending").getValue(String.class); TestsPojo testsPojo = new TestsPojo(url,dataSnapshot.getKey()); //Toast.makeText(Tests.this,dataSnapshot.getKey(),Toast.LENGTH_LONG).show(); uploads.add(testsPojo); recyclerView.setAdapter(adapter); adapter.notifyDataSetChanged(); } @Override public void onChildChanged(com.firebase.client.DataSnapshot dataSnapshot, String s) { } @Override public void onChildRemoved(com.firebase.client.DataSnapshot dataSnapshot) { } @Override public void onChildMoved(com.firebase.client.DataSnapshot dataSnapshot, String s) { } @Override public void onCancelled(FirebaseError firebaseError) { } }); } } @Override public void onChildChanged(com.firebase.client.DataSnapshot dataSnapshot, String s) { } @Override public void onChildRemoved(com.firebase.client.DataSnapshot dataSnapshot) { } @Override public void onChildMoved(com.firebase.client.DataSnapshot dataSnapshot, String s) { } @Override public void onCancelled(FirebaseError firebaseError) { } }); adapter = new TestsAdapter(getApplicationContext(), uploads); } }
import javax.faces.bean.ManagedBean; import java.io.Serializable; /** * Created by reda-benchraa on 22/02/17. */ @ManagedBean public class Arithm implements Serializable{ private float n1,n2; public Arithm() {} public char getOp() { return op; } public void setOp(char op) { this.op = op; } private char op; public float getN1() { return n1; } public void setN1(float n1) { this.n1 = n1; } public float getN2() { return n2; } public void setN2(float n2) { this.n2 = n2; } public float calculate(){ switch (op){ case '+' : return n1+n2; case '-' : return n1-n2; case '*' : return n1*n2; case '/' : return n1/n2; default: return 0; } } }
package com.mediafire.sdk.api.responses; import com.mediafire.sdk.api.responses.data_models.WebUploads; /** * Created by Chris on 5/19/2015. */ public class UploadGetWebUploadsResponse extends ApiResponse { private WebUploads[] web_uploads; public WebUploads[] getWebUploads() { return web_uploads; } }
package com.github.xuchengen.request; /** * 公共请求参数模型 * 作者:徐承恩 * 邮箱:xuchengen@gmail.com * 日期:2019-08-27 */ public class UnionPayCommonRequest { /** * 交易类型 */ private String txnType; /** * 交易子类 */ private String txnSubType; /** * 接入类型 */ private String accessType; public String getTxnType() { return txnType; } public UnionPayCommonRequest setTxnType(String txnType) { this.txnType = txnType; return this; } public String getTxnSubType() { return txnSubType; } public UnionPayCommonRequest setTxnSubType(String txnSubType) { this.txnSubType = txnSubType; return this; } public String getAccessType() { return accessType; } public UnionPayCommonRequest setAccessType(String accessType) { this.accessType = accessType; return this; } }
package com.bac.rest.config; import javax.ws.rs.core.Configuration; import javax.ws.rs.core.Feature; import javax.ws.rs.core.FeatureContext; import javax.ws.rs.ext.MessageBodyReader; import javax.ws.rs.ext.MessageBodyWriter; import org.glassfish.jersey.internal.InternalProperties; import org.glassfish.jersey.internal.util.PropertiesHelper; import com.fasterxml.jackson.jaxrs.base.JsonMappingExceptionMapper; import com.fasterxml.jackson.jaxrs.base.JsonParseExceptionMapper; public class MarshallingFeature implements Feature { private final static String JSON_FEATURE = MarshallingFeature.class.getSimpleName(); @Override public boolean configure(FeatureContext context) { context.register(JsonParseExceptionMapper.class); context.register(JsonMappingExceptionMapper.class); context.register(JacksonJsonProviderAtRest.class, MessageBodyReader.class, MessageBodyWriter.class); final Configuration config = context.getConfiguration(); // Disables discoverability of org.glassfish.jersey.jackson.JacksonFeature context.property( PropertiesHelper.getPropertyNameForRuntime(InternalProperties.JSON_FEATURE, config.getRuntimeType()), JSON_FEATURE); return true; } }
/* * Copyright 2020 WeBank * * 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.webank.wedatasphere.schedulis.common.executor; import azkaban.executor.ExecutionOptions; import azkaban.executor.Status; import azkaban.sla.SlaOption; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class ExecutionCycle { private int id; private Status status; private int currentExecId; private int projectId; private String flowId; private String submitUser; private long submitTime; private long updateTime; private long startTime; private long endTime; private int encType; private byte[] data; private Map<String, Object> cycleOption = new HashMap<>(); private String proxyUsers; private ExecutionOptions executionOptions; private String cycleErrorOption; private Map<String, Object> otherOption = new HashMap<>(); private List<SlaOption> slaOptions = new ArrayList<>(); public int getId() { return id; } public Status getStatus() { return status; } public int getCurrentExecId() { return currentExecId; } public int getProjectId() { return projectId; } public String getFlowId() { return flowId; } public String getSubmitUser() { return submitUser; } public long getUpdateTime() { return updateTime; } public long getSubmitTime() { return submitTime; } public long getStartTime() { return startTime; } public long getEndTime() { return endTime; } public int getEncType() { return encType; } public byte[] getData() { return data; } public Map<String, Object> getCycleOption() { return cycleOption; } public String getProxyUsers() { return proxyUsers; } public ExecutionOptions getExecutionOptions() { return executionOptions; } public String getCycleErrorOption() { return cycleErrorOption; } public Map<String, Object> getOtherOption() { return otherOption; } public List<SlaOption> getSlaOptions() { return slaOptions; } public void setId(int id) { this.id = id; } public void setStatus(Status status) { this.status = status; } public void setCurrentExecId(int currentExecId) { this.currentExecId = currentExecId; } public void setProjectId(int projectId) { this.projectId = projectId; } public void setFlowId(String flowId) { this.flowId = flowId; } public void setSubmitUser(String submitUser) { this.submitUser = submitUser; } public void setSubmitTime(long submitTime) { this.submitTime = submitTime; } public void setUpdateTime(long updateTime) { this.updateTime = updateTime; } public void setStartTime(long startTime) { this.startTime = startTime; } public void setEndTime(long endTime) { this.endTime = endTime; } public void setEncType(int encType) { this.encType = encType; } public void setData(byte[] data) { this.data = data; } public void setCycleOption(Map<String, Object> cycleOption) { this.cycleOption = cycleOption; } public void setProxyUsers(String proxyUsers) { this.proxyUsers = proxyUsers; } public void setExecutionOptions(ExecutionOptions executionOptions) { this.executionOptions = executionOptions; } public void setCycleErrorOption(String recoverErrorOption) { this.cycleErrorOption = recoverErrorOption; } public void setOtherOption(Map<String, Object> otherOption) { this.otherOption = otherOption; } public void setSlaOptions(List<SlaOption> slaOptions) { this.slaOptions = slaOptions; } }
package testCase; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.Test; import generics.RedBlackTree; import junit.framework.TestCase; class RedBlackTreeTest extends TestCase { private RedBlackTree<String> redblackTree; private String refers; void stageOne(){ redblackTree = new RedBlackTree<>(); refers = "test"; } @Test public void testInsertRB() { stageOne(); redblackTree.insertRB(refers); assertEquals(redblackTree.getRoot(), refers); } @Test public void testsDelete() { stageOne(); redblackTree.insertRB(refers); redblackTree.deleteRB(refers); assertEquals(redblackTree.getRoot(), null); } }
package br.com.mixfiscal.prodspedxnfe.domain.enums; import br.com.mixfiscal.prodspedxnfe.domain.ex.EnumDesconhecidoException; public enum ETipoNotaFiscal { Entrada((byte)0), Saida((byte)1); private final byte tipoNotaFiscal; private ETipoNotaFiscal(byte tipoNotaFiscal) { this.tipoNotaFiscal = tipoNotaFiscal; } public byte getTipoNotaFiscal() { return this.tipoNotaFiscal; } public static ETipoNotaFiscal deCodigo(String codigo) throws EnumDesconhecidoException, NumberFormatException { byte iCodigo = Byte.parseByte(codigo); return deCodigo(iCodigo); } public static ETipoNotaFiscal deCodigo(byte codigo) throws EnumDesconhecidoException { for (ETipoNotaFiscal tipoItem : ETipoNotaFiscal.values()) { if (tipoItem.getTipoNotaFiscal() == codigo) return tipoItem; } throw new EnumDesconhecidoException(); } }
package com.liuzhenkun.cms.dao; import com.liuzhenkun.cms.entity.VoteContent; public interface VoteContentDao extends BaseDao<VoteContent>{ }
//Lonnie Williams //Jump Training public class HeadOrTailTally { public static void main(String[] args) { int heads = 0; int tails = 0; for(int x=0;x<1000;x++){ if (Math.random() < 0.5) { tails = tails +1; } else { heads = heads +1; } } System.out.println("Count of Heads: " + heads); System.out.println("Count of Tails: " + tails); } }
package com.augen.bookstore.constants; public enum DeliveryServiceEnum { MOTORBIKE("MotorBike", 5.0, 0.5, 1.5, 1.0), TRAIN("Train", 10.0, 0.8, 1.8, 1.0), AIRCRAFT("AirCraft", 20.0, 0.8, 2.0, 1.0); private final String type; private final Double cost; private final Double juneToAug; private final Double sep; private final Double otherMonth; DeliveryServiceEnum(String type, Double cost, Double juneToAug, Double sep, Double otherMonth) { this.type = type; this.cost = cost; this.juneToAug = juneToAug; this.sep = sep; this.otherMonth = otherMonth; } public String getType() { return this.type;} public Double getCost() {return this.cost;} public Double getJuneToAug() {return this.juneToAug;} public Double getSep() {return this.sep;} public Double getOtherMonth() {return this.otherMonth;} }
package com.prj.controller; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.prj.pojo.Orderform; import com.prj.service.IOrderformService; @Controller public class OrderformController { @Resource private IOrderformService orderformService; private Orderform of; public Orderform getOf() { return of; } public void setOf(Orderform of) { this.of = of; } @RequestMapping("/findAll_orderform") public String findAll(HttpServletRequest request){ List<Orderform> orderforms = orderformService.findAll(); request.getSession().setAttribute("orderforms", orderforms); return "orderform_list"; } @RequestMapping("/seach_of") public String seach(String ofname){ return ""; } }
package com.cs240.server.dao; import model.Event; import java.sql.*; import java.util.ArrayList; /*** * Performs the following SQL Statements on the Event Table: * Create Table * Drop Table * Select (Single) * Select (All) * Insert (Single) * Delete (Associated User) * Delete (All) */ public class EventDAO { private final Connection c; /*** * Constructor. * * @param c - Connection from Database class. */ public EventDAO(Connection c) { this.c = c; } /*** * Creates the Event Table * * @throws DataAccessException - Unable to create Event Table: + e */ public void createTable() throws DataAccessException { //Event Table String sqlE = "Create Table IF NOT EXISTS Event(\n" + "EventID varChar(20) PRIMARY KEY NOT NULL,\n" + "EventType varChar(20) NOT NULL,\n" + "PersonID varchar(20) NOT NULL,\n" + "AssociatedUsername varchar(20),\n" + "Year Integer NOT NULL,\n" + "Country varchar(50) NOT NULL,\n" + "City varchar(50) NOT NULL,\n" + "Latitude float NOT NULL,\n" + "Longitude float NOT NULL);"; try (Statement stmt = c.createStatement()){ //Create Table stmt.executeUpdate(sqlE); } //SQL Error catch (SQLException e) { throw new DataAccessException("Unable to create Event Table: " + e); } } /*** * For Testing Purposes, I need to make sure that the * Event table is properly created. So dropping it is * useful. * * @throws DataAccessException - Unable to drop Event table: + e */ public void dropTable() throws DataAccessException{ //Initialize and prepare statements. String sqlE = "Drop Table Event"; try (Statement stmt = c.createStatement()){ //Execute stmt.executeUpdate(sqlE); } //SQL Error catch (SQLException e) { throw new DataAccessException("Unable to drop Event table: " + e); } } /*** * (Select - Single) * Takes an eventID String. Selects the event associated with the ID, * and then returns the row as an event object. Returns null if no row found. * * @param eventID - The eventID to check for. * @return event - The event object for the row found. * @throws DataAccessException - Unable to find event: + e */ public Event fetchEvent(String eventID) throws DataAccessException { //Initialize and prepare statements. Event event = null; ResultSet ur = null; String sql = "SELECT * FROM Event WHERE EventID = ?;"; //Execute the Query. If you find a row, set the Authtoken values. try (PreparedStatement stmt = c.prepareStatement(sql)) { stmt.setString(1, eventID); ur = stmt.executeQuery(); //If a row is found if (ur.next()) { event = new Event( ur.getString("EventID"), ur.getString("EventType"), ur.getString("PersonID"), ur.getString("AssociatedUsername"), ur.getInt("Year"), ur.getString("Country"), ur.getString("City"), ur.getFloat("Latitude"), ur.getFloat("Longitude") ); return event; } } //SQL Error catch (SQLException e) { e.printStackTrace(); throw new DataAccessException("Unable to find event: " + e); } //Close the resultSet finally { if(ur != null) { try { ur.close(); } catch (SQLException e) { e.printStackTrace(); } } } return null; } /*** * (Select - All) * Takes an personID String. Selects all events associated with the ID, * and then returns the rows as an array of event objects. Returns empty * array if none are found. * * @param personID - The personID to check for. * @return event - The event object for the row found. * @throws DataAccessException - Unable to find events: + e */ public ArrayList<Event> fetchEvents(String personID) throws DataAccessException { //Initialize and prepare statements. ArrayList<Event> events = new ArrayList<Event>(); Event event = null; ResultSet ur = null; String sql = "SELECT * FROM Event WHERE PersonID = ?;"; //Execute the Query. If you find a row, set the Authtoken values. try (PreparedStatement stmt = c.prepareStatement(sql)) { stmt.setString(1, personID); ur = stmt.executeQuery(); //If a row is found while (ur.next()) { event = new Event( ur.getString("EventID"), ur.getString("EventType"), ur.getString("PersonID"), ur.getString("AssociatedUsername"), ur.getInt("Year"), ur.getString("Country"), ur.getString("City"), ur.getFloat("Latitude"), ur.getFloat("Longitude") ); events.add(event); } } //SQL Error catch (SQLException e) { e.printStackTrace(); throw new DataAccessException("Unable to find events: " + e); } //Close the resultSet finally { if(ur != null) { try { ur.close(); } catch (SQLException e) { e.printStackTrace(); } } } return events; } /*** * (Insert) * Takes an event object. Inserts a new event. * * @param event - New event object to insert into the Database * @throws DataAccessException - Unable to create event: + e */ public void insertEvent(Event event) throws DataAccessException { //Prepare Statements String sql = "INSERT INTO Event (EventID, EventType, PersonID, AssociatedUsername, " + "Year, Country, City, Latitude, Longitude) VALUES(?,?,?,?,?,?,?,?,?);"; try (PreparedStatement stmt = c.prepareStatement(sql)) { //Set Event values. stmt.setString(1, event.getEventID()); stmt.setString(2, event.getEventType()); stmt.setString(3, event.getPersonID()); stmt.setString(4, event.getAssociatedUsername()); stmt.setInt(5, event.getYear()); stmt.setString(6, event.getCountry()); stmt.setString(7, event.getCity()); stmt.setFloat(8, event.getLatitude()); stmt.setFloat(9, event.getLongitude()); //Execute Query stmt.executeUpdate(); } //SQL Error catch (SQLException e) { throw new DataAccessException("Unable to create event: " + e); } } /*** * (Delete) * Takes a username. Deletes Events who have that associated username. * * @param asscoiatedUsername - username of event to delete. * @throws DataAccessException - Unable to delete event: + e */ public void deleteEvent(String asscoiatedUsername) throws DataAccessException { //Prepare Statements String sql = "DELETE FROM Event WHERE AssociatedUsername = ?;"; try (PreparedStatement stmt = c.prepareStatement(sql)) { //Set Person values. stmt.setString(1, asscoiatedUsername); //Execute Query stmt.executeUpdate(); } //SQL Error catch (SQLException e) { throw new DataAccessException("Unable to delete event: " + e); } } /*** * (Delete) * Clears all events from the Event table. * * @throws DataAccessException - Unable to clear events: + e */ public void clear() throws DataAccessException { //Prepare Statements String sql = "DELETE FROM Event"; try (Statement stmt = c.createStatement()){ //Execute Query stmt.executeUpdate(sql); } //SQL Error catch (SQLException e) { throw new DataAccessException("Unable to clear events: " + e); } } }
package com.traineeapp.model.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import com.traineeapp.model.dao.factory.ConnectionFactory; import com.traineeapp.web.entity.User; import com.traineeapp.web.exception.DataAccessException; import com.traineeapp.web.exception.UserNotFoundException; public class UserDaoImpl implements UserDao{ private Connection connection; public UserDaoImpl() { connection=ConnectionFactory.getConnection(); } @Override public User getUser(String username, String password) { User user = null; PreparedStatement pstmt; try { pstmt = connection.prepareStatement("select * from user_table where username=? and password=?"); pstmt.setString(1, username); pstmt.setString(2, password); ResultSet rs = pstmt.executeQuery(); if (rs.next()) { user = new User(rs.getInt("id"), rs.getString("username"), rs.getString("password")); } else { throw new UserNotFoundException("user with username " + username + " is not found"); } } catch (SQLException e) { e.printStackTrace(); throw new DataAccessException(e.getMessage()); } System.out.println(user); return user; } }
package com.prince.stream.map; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class StreamMapExample { public static void main(String[] args) { List<String> alist = new ArrayList<>(); alist.add("abc"); alist.add("xyz"); alist.add("mno"); alist.forEach(System.out::println); List<String> alist2 = alist.stream().map(s -> s.toUpperCase()).collect(Collectors.toList()); alist2.forEach(System.out::println); } }
package com.github.gaoyangthu.core.hbase.mapper; import com.github.gaoyangthu.core.hbase.RowMapper; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.client.Result; import org.apache.hadoop.hbase.util.Bytes; /** * Created with IntelliJ IDEA. * Author: gaoyangthu * Date: 14-3-11 * Time: 下午4:42 */ public class PrintMapper implements RowMapper { @Override public Object mapRow(Result result, int rowNum) throws Exception { System.out.println("row:" + Bytes.toString(result.getRow())); for(KeyValue keyValue : result.raw()) { System.out.println("family:" + Bytes.toString(keyValue.getFamily())); System.out.println("Qualifier:" + Bytes.toString(keyValue.getQualifier())); System.out.println("value:" + Bytes.toString(keyValue.getValue())); System.out.println("timestamp:" + keyValue.getTimestamp()); } System.out.println("Result:" + result); return result; } }