blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
sequencelengths
1
1
author_id
stringlengths
0
313
d59c3b6f34bb4848847b35500d4c9a7520c17be1
675cbffa1d3e6716f0f89db8ac0ca637105967cf
/app/src/main/java/com/huatu/handheld_huatu/ui/PullRefreshRecyclerView.java
af2ebc4a00de85f2f4335cd70e6762d7a0606a43
[]
no_license
led-os/HTWorks
d5bd33e7fddf99930c318ced94869c17f7a97836
ee94e8a2678b8a2ea79e73026d665d57f312f7e2
refs/heads/master
2022-04-05T02:56:14.051111
2020-01-21T07:38:25
2020-01-21T07:38:25
null
0
0
null
null
null
null
UTF-8
Java
false
false
6,515
java
package com.huatu.handheld_huatu.ui; import android.content.Context; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.widget.FrameLayout; import com.huatu.handheld_huatu.ui.recyclerview.RecyclerViewEx; import com.huatu.library.PullToRefreshBase; /** * Created by Administrator on 2017/1/11. */ /** * Created by Administrator on 2016/8/25. */ public class PullRefreshRecyclerView extends PullToRefreshBase<RecyclerViewEx> { boolean DEBUG=false; private int mAdjustDistance=0; //排除top decoration的影响 public void setAdjustDistance(int topDistance){ mAdjustDistance=topDistance; } public PullRefreshRecyclerView(Context context, Mode mode) { super(context, mode); //mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); } public PullRefreshRecyclerView(Context context) { super(context); //mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); } public PullRefreshRecyclerView(Context context, AttributeSet attrs) { super(context, attrs); //mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); } public PullRefreshRecyclerView(Context context, Mode mode, AnimationStyle animStyle) { super(context, mode, animStyle); // mTouchSlop = ViewConfiguration.get(context).getScaledTouchSlop(); } public FrameLayout getRefreshContainer(){ return super.getRefreshableViewWrapper(); } boolean canPullToRefresh=true; public void setCanPull(boolean pullEnable){ canPullToRefresh=pullEnable; } @Override public boolean isPullToRefreshEnabled() { return canPullToRefresh&&super.isPullToRefreshEnabled(); } @Override public Orientation getPullToRefreshScrollDirection() { return Orientation.VERTICAL; } @Override protected RecyclerViewEx createRefreshableView(Context context, AttributeSet attrs) { RecyclerViewEx recyclerView = new RecyclerViewEx(context,attrs); recyclerView.setId(android.R.id.list); LinearLayoutManager mannagerTwo = new LinearLayoutManager(context); mannagerTwo.setOrientation(LinearLayoutManager.VERTICAL); //recyclerView.addItemDecoration( // new DividerItemDecoration(this, DividerItemDecoration.HORIZONTAL_LIST)); recyclerView.setLayoutManager(mannagerTwo); return recyclerView; } public void addItemDecoration(RecyclerView.ItemDecoration itemDecoration){ mRefreshableView.addItemDecoration(itemDecoration); } public void setAdapter(RecyclerView.Adapter adapter){ mRefreshableView.setAdapter(adapter); } @Override protected boolean isReadyForPullEnd() { return isLastItemVisible(); } @Override protected boolean isReadyForPullStart() { return isFirstItemVisible(); } private boolean isLastItemVisible() { final RecyclerView.Adapter adapter = mRefreshableView.getAdapter(); if (null == adapter || adapter.getItemCount()==0) { if (DEBUG) { Log.d("LOG_TAG", "isLastItemVisible. Empty View."); } return true; } else { final int lastItemPosition = adapter.getItemCount() - 1; final int lastVisiblePosition = getLastVisiblePosition(); if (DEBUG) { Log.d("LOG_TAG", "isLastItemVisible. Last Item Position: " + lastItemPosition + " Last Visible Pos: " + lastVisiblePosition); } /** * This check should really just be: lastVisiblePosition == * lastItemPosition, but PtRListView internally uses a FooterView * which messes the positions up. For me we'll just subtract one to * account for it and rely on the inner condition which checks * getBottom(). */ if (lastVisiblePosition >= lastItemPosition - 1) { final int childIndex = lastVisiblePosition - getFirstVisiblePosition(); final View lastVisibleChild = mRefreshableView.getChildAt(childIndex); if (lastVisibleChild != null) { return lastVisibleChild.getRight() <= mRefreshableView.getRight(); } } } return false; } private int getFirstVisiblePosition(){ int position = 0; RecyclerView.LayoutManager manager = mRefreshableView.getLayoutManager(); if (manager instanceof LinearLayoutManager){ LinearLayoutManager linearLayoutManager = (LinearLayoutManager) manager; return linearLayoutManager.findFirstVisibleItemPosition(); } return position; } private int getLastVisiblePosition(){ int position = 0; RecyclerView.LayoutManager manager = mRefreshableView.getLayoutManager(); if (manager instanceof LinearLayoutManager){ LinearLayoutManager linearLayoutManager = (LinearLayoutManager) manager; return linearLayoutManager.findLastVisibleItemPosition(); } return position; } private boolean isFirstItemVisible() { final RecyclerView.Adapter adapter = mRefreshableView.getAdapter(); if (null == adapter || adapter.getItemCount() ==0) { if (DEBUG) { Log.d("LOG_TAG", "isFirstItemVisible. Empty View."); } return true; } else { /** * This check should really just be: * mRefreshableView.getFirstVisiblePosition() == 0, but PtRListView * internally use a HeaderView which messes the positions up. For * now we'll just add one to account for it and rely on the inner * condition which checks getTop(). */ if (getFirstVisiblePosition() < 1) { final View firstVisibleChild = mRefreshableView.getChildAt(0); if (firstVisibleChild != null) { // return firstVisibleChild.getLeft() >= mRefreshableView.getLeft(); return (firstVisibleChild.getTop()-mAdjustDistance )>= mRefreshableView.getTop(); } } } return false; } }
26ea6e9e26db292fdc9ac1de7c422c76756e8edc
f51582e6907083d8397b68dd29584ca7aaafbad1
/app/src/main/java/com/example/hello/myapplicationmvp/MainActivity.java
78f5c5d1d28fd93e1acb7475ea9e0e0c490e672c
[]
no_license
weizuoming/MyApplicationMVP
cda27a25689f26a348ff9e6961563d8c84f8c5c3
ae5169174efe24da690b8722f53d01f9a760f4ab
refs/heads/master
2021-05-09T04:25:34.125161
2018-01-28T15:50:07
2018-01-28T15:50:07
119,272,031
0
0
null
null
null
null
UTF-8
Java
false
false
2,542
java
package com.example.hello.myapplicationmvp; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.example.hello.myapplicationmvp.model.Deng_bean; import com.example.hello.myapplicationmvp.presenter.Denglu_p; import com.example.hello.myapplicationmvp.util.API; import com.example.hello.myapplicationmvp.view.DengluV_i; import com.example.hello.myapplicationmvp.view.Main2Activity; import com.example.hello.myapplicationmvp.view.Main3Activity; import com.google.gson.Gson; public class MainActivity extends AppCompatActivity implements DengluV_i { private EditText pas; private EditText ph; private Button ligon; private Button reg; private Denglu_p denglu_p; private String msg; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ph = (EditText) findViewById(R.id.phone); pas = (EditText) findViewById(R.id.password); ligon = (Button) findViewById(R.id.ligon); reg = (Button) findViewById(R.id.reg); denglu_p = new Denglu_p(this); reg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent in = new Intent(MainActivity.this, Main2Activity.class); startActivity(in); } }); ligon.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String name = ph.getText().toString(); String password = pas.getText().toString(); denglu_p.getdeat(API.denglu_api, name, password); } }); } @Override public void success(String s) { Gson g = new Gson(); Deng_bean deng_bean = g.fromJson(s, Deng_bean.class); msg = deng_bean.getMsg(); runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show(); if (msg.equals("登录注册")) { Intent in = new Intent(MainActivity.this, Main3Activity.class); startActivity(in); } } }); } @Override public void jumpactivity() { } }
3219d2c0e0852ac9c10d5bfd4efb960f74c26758
7d9214a3738e05c23a03de75aa813ff6322ef46e
/src/main/java/io/thesf/swiftframework/activiti/api/runtime/model/impl/BPMNActivityChainImpl.java
426793798b4b9730098e4b6c54b80efeeb27326d
[ "Apache-2.0" ]
permissive
EDENLIC/swift-activiti-engine
506787d4634e216240e1b361cb6c589bd5a4024f
c0e48a4178090624f72a5748171e791ea49f6ae8
refs/heads/master
2022-12-28T23:51:49.559000
2020-10-03T03:31:18
2020-10-03T03:31:18
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,287
java
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.thesf.swiftframework.activiti.api.runtime.model.impl; import io.thesf.swiftframework.activiti.api.runtime.model.BPMNActivityChain; import org.activiti.api.process.model.BPMNActivity; import org.activiti.bpmn.model.Task; import java.util.ArrayList; import java.util.Collection; import java.util.Objects; /** * Implement of {@link BPMNActivityChain}. * * @author VirtualCry */ public class BPMNActivityChainImpl extends ArrayList<BPMNActivity> implements BPMNActivityChain { public BPMNActivityChainImpl() { } public BPMNActivityChainImpl(Collection<? extends BPMNActivity> activities) { super(activities); } @Override public BPMNActivity getLastActivity() { return this.isEmpty() ? null : this.get(this.size() - 1); } @Override public int getSecondLastTaskIndex() { try { int length = this.size(); int taskCount = 0; for (int i = 1; i < length; i++) { int index = length - i; BPMNActivity activity = this.get(index); if (activity instanceof FreeJumpBPMNActivityImpl // 若是通过自由跳转记录的节点,视为满足条件 || Task.class.isAssignableFrom(Class.forName(activity.getActivityType()))) { taskCount++; if (taskCount == 2) return index; } } return -1; } catch (Exception ex) { throw new RuntimeException(ex); } } @Override public BPMNActivity getSecondLastTask() { int index = this.getSecondLastTaskIndex(); return index < 0 ? null : this.get(index); } @Override public BPMNActivityChain subActivityChain(int beginIndex, int endIndex) { BPMNActivityChain activityChain = new BPMNActivityChainImpl(); for (int i = 0; i < this.size(); i++) { if (i >= beginIndex && i <= endIndex) activityChain.add(this.get(i)); } return activityChain; } @Override public boolean equals(Object o) { if (o instanceof BPMNActivityChain && this.size() == ((BPMNActivityChain) o).size()) { for (int i = 0; i < this.size(); i++) { if (!this.get(i).equals(((BPMNActivityChain) o).get(i))) return false; } return true; } else return false; } @Override public int hashCode() { return Objects.hash(this.stream().map(BPMNActivity::toString).reduce("", (x, y) -> x + "," + y)); } }
a50ba34617b6cbf592cfb5b375f077380cdf9520
19048f0a2d5e31402bd791b2dd594362de44afe3
/java/Spring/CaveOfProgramming/spring-tutorial-14/src/main/java/mx/naui/spring/App.java
ed1a320268891a5eb6a06d4376f56ac8ca888067
[]
no_license
humbertoperdomo/practices
f5f2288f4375cbc507f5d9c5ebf80064b4e946a0
ddc8dd587015e450858e851a2879026c7534f665
refs/heads/master
2021-01-24T06:30:00.405750
2018-11-11T01:57:30
2018-11-11T01:57:30
29,109,838
0
0
null
null
null
null
UTF-8
Java
false
false
519
java
package mx.naui.spring; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; /** * Hello world! * */ public class App { public static void main( String[] args ) { ApplicationContext context = new ClassPathXmlApplicationContext("META-INF/beans.xml"); FruitBasket basket = (FruitBasket) context.getBean("basket"); System.out.println(basket); ((ClassPathXmlApplicationContext)context).close(); } }
3ddcf120c857c6318a4aa410ba1f1d569bdb1b43
3752c2bf2bab660cb0e69a4b02bca2d7879632da
/src/javac/codegen/jr.java
c2695854822b461d01aed0aa0c9854359db3d441
[]
no_license
cqxmzz/tiger-compiler
1fc03bf7ebf96bf392c9dd90325f15f7dba36b70
75a88d1740b6ae560a70e24ac9499ea9a7e3a943
refs/heads/master
2020-06-05T02:59:48.877692
2015-04-17T21:15:21
2015-04-17T21:15:21
24,250,991
4
0
null
null
null
null
UTF-8
Java
false
false
325
java
package javac.codegen; import javac.quad.*; public class jr extends asm { Label label; public jr() { } public String toString() { return "\tjr $ra"; } public String toCode() { return "\tjr $ra"; } public Temp[] getS() { return null; } public Temp[] getD() { return null; } }
9259f65d80d4cb6054fc94baf1d68e5494e022bf
47a9ae8cbe253a4c2784f8c7328a5f79154c92a5
/src/main/java/me/nickyadmin/nickysfixer/utils/GetTps_1_12_R1.java
e4c6419971c81194261473de2432542bd67eec4c
[]
no_license
NickyAdmin/NickysFixer-1.16.5-STABLE
84971390a0fa97636e5428c15ea6ba96b17d4c43
066964c58a47d6ace2b8ba12c3fe1dcf088cf418
refs/heads/main
2023-04-03T07:04:22.485334
2021-04-13T10:03:33
2021-04-13T10:03:33
357,506,065
1
0
null
null
null
null
UTF-8
Java
false
false
480
java
package me.nickyadmin.nickysfixer.utils; import net.minecraft.server.v1_16_R3.MinecraftServer; public class GetTps_1_12_R1 { @SuppressWarnings("deprecation") public static double getTps () { try { try { return (MinecraftServer.getServer().recentTps[0]); } catch (NoClassDefFoundError e) {} } catch (StackOverflowError e) {} return getTps(); } }
c6beacd098ed1b5b4d8ddd34f44c629362502c18
3db5f542f3f8c3b5b0d1f74b9dcd766732e6c822
/backend/src/main/java/com/yashal/locatr/backend/OfyService.java
6d1c4e663fd92178733522423a30c54f4b06d98b
[]
no_license
YashalShakti/Locatr
5dde3e4202ca4136fe38b1856b2265c21c3e8ea0
8d3f209c961ce5c0de180a7ef560df527942aba1
refs/heads/master
2020-05-30T19:40:55.038506
2016-04-16T23:29:44
2016-04-16T23:29:44
56,373,261
0
0
null
null
null
null
UTF-8
Java
false
false
637
java
package com.yashal.locatr.backend; import com.googlecode.objectify.Objectify; import com.googlecode.objectify.ObjectifyFactory; import com.googlecode.objectify.ObjectifyService; /** * Objectify service wrapper so we can statically register our persistence classes * More on Objectify here : https://code.google.com/p/objectify-appengine/ * */ public class OfyService { static { ObjectifyService.register(RegistrationRecord.class); } public static Objectify ofy() { return ObjectifyService.ofy(); } public static ObjectifyFactory factory() { return ObjectifyService.factory(); } }
2005ad0a7494669dab85cd160f8a46a0929fe914
55735bf4e4141b88df3184a0fa213dcdecdc2e74
/app/src/main/java/com/example/zenon/inframatisse/FullscreenActivity.java
096d0922e73fe696506e82b5f2807b8316a73700
[]
no_license
3EHOH/InfraMatisse1
49fa9b97f6e013e357fe2176cbc20afdb7c0d13c
725c13d12105297aee18632628be73e99ae16bbd
refs/heads/master
2021-05-29T22:01:21.078012
2015-06-28T19:47:59
2015-06-28T19:47:59
null
0
0
null
null
null
null
UTF-8
Java
false
false
12,526
java
package com.example.zenon.inframatisse; import android.annotation.TargetApi; import android.app.Activity; import android.content.Context; import android.content.ContextWrapper; import android.graphics.Bitmap; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.view.MotionEvent; import android.view.View; import android.widget.ImageView; import com.example.zenon.inframatisse.util.SystemUiHider; import com.flir.flironesdk.Device; import com.flir.flironesdk.Frame; import com.flir.flironesdk.FrameProcessor; import com.flir.flironesdk.RenderedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.nio.ByteBuffer; import java.util.EnumSet; /** * An example full-screen activity that shows and hides the system UI (i.e. * status bar and navigation/system bar) with user interaction. * * @see SystemUiHider */ public class FullscreenActivity extends Activity implements Device.Delegate, FrameProcessor.Delegate{ /** * Whether or not the system UI should be auto-hidden after * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds. */ private static final boolean AUTO_HIDE = true; /** * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after * user interaction before hiding the system UI. */ private static final int AUTO_HIDE_DELAY_MILLIS = 3000; /** * If set, will toggle the system UI visibility upon interaction. Otherwise, * will show the system UI visibility upon interaction. */ private static final boolean TOGGLE_ON_CLICK = true; /** * The flags to pass to {@link SystemUiHider#getInstance}. */ private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION; /** * The instance of the {@link SystemUiHider} for this activity. */ private SystemUiHider mSystemUiHider; private FrameProcessor frameProcessor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); frameProcessor = new FrameProcessor(this, this, EnumSet.of(RenderedImage.ImageType.VisualYCbCr888Image)); setContentView(R.layout.activity_fullscreen); final View controlsView = findViewById(R.id.fullscreen_content_controls); final View contentView = findViewById(R.id.fullscreen_content); // Set up an instance of SystemUiHider to control the system UI for // this activity. mSystemUiHider = SystemUiHider.getInstance(this, contentView, HIDER_FLAGS); mSystemUiHider.setup(); mSystemUiHider .setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() { // Cached values. int mControlsHeight; int mShortAnimTime; @Override @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) public void onVisibilityChange(boolean visible) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { // If the ViewPropertyAnimator API is available // (Honeycomb MR2 and later), use it to animate the // in-layout UI controls at the bottom of the // screen. if (mControlsHeight == 0) { mControlsHeight = controlsView.getHeight(); } if (mShortAnimTime == 0) { mShortAnimTime = getResources().getInteger( android.R.integer.config_shortAnimTime); } controlsView.animate() .translationY(visible ? 0 : mControlsHeight) .setDuration(mShortAnimTime); } else { // If the ViewPropertyAnimator APIs aren't // available, simply show or hide the in-layout UI // controls. controlsView.setVisibility(visible ? View.VISIBLE : View.GONE); } if (visible && AUTO_HIDE) { // Schedule a hide(). delayedHide(AUTO_HIDE_DELAY_MILLIS); } } }); // Set up the user interaction to manually show or hide the system UI. contentView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (TOGGLE_ON_CLICK) { mSystemUiHider.toggle(); } else { mSystemUiHider.show(); } } }); // Upon interacting with UI controls, delay any scheduled hide() // operations to prevent the jarring behavior of controls going away // while interacting with the UI. findViewById(R.id.dummy_button).setOnTouchListener(mDelayHideTouchListener); } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Trigger the initial hide() shortly after the activity has been // created, to briefly hint to the user that UI controls // are available. delayedHide(100); } /** * Touch listener to use for in-layout UI controls to delay hiding the * system UI. This is to prevent the jarring behavior of controls going away * while interacting with activity UI. */ View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { if (AUTO_HIDE) { delayedHide(AUTO_HIDE_DELAY_MILLIS); } return false; } }; Handler mHideHandler = new Handler(); Runnable mHideRunnable = new Runnable() { @Override public void run() { mSystemUiHider.hide(); } }; /** * Schedules a call to hide() in [delay] milliseconds, canceling any * previously scheduled calls. */ private void delayedHide(int delayMillis) { mHideHandler.removeCallbacks(mHideRunnable); mHideHandler.postDelayed(mHideRunnable, delayMillis); } Device flirDevice; @Override protected void onResume() { super.onResume(); Device.startDiscovery(this, this); } @Override protected void onPause(){ super.onPause(); Device.stopDiscovery(); } @Override public void onTuningStateChanged(Device.TuningState tuningState) { } @Override public void onAutomaticTuningChanged(boolean b) { } @Override public void onDeviceConnected(Device device) { flirDevice = device; device.startFrameStream(new Device.StreamDelegate() { @Override public void onFrameReceived(Frame frame) { frameProcessor.processFrame(frame); } }); } @Override public void onDeviceDisconnected(Device device) { } static int BLACK; @Override public void onFrameProcessed(RenderedImage renderedImage) { final Bitmap imageBitmap = Bitmap.createBitmap(renderedImage.width(), renderedImage.height(), Bitmap.Config.ARGB_8888); final short[] shortPixels = new short[renderedImage.pixelData().length / 2]; imageBitmap.copyPixelsFromBuffer(ByteBuffer.wrap(renderedImage.pixelData())); final ImageView imageView = (ImageView)findViewById(R.id.imageView); runOnUiThread(new Runnable() { @Override public void run() { imageView.setImageBitmap(imageBitmap); //layer all the other ones on top of this, set up as black/blank canvas Bitmap canvas = Bitmap.createBitmap(imageBitmap.getWidth(), imageBitmap.getHeight(), Bitmap.Config.ARGB_8888); Bitmap finalProduct = Bitmap.createBitmap(imageBitmap.getWidth(), imageBitmap.getHeight(), Bitmap.Config.ARGB_8888); for(int j = 0; j < canvas.getWidth(); j++){ for(int k = 0; k < canvas.getHeight(); k++){ canvas.setPixel(j,k, BLACK); finalProduct.setPixel(j,k,BLACK); } } //eventually come up with a user input to decide nFrames, and later for the timer too int nFrames = 10; for(int i = 0; i < nFrames; i++){ //set up a timer to take snap a photo/screencap every X seconds, for now just delay try { Thread.sleep(5000); } catch(InterruptedException ex) { Thread.currentThread().interrupt(); } finalProduct = processImage(shortPixels, canvas); canvas = finalProduct; nFrames++; } saveToInternalStorage(finalProduct); } }); } private Bitmap processImage(short[] shortPixels, Bitmap canvas) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); canvas.compress(Bitmap.CompressFormat.PNG, 100, stream); byte[] canvasArray = stream.toByteArray(); //rewind(); int argbPixelArraySize = canvas.getWidth() * canvas.getHeight() * 4; byte[] argbPixels = new byte[argbPixelArraySize]; boolean[] boolPixels = new boolean[argbPixelArraySize]; final byte aPixValue = (byte) 255; for (int p = 0; p < shortPixels.length; p++) { int destP = p * 4; int tempInC = (shortPixels[p] - 27315) / 100; byte rPixValue; byte gPixValue; byte bPixValue; if (tempInC < 20) { gPixValue = canvasArray[destP + 1]; rPixValue = canvasArray[destP]; bPixValue = canvasArray[destP + 2]; } else if (tempInC < 36) { rPixValue = bPixValue = 0; gPixValue = (byte) 160; } else if (tempInC < 40) { bPixValue = gPixValue = 0; rPixValue = 127; } else if (tempInC < 50) { bPixValue = gPixValue = 0; rPixValue = (byte) 255; } else if (tempInC < 60) { rPixValue = (byte) 255; gPixValue = (byte) 166; bPixValue = 0; } else if (tempInC < 100) { rPixValue = gPixValue = (byte) 255; bPixValue = 0; } else { bPixValue = rPixValue = gPixValue = (byte) 255; } argbPixels[destP + 3] = aPixValue; argbPixels[destP] = rPixValue; argbPixels[destP + 1] = gPixValue; argbPixels[destP + 2] = bPixValue; } canvas.copyPixelsFromBuffer(ByteBuffer.wrap(argbPixels)); return canvas; } private String saveToInternalStorage(Bitmap bitmapImage){ ContextWrapper cw = new ContextWrapper(getApplicationContext()); // path to /data/data/yourapp/app_data/imageDir File directory = cw.getDir("imageDir", Context.MODE_PRIVATE); // Create imageDir File mypath=new File(directory,"profile.jpg"); FileOutputStream fos = null; try { fos = new FileOutputStream(mypath); // Use the compress method on the BitMap object to write image to the OutputStream bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos); fos.close(); } catch (Exception e) { e.printStackTrace(); } return directory.getAbsolutePath(); } }
cc43da9a2481b0bbc08adf534a334bad620f7684
92c1674aacda6c550402a52a96281ff17cfe5cff
/module22/module06/module5/src/main/java/com/android/example/module22_module06_module5/ClassAAG.java
5a63410f0d16517ce73980361c4f311db03b5692
[]
no_license
bingranl/android-benchmark-project
2815c926df6a377895bd02ad894455c8b8c6d4d5
28738e2a94406bd212c5f74a79179424dd72722a
refs/heads/main
2023-03-18T20:29:59.335650
2021-03-12T11:47:03
2021-03-12T11:47:03
336,009,838
0
0
null
null
null
null
UTF-8
Java
false
false
680
java
package com.android.example.module22_module06_module5; public class ClassAAG { private java.lang.String instance_var_1_0 = "SomeString"; private java.lang.String instance_var_1_1 = "SomeString"; public void method0( java.lang.String param0, java.lang.String param1, java.lang.String param2) throws Throwable { } public void method1( java.lang.String param0, java.lang.String param1, java.lang.String param2, java.lang.String param3) throws Throwable { java.lang.String local_var_2_4 = "SomeString"; local_var_2_4.codePoints(); for (int iAb = 0; iAb < 4; iAb++) { java.lang.String local_var_3_0 = "SomeString"; local_var_3_0.chars(); } } }
dcdc39b07d6bc89c2a9e19689ca3e0039e713142
f2f31711745d6b4cd26fcc193dee4e3a2ac3d8af
/src/main/java/com/sdgas/base/DAO.java
a30d8de668b54f09a6e0b9cce4dee0da032e8bcc
[ "Apache-2.0" ]
permissive
sdgas/purchasing
fe173255ead18d89f06d34385c88765501c7cbbe
efd3e25954af5999bc63d2fc9f831d3cd51aee1a
refs/heads/master
2020-04-23T04:20:26.464886
2015-11-13T03:36:15
2015-11-13T03:36:15
28,896,524
0
0
null
null
null
null
UTF-8
Java
false
false
2,876
java
package com.sdgas.base; import java.util.List; import java.util.Map; public interface DAO { /** * 保存实体 * * @param entity the Object to be same */ public void save(Object entity); /** * 更新实体 * * @param entity to be update */ public void update(Object entity); /** * 清队缓存 */ public void clear(); /** * 删除实体 * * @param <T> 实体类 * @param entityId 实体ID(对应DB的主键) */ public <T> void delete(Class<T> entityClass, Object entityId); /** * 删除实体 * * @param entity 实体类 */ public void delete(Object entity); /** * 获取实体 * * @param <T> * @param entityClass 实体类 * @param entityId 实体ID(对应DB的主键) * @return */ public <T> T find(Class<T> entityClass, Object entityId); /** * 获取实体 * * @param <T> * @param entityClass 实体类 * @return */ public <T> List find(Class<T> entityClass); /** * 根据用户的要求查找相关数据 * * @param entityClass 类名 * @param params 属性名值对 * @return 返回一个list集合 */ public <T> List findByFields(Class<T> entityClass, Map<String, Object> params); /** * 根据用户的要求查找相关数据 * * @param entityClass 类名 * @param params 属性名值对 * @return 唯一一个实体 */ public <T> Object findSpecialObject(Class<T> entityClass, Map<String, Object> params); /** * 根据用户的要求模糊查找相关数据 * * @param entityClass 类名 * @param params 属性名值对 * @return 唯一一个实体 */ public <T> List findByFuzzy(Class<T> entityClass, Map<String, Object> params); /** * 通用分页功能 * * @param <T> * @param entityClass * @param fisrtIndex 索引位置 * @param maxResult 每页的对象个数 * @param wherejpql where的查询语句 * @param queryParams 语句的对象设置 * @param orderby 排序 * @return */ public <T> QueryResult<T> getScrollData(Class<T> entityClass, int fisrtIndex, int maxResult, String wherejpql, Object[] queryParams, Map<String, String> orderby); public <T> QueryResult<T> getScrollData(Class<T> entityClass); public <T> QueryResult<T> getScrollData(Class<T> entityClass, int fisrtIndex, int maxResult); public <T> QueryResult<T> getScrollData(Class<T> entityClass, int fisrtIndex, int maxResult, Map<String, String> orderby); public <T> QueryResult<T> getScrollData(Class<T> entityClass, int fisrtIndex, int maxResult, String wherejpql, Object[] queryParams); }
fbc4adfc197de0f795a79229a0e1c99491dc37ee
d233d6795d5714a641eb9e6d75f8523470f53db1
/CoDZombies(OverrideNetwork)/src/me/morgancentral99/override/listeners/PlayerKill.java
de56ce81425e330d90fc17e02fdf2a43ced64fc2
[]
no_license
Morgancentral99/OverrideZombieMinigames
76dae6c52d29e092b877a6977054f9c4673c6475
433da870d9e94cebda408c8c381681a1a5f00c9d
refs/heads/master
2020-12-25T14:48:08.904120
2016-07-14T23:48:33
2016-07-14T23:48:33
63,377,106
0
0
null
null
null
null
UTF-8
Java
false
false
540
java
package me.morgancentral99.override.listeners; public class PlayerKill { //Unused public PlayerKill() { } // @EventHandler // public void onPlayerEntityKill(EntityDeathEvent e) { // LivingEntity entity = e.getEntity(); // Player p = ((LivingEntity) e).getKiller(); // if(entity.getType() == EntityType.ZOMBIE) { // me.josh.networkcoins.API.addCoins(p, 1); // p.sendMessage(ChatColor.GREEN + "You killed a zombie, you have gainned 1 coin! You have a balance of " + me.josh.networkcoins.API.getCoins(p)); // } // } }
adc26979474d5eb5293448b3cf4d3ec47b40cd41
ac45dcb1dd211009ed8cff6034acab1ecf2d8ed0
/src/main/java/com/tqz/pattern/proxy/cglibproxy/CglibTest.java
6882b569dfebc26111f64c7bebca39106802a794
[]
no_license
tian-qingzhao/design-pattern
f42a0384c1f44b3e2878f668d83da30c31eec8cf
5980ec16be924a4622299b52387bd705c5c6989e
refs/heads/master
2023-04-05T11:31:28.966461
2023-02-10T02:50:05
2023-02-10T02:50:05
265,293,741
0
0
null
2023-03-28T22:27:21
2020-05-19T15:57:31
Java
UTF-8
Java
false
false
1,270
java
package com.tqz.pattern.proxy.cglibproxy; import net.sf.cglib.core.DebuggingClassWriter; /** * @Author: tian * @Date: 2020/4/19 23:59 * @Desc: */ public class CglibTest { public static void main(String[] args) { try { //JDK是采用读取接口的信息 //CGLib覆盖父类方法 //目的:都是生成一个新的类,去实现增强代码逻辑的功能 //JDK Proxy 对于用户而言,必须要有一个接口实现,目标类相对来说复杂 //CGLib 可以代理任意一个普通的类,没有任何要求 //CGLib 生成代理逻辑更复杂,效率,调用效率更高,生成一个包含了所有的逻辑的FastClass,不再需要反射调用 //JDK Proxy生成代理的逻辑简单,执行效率相对要低,每次都要反射动态调用 //CGLib 有个坑,CGLib不能代理final的方法 System.setProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY,"E://cglib_proxy_classes"); Customer obj = (Customer) new CglibProxy().getInstance(Customer.class); System.out.println(obj); obj.findLove(); } catch (Exception e) { e.printStackTrace(); } } }
049d799e18aa9baea2d574d9f838a165647a139f
eecce0741782b0d2514fd0595ee7395aa1434af0
/BallBouncer/app/src/test/java/com/justinwise/ballbouncer/ExampleUnitTest.java
b6d7ee8e5dcb1975c656e13176f992c654a3cff6
[]
no_license
wise200/Apps
24509a5f4d145154b76edba6069af72d245069a5
b4ade3a6789d7bb3d8fc387fe81e5ee611a7f02d
refs/heads/master
2020-03-29T08:03:07.601470
2018-11-09T21:55:16
2018-11-09T21:55:16
149,691,984
0
0
null
null
null
null
UTF-8
Java
false
false
404
java
package com.justinwise.ballbouncer; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
8ee86c27dba41ee3dffc06dd8a7fc4734ebbf9ed
e23acfaa284259fecf9f0bccedb8e20ee0779ae7
/rely/src/main/java/com/seesea/rely/thread/ThreadPoolManager.java
3306ba6a86b742d96d8fc51c01969bd0c5a639a9
[]
no_license
xiechongyang7/study
4b1761583fca72bd16b4bc3b1ef2a1c92c789802
f77ade4d9914c14b4476efdffbf454d9d08ad656
refs/heads/master
2022-11-23T11:33:33.400421
2020-11-20T07:32:08
2020-11-20T07:32:08
161,575,180
0
1
null
2022-11-16T11:32:50
2018-12-13T02:51:52
Java
UTF-8
Java
false
false
2,707
java
package com.seesea.rely.thread; import org.slf4j.MDC; import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.*; /** * 线程池管理 * * @author LW * @date 2011-2-12 */ public class ThreadPoolManager { private static ThreadPoolManager tpm = new ThreadPoolManager(); // 线程池维护线程的最少数量 private final static int CORE_POOL_SIZE = 3; // 线程池维护线程的最大数量 private final static int MAX_POOL_SIZE = 10; // 线程池维护线程所允许的空闲时间 private final static int KEEP_ALIVE_TIME = 0; // 线程池所使用的缓冲队列大小 private final static int WORK_QUEUE_SIZE = 10; // 任务调度周期 private final static int TASK_QOS_PERIOD = 10; // 任务缓冲队列 private Queue<Runnable> taskQueue = new LinkedList<Runnable>(); /* * 线程池超出界线时将任务加入缓冲队列 */ final RejectedExecutionHandler handler = new RejectedExecutionHandler() { public void rejectedExecution(Runnable task, ThreadPoolExecutor executor) { taskQueue.offer(task); } }; /* * 将缓冲队列中的任务重新加载到线程池 */ final Runnable accessBufferThread = new Runnable() { public void run() { if (hasMoreAcquire()) { threadPool.execute(taskQueue.poll()); } } }; /* * 创建一个调度线程池 */ final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); /* * 通过调度线程周期性的执行缓冲队列中任务 */ final ScheduledFuture<?> taskHandler = scheduler.scheduleAtFixedRate(accessBufferThread, 0, TASK_QOS_PERIOD, TimeUnit.MILLISECONDS); /* * 线程池 */ final ThreadPoolExecutor threadPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, KEEP_ALIVE_TIME, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(WORK_QUEUE_SIZE), this.handler); /* * 将构造方法访问修饰符设为私有,禁止任意实例化。 */ private ThreadPoolManager() { } /* * 线程池单例创建方法 */ public static ThreadPoolManager newInstance() { return tpm; } public static void addThread(Runnable task) { tpm.addExecuteTask(task); } /* * 消息队列检查方法 */ private boolean hasMoreAcquire() { return !taskQueue.isEmpty(); } /* * 向线程池中添加任务方法 */ public void addExecuteTask(Runnable task) { if (task != null) { threadPool.execute(task); } } }
ef1e8642271a1980c004a590e90913ba9326d757
38febb0e005a5d73672b6b5f4762c07f57711172
/src/ru/mirea/inbo0219/Circle.java
cb9084617afe5e0c9c7b994b223ea44f71608857
[]
no_license
volkondav/Pr3_Ex1-5
dc12c8caceb941f833c88859b0a5957aa8d0eb6c
04d8bf16787243caf0f8dccc0454ee7c2058876b
refs/heads/master
2022-12-24T17:52:39.021415
2020-10-04T14:37:41
2020-10-04T14:37:41
301,145,576
0
0
null
null
null
null
UTF-8
Java
false
false
1,060
java
package ru.mirea.inbo0219; public class Circle extends Shape{ protected double radius; public Circle(){ this.color = "Не задано"; this.filled = false; this.radius = 0; } public Circle(double radius){ this.color = "Не задано"; this.filled = false; this.radius = radius; } public Circle(double radius,String color,boolean filled){ this.radius = radius; this.color = color; this.filled = filled; } public double getRadius() { return radius; } public void setRadius(double radius) { System.out.printf("Радиус до " + this.radius ); this.radius = radius; System.out.println("Радиус после "+this.radius); } double getArea(){ return Math.PI * radius * radius; } double getPerimeter(){ return 2 * Math.PI * radius; } @Override public String toString() { return "Shape: circle, radius: "+this.radius+", color: "+this.color; } }
2ac9c7753e446af927ac657967a46c383d41de08
0037a12985e1c2806f2d4c28939c526e3e0c0f20
/CWMLApp/src/com/cwml/classcontent/AbstractDiarycomment.java
7d6dc62bc1673679c8632135526374ca7d080ff9
[]
no_license
FreeDao/chatwithmylove
15e9e552b1fafdd88cea8acf7f02a76999bbc593
1b46432249d0a1dfa8fb841c047814c7298d5259
refs/heads/master
2021-01-21T03:50:06.172002
2015-02-08T09:21:01
2015-02-08T09:21:01
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,398
java
package com.cwml.classcontent; /** * AbstractDiarycomment entity provides the base persistence definition of the * Diarycomment entity. @author MyEclipse Persistence Tools */ public abstract class AbstractDiarycomment implements java.io.Serializable { // Fields private Integer id; private String diaryid; private String commentusername; private String time; private String content; // Constructors /** default constructor */ public AbstractDiarycomment() { } /** full constructor */ public AbstractDiarycomment(String diaryid, String commentusername, String time, String content) { this.diaryid = diaryid; this.commentusername = commentusername; this.time = time; this.content = content; } // Property accessors public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public String getDiaryid() { return this.diaryid; } public void setDiaryid(String diaryid) { this.diaryid = diaryid; } public String getCommentusername() { return this.commentusername; } public void setCommentusername(String commentusername) { this.commentusername = commentusername; } public String getTime() { return this.time; } public void setTime(String time) { this.time = time; } public String getContent() { return this.content; } public void setContent(String content) { this.content = content; } }
cc287a55cce990bb938f9434eecffc18d4f76025
1799d73e819d20ba34a0dc6ddb4d0940bc2f4a24
/saaj-files-service/src/main/java/info/gyokit/saaj/files/service/SendFilesImpl.java
f2d413d311cc8a017ff6345b9bd374a56f613d0b
[]
no_license
GyokayAli/Java-Web-Services
e9b24b78913afa24350cdfdff913ad296c6739ce
63e3d563734c4e7cade15f4619c91d29874c506f
refs/heads/master
2021-01-11T21:54:43.750266
2017-01-25T09:31:40
2017-01-25T09:31:40
78,873,458
0
0
null
null
null
null
UTF-8
Java
false
false
4,086
java
package info.gyokit.saaj.files.service; import info.gyokit.saaj.files.FileHelper; import java.io.InputStream; import java.util.Iterator; import java.util.UUID; import javax.annotation.Resource; import javax.servlet.ServletContext; import javax.xml.namespace.QName; import javax.xml.soap.AttachmentPart; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPBody; import javax.xml.soap.SOAPBodyElement; import javax.xml.soap.SOAPElement; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPMessage; import javax.xml.ws.Provider; import javax.xml.ws.Service; import javax.xml.ws.ServiceMode; import javax.xml.ws.WebServiceContext; import javax.xml.ws.WebServiceProvider; import javax.xml.ws.handler.MessageContext; /** * * @author Gyokay Ali */ @WebServiceProvider(serviceName = "SendFilesService") @ServiceMode(value = Service.Mode.MESSAGE) public class SendFilesImpl implements Provider<SOAPMessage> { @Resource private WebServiceContext context; @Override public SOAPMessage invoke(SOAPMessage soapRequest) { // Response message SOAPMessage soapResponse = null; // Attachment (file) AttachmentPart attachment = null; try { // Data acquisition from the request message // Acquire the file name SOAPBody soapBody = soapRequest.getSOAPBody(); SOAPBodyElement requestRoot = (SOAPBodyElement) soapBody.getChildElements().next(); Iterator fileIterator = requestRoot.getChildElements(); //get the original file name from the request String fileName = ((SOAPElement) fileIterator.next()).getFirstChild().getNodeValue(); // Acquire the file Iterator attachment_iterator = soapRequest.getAttachments(); while (attachment_iterator.hasNext()) { attachment = (AttachmentPart) attachment_iterator.next(); } // Generating a response message soapResponse = MessageFactory.newInstance().createMessage(); SOAPBody responseSoapBody = soapResponse.getSOAPBody(); SOAPBodyElement responseRoot = responseSoapBody.addBodyElement( new QName("http://service.files.saaj.gyokit.info", "uuid")); SOAPElement soapElement = responseRoot.addChildElement( new QName("http://service.files.saaj.gyokit.info", "value")); // Set up a basic validation if (null == attachment) { soapElement.addTextNode("No file attached!"); } else { //generate UUID to be the file name UUID fileNameUUID = UUID.randomUUID(); //stream to carry the attachment content InputStream inputStream = attachment.getRawContent(); //get MIME from attachment String mimeType = attachment.getContentType(); //initialize and get the context ServletContext servletContext = (ServletContext) context.getMessageContext().get(MessageContext.SERVLET_CONTEXT); //gets the directory to keep the files received by the Web Service String fileDir = servletContext.getInitParameter("FILEDIR"); //check if the directory given in the context exists, else throws exception if (fileDir == null || fileDir.isEmpty()) { throw new java.lang.IllegalArgumentException("FILEDIR Initialization Parameter is empty. Please configure it in web.xml!"); } //save received data into files FileHelper.saveDataToDir(fileNameUUID, fileName, inputStream, mimeType, fileDir); //set response message for uuid soapElement.addTextNode(fileNameUUID.toString()); } } catch (SOAPException e) { System.out.println("SOAP Exception: " + e.getMessage()); } return soapResponse; } }
0c12edc1b7b286ddcea779f86912da039691b10c
08b837b05bd51b62f0fca18031b6ffe34cda7ecd
/integration-tests/idm-aerogear-security/src/test/java/org/jboss/aerogear/jaxrs/rest/producer/PicketLinkDefaultUsers.java
3e71014bbb8a4964f6845e47285fbb93e90b1f78
[]
no_license
jboss-security-qe/picketlink-integration-tests
991b6bd8b8d040d89c55fd57c42408b585c2fc9c
b6ff77ccfa977bc4901c928dbc5dff131c832a15
refs/heads/pl-2.5
2021-01-18T07:49:01.961617
2014-08-28T12:01:32
2014-09-15T07:15:42
10,521,945
0
0
null
2014-06-12T07:00:48
2013-06-06T08:20:49
Java
UTF-8
Java
false
false
4,501
java
/** * JBoss, Home of Professional Open Source * Copyright Red Hat, Inc., and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jboss.aerogear.jaxrs.rest.producer; import org.jboss.aerogear.jaxrs.demo.user.UserRoles; import org.picketlink.idm.IdentityManager; import org.picketlink.idm.PartitionManager; import org.picketlink.idm.RelationshipManager; import org.picketlink.idm.credential.Password; import org.picketlink.idm.model.basic.BasicModel; import org.picketlink.idm.model.basic.Realm; import org.picketlink.idm.model.basic.Role; import org.picketlink.idm.model.basic.User; import javax.annotation.PostConstruct; import javax.ejb.Singleton; import javax.ejb.Startup; import javax.inject.Inject; import java.util.logging.Level; import java.util.logging.Logger; @Singleton @Startup public class PicketLinkDefaultUsers { public static final String DEFAULT_JOHN_LOGIN_NAME = "john"; public static final String DEFAULT_JOHN_EMAIL = "[email protected]"; public static final String DEFAULT_JOHN_FIRST_NAME = "John"; public static final String DEFAULT_JOHN_LAST_NAME = "Doe"; public static final String DEFAULT_JOHN_PASSWORD = "123"; public static final String DEFAULT_AGNES_LOGIN_NAME = "agnes"; public static final String DEFAULT_AGNES_EMAIL = "[email protected]"; public static final String DEFAULT_AGNES_FIRST_NAME = "Agnes"; public static final String DEFAULT_AGNES_LAST_NAME = "Doe"; public static final String DEFAULT_AGNES_PASSWORD = "123"; @Inject private PartitionManager partitionManager; private IdentityManager identityManager; private RelationshipManager relationshipManager; public static final Logger LOG = Logger.getLogger(PicketLinkDefaultUsers.class.getName()); /** * <p> * Loads some users during the first construction. * </p> */ @PostConstruct public void create() { LOG.log(Level.INFO, "PartitionManager: {0}", partitionManager); // this need to be here since APE from tests cleans it so that partition does not exist anymore Realm defaultRealm = partitionManager.getPartition(Realm.class, Realm.DEFAULT_REALM); if (defaultRealm == null) { this.partitionManager.add(new Realm(Realm.DEFAULT_REALM)); } this.identityManager = partitionManager.createIdentityManager(); this.relationshipManager = partitionManager.createRelationshipManager(); // John User john = newUser(DEFAULT_JOHN_LOGIN_NAME, DEFAULT_JOHN_EMAIL, DEFAULT_JOHN_FIRST_NAME, DEFAULT_JOHN_LAST_NAME); this.identityManager.updateCredential(john, new Password(DEFAULT_JOHN_PASSWORD)); // Agnes User agnes = newUser(DEFAULT_AGNES_LOGIN_NAME, DEFAULT_AGNES_EMAIL, DEFAULT_AGNES_FIRST_NAME, DEFAULT_AGNES_LAST_NAME); this.identityManager.updateCredential(agnes, new Password(DEFAULT_AGNES_PASSWORD)); Role roleUser = new Role(UserRoles.USER); Role roleAdmin = new Role(UserRoles.ADMIN); this.identityManager.add(roleUser); this.identityManager.add(roleAdmin); // Grant roles to them grantRoles(john, roleAdmin); grantRoles(agnes, roleUser); } private void grantRoles(User user, Role role) { BasicModel.grantRole(relationshipManager, user, role); } private User newUser(String loginName, String email, String firstName, String lastName) { User user = new User(loginName); user.setEmail(email); user.setFirstName(firstName); user.setLastName(lastName); /* * Note: Password will be encoded in SHA-512 with SecureRandom-1024 salt See * http://lists.jboss.org/pipermail/security-dev/2013-January/000650.html for more information */ this.identityManager.add(user); return user; } }
7735032e7088acb9b1d1380138f2075aacbd9c19
94fda551ee96334ffd5d4130a4ac0d491ba885b4
/ssmDemo/src/com/gec/controller/UserController.java
0956473317b91e5d21b8317c05934ee68e026ca6
[]
no_license
Cool-Birce/codeDepository
78fea2b331414bba09944496e0a5be6eb4f3a200
6ecf70bc9cc106deb2d63d8530250b250a8fde9d
refs/heads/master
2023-01-12T16:15:41.644264
2020-11-20T12:01:11
2020-11-20T12:01:27
313,796,936
0
0
null
null
null
null
UTF-8
Java
false
false
1,432
java
package com.gec.controller; import com.gec.pojo.Product; import com.gec.pojo.User; import com.gec.service.ProductService; import com.gec.service.UserService; import org.mybatis.spring.annotation.MapperScan; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpSession; import java.util.List; /** * @author Brice * @title: UserController * @projectName springDemo * @description: TODO * @date 2020/11/1018:43 */ @Controller @RequestMapping("/user") public class UserController { @Autowired private UserService userService; @Autowired private ProductService productService; private ModelAndView mav; @RequestMapping("/login") @ResponseBody public String login(@RequestBody User user) { mav = new ModelAndView(); User user1 = userService.login(user.getUsername(), user.getPassword()); if (user != null) { return "1"; } else { return "用户不存在或者密码错误"; } } @RequestMapping("/loginView") public ModelAndView loginView() { return new ModelAndView("login"); } }
f3189b62fa292b6524cf01f862c0138c98a6f700
595bfaa1a5d66e784c857ba95a253ad1ef00a9c3
/MSThesis-resurrected/MS Thesis/src/tr/edu/metu/ceng/ms/thesis/spea2/util/comparators/OverallConstraintViolationComparator.java
cdb080cf148ff91d6d6f4e81ba826ae2a6627bf9
[]
no_license
tugcemoral/MS
5f4b2a6506bfd65ab175f8f27da909e9c508b221
2d89781b1b896dea366720206a0d930cd3f78c19
refs/heads/master
2020-06-02T03:44:28.939540
2015-01-21T09:10:59
2015-01-21T09:10:59
1,972,300
1
1
null
null
null
null
UTF-8
Java
false
false
2,674
java
// OverallConstraintViolationComparator.java // // Author: // Antonio J. Nebro <[email protected]> // Juan J. Durillo <[email protected]> // // Copyright (c) 2011 Antonio J. Nebro, Juan J. Durillo // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser 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 Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package tr.edu.metu.ceng.ms.thesis.spea2.util.comparators; import tr.edu.metu.ceng.ms.thesis.spea2.integration.core.SPEA2Solution; /** * This class implements a <code>Comparator</code> (a method for comparing * <code>Solution</code> objects) based on the overall constraint violation of * the solucions, as in NSGA-II. */ public class OverallConstraintViolationComparator implements IConstraintViolationComparator { /** * Compares two solutions. * @param o1 Object representing the first <code>Solution</code>. * @param o2 Object representing the second <code>Solution</code>. * @return -1, or 0, or 1 if o1 is less than, equal, or greater than o2, * respectively. */ public int compare(Object o1, Object o2) { double overall1, overall2; // overall1 = ((SPEA2Solution)o1).getOverallConstraintViolation(); // overall2 = ((SPEA2Solution)o2).getOverallConstraintViolation(); overall1 = 0d; overall2 = 0d; if ((overall1 < 0) && (overall2 < 0)) { if (overall1 > overall2){ return -1; } else if (overall2 > overall1){ return 1; } else { return 0; } } else if ((overall1 == 0) && (overall2 < 0)) { return -1; } else if ((overall1 < 0) && (overall2 == 0)) { return 1; } else { return 0; } } // compare /** * Returns true if solutions s1 and/or s2 have an overall constraint * violation < 0 */ public boolean needToCompare(SPEA2Solution s1, SPEA2Solution s2) { boolean needToCompare ; needToCompare = (/*s1.getOverallConstraintViolation()*/ 0 < 0) || (/*s2.getOverallConstraintViolation()*/ 0 < 0); return needToCompare ; } } // OverallConstraintViolationComparator
9f77560ac449ad9a30d68bc6a3232470b6b9736e
106ef6d6b981e3ecfd94c5cf8153fdcc1340b917
/jplugin-core/jplugin-common-kits/src/main/java/net/jplugin/common/kits/StringKit.java
39ed40f4b4318f55bbd09d89ae22f5b949d3b2aa
[]
no_license
sd4324530/jplugin
a45ed804975c8eefcfe83df01b2337907b10c222
7d17343f5cefb9ec07e995a4ad1a6b852ec80471
refs/heads/master
2023-09-02T16:30:15.120030
2023-06-26T01:56:38
2023-06-26T01:56:38
44,083,012
0
0
null
2015-12-17T10:57:47
2015-10-12T03:53:17
Java
UTF-8
Java
false
false
24,886
java
package net.jplugin.common.kits; /* * 修改历史 版本 修订人 修订时间 修订原因 */ import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Array; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.StringTokenizer; import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; public class StringKit { final static String[] SBC = { ",", "。", ";", "“", "”", "?", "!", "(", ")", ":", "——", "、" }; final static String[] DBC = { ",", ".", ";", "\"", "\"", "?", "!", "(", ")", ":", "_", "," }; public static String replaceBatch(String str,String ... arg){ if (arg==null) return str; for (int i=0;i<arg.length;i+=2){ str = StringKit.replaceStr(str, arg[i], arg[i+1]); } return str; } public static boolean eqOrNull(String s1,String s2) { return (s1==null && s2==null) || (s1!=null && s1.equals(s2)); } /** * 去除字符串两端空格 如果字符串是空的返加null * * @Param String * @return String */ public static String trim(String str) { if (str == null) return null; str = str.trim(); if (str.length() == 0) return null; return str; } public static String replaceStr(String str, String oldStr, String newStr) { int pos1 = 0; int pos2 = 0; StringBuffer retu = new StringBuffer(); if (str != null && str.length() > 0) { for (pos2 = str.indexOf(oldStr, pos1); pos2 != -1; pos2 = str .indexOf(oldStr, pos1)) { retu.append(str.substring(pos1, pos2) + newStr); pos1 = pos2 + oldStr.length(); } retu.append(str.substring(pos1)); } return retu.toString(); } /** * 设置字符串首字母为大写 */ public static String cap(String str) { if (str == null) return null; StringBuffer sb = new StringBuffer(); sb.append(Character.toUpperCase(str.charAt(0))); sb.append(str.substring(1).toLowerCase()); return sb.toString(); } /** * 判断字符串是否是包含a-z, A-Z, 0-9, _(下划线) */ public static boolean isWord(String str) { if (str == null) return false; char[] ch = str.toCharArray(); int i; for (i = 0; i < str.length(); i++) { if ((!Character.isLetterOrDigit(ch[i])) && (ch[i] != '_')) return false; } return true; } //允许是负数 public static boolean isNumAllowNig(String str){ if (str.startsWith("-")){ return isNum(str.substring(1)); }else{ return isNum(str); } } /** * 判断字符串是否数字 */ public static boolean isNum(String str) { if (str == null || str.length() <= 0) return false; char[] ch = str.toCharArray(); for (int i = 0; i < str.length(); i++) if (!Character.isDigit(ch[i])) return false; return true; } /** * 判断字符串是否为实数 */ public static boolean isNumEx(String str) { if (str == null || str.length() <= 0) return false; char[] ch = str.toCharArray(); // 判断第一个字符是否-号 int index = 0; if (ch[0] == '-') index = 1; for (int i = index, comcount = 0; i < str.length(); i++) { if (!Character.isDigit(ch[i])) { if (ch[i] != '.') return false; else if (i == 0 || i == str.length() - 1) return false; // .12122 or 423423. is not a real number else if (++comcount > 1) return false; // 12.322.23 is not a real number } } return true; } /** * 替换字符串,sOld sNew的大小必须相同 */ public static String replaceStrEq(String sReplace, String sOld, String sNew) { if (sReplace == null || sOld == null || sNew == null) return null; int iLen = sReplace.length(); int iLenOldStr = sOld.length(); int iLenNewStr = sNew.length(); if (iLen <= 0 || iLenOldStr <= 0 || iLenNewStr <= 0) return sReplace; if (iLenOldStr != iLenNewStr) return sReplace; int[] iIndex = new int[iLen]; iIndex[0] = sReplace.indexOf(sOld, 0); if (iIndex[0] == -1) return sReplace; int iIndexNum = 1; while (true) { iIndex[iIndexNum] = sReplace.indexOf(sOld, iIndex[iIndexNum - 1] + 1); if (iIndex[iIndexNum] == -1) break; iIndexNum++; } char[] caReplace = sReplace.toCharArray(); char[] caNewStr = sNew.toCharArray(); for (int i = 0; i < iIndexNum; i++) { for (int j = 0; j < iLenOldStr; j++) { caReplace[j + iIndex[i]] = caNewStr[j]; } } return new String(caReplace); } /** * 替换字符串 */ @SuppressWarnings("unchecked") public static String replaceStrEx(String sReplace, String sOld, String sNew) { if (sReplace == null || sOld == null || sNew == null) return null; int iLen = sReplace.length(); int iLenOldStr = sOld.length(); int iLenNewStr = sNew.length(); if (iLen <= 0 || iLenOldStr <= 0 || iLenNewStr < 0) return sReplace; int[] iIndex = new int[iLen]; iIndex[0] = sReplace.indexOf(sOld, 0); if (iIndex[0] == -1) return sReplace; int iIndexNum = 1; while (true) { iIndex[iIndexNum] = sReplace.indexOf(sOld, iIndex[iIndexNum - 1] + 1); if (iIndex[iIndexNum] == -1) break; iIndexNum++; } ArrayList vStore = new ArrayList(); String sub = sReplace.substring(0, iIndex[0]); if (sub != null) vStore.add(sub); int i = 1; for (i = 1; i < iIndexNum; i++) { vStore.add(sReplace .substring(iIndex[i - 1] + iLenOldStr, iIndex[i])); } vStore.add(sReplace.substring(iIndex[i - 1] + iLenOldStr, iLen)); StringBuffer sbReplaced = new StringBuffer(""); for (i = 0; i < iIndexNum; i++) { sbReplaced.append(vStore.get(i) + sNew); } sbReplaced.append(vStore.get(i)); return sbReplaced.toString(); } /** * 分隔字符串 */ public static String[] splitStr(String sStr, String sSplitter) { if (sStr == null || sStr.length() <= 0 || sSplitter == null || sSplitter.length() <= 0) return null; String[] saRet = null; int[] iIndex = new int[sStr.length()]; iIndex[0] = sStr.indexOf(sSplitter, 0); if (iIndex[0] == -1) { saRet = new String[1]; saRet[0] = sStr; return saRet; } int iIndexNum = 1; while (true) { iIndex[iIndexNum] = sStr.indexOf(sSplitter, iIndex[iIndexNum - 1] + 1); if (iIndex[iIndexNum] == -1) break; iIndexNum++; } Vector vStore = new Vector(); int iLen = sSplitter.length(); int i = 0; String sub = null; for (i = 0; i < iIndexNum + 1; i++) { if (i == 0) sub = sStr.substring(0, iIndex[0]); else if (i == iIndexNum) sub = sStr.substring(iIndex[i - 1] + iLen, sStr.length()); else sub = sStr.substring(iIndex[i - 1] + iLen, iIndex[i]); if (sub != null && sub.length() > 0) vStore.add(sub); } if (vStore.size() <= 0) return null; saRet = new String[vStore.size()]; Enumeration e = vStore.elements(); for (i = 0; e.hasMoreElements(); i++) saRet[i] = (String) e.nextElement(); return saRet; } /** * 以sContacter为分隔符连接字符串数组saStr */ public static String contactStr(String[] saStr, String sContacter) { if (saStr == null || saStr.length <= 0 || sContacter == null || sContacter.length() <= 0) return null; StringBuffer sRet = new StringBuffer(""); for (int i = 0; i < saStr.length; i++) { if (i == saStr.length - 1) sRet.append(saStr[i]); else sRet.append(saStr[i] + sContacter); } return sRet.toString(); } /** * 转换整型数组为字符串 */ public static String contactStr(int[] saStr, String sContacter) { if (saStr == null || saStr.length <= 0 || sContacter == null || sContacter.length() <= 0) return null; StringBuffer sRet = new StringBuffer(""); for (int i = 0; i < saStr.length; i++) { if (i == saStr.length - 1) sRet.append(new Integer(saStr[i])); else sRet.append(new Integer(saStr[i]) + sContacter); } return sRet.toString(); } /** * 排序字符串数组 */ public static String[] sortByLength(String[] saSource, boolean bAsc) { if (saSource == null || saSource.length <= 0) return null; int iLength = saSource.length; String[] saDest = new String[iLength]; for (int i = 0; i < iLength; i++) saDest[i] = saSource[i]; String sTemp = ""; int j = 0, k = 0; for (j = 0; j < iLength; j++) for (k = 0; k < iLength - j - 1; k++) { if (saDest[k].length() > saDest[k + 1].length() && bAsc) { sTemp = saDest[k]; saDest[k] = saDest[k + 1]; saDest[k + 1] = sTemp; } else if (saDest[k].length() < saDest[k + 1].length() && !bAsc) { sTemp = saDest[k]; saDest[k] = saDest[k + 1]; saDest[k + 1] = sTemp; } } return saDest; } public static String compactStr(String str) { if (str == null) return null; if (str.length() <= 0) return ""; String sDes = new String(str); int iBlanksAtStart = 0; int iLen = str.length(); while (sDes.charAt(iBlanksAtStart) == ' ') if (++iBlanksAtStart >= iLen) break; String[] saDes = splitStr(sDes.trim(), " "); if (saDes == null) return null; int i = 0; for (i = 0; i < saDes.length; i++) { saDes[i] = saDes[i].trim(); } sDes = contactStr(saDes, " "); StringBuffer sBlank = new StringBuffer(""); for (i = 0; i < iBlanksAtStart; i++) sBlank.append(" "); return sBlank.toString() + sDes; } /** * 转换sbctodbc */ public static String symbolSBCToDBC(String sSource) { if (sSource == null || sSource.length() <= 0) return sSource; int iLen = SBC.length < DBC.length ? SBC.length : DBC.length; for (int i = 0; i < iLen; i++) sSource = replaceStrEx(sSource, SBC[i], DBC[i]); return sSource; } /** * 转换dbctosbc */ public static String symbolDBCToSBC(String sSource) { if (sSource == null || sSource.length() <= 0) return sSource; int iLen = SBC.length < DBC.length ? SBC.length : DBC.length; for (int i = 0; i < iLen; i++) sSource = replaceStrEx(sSource, DBC[i], SBC[i]); return sSource; } /** * 判断是否email地址 */ public static boolean isEmailUrl(String str) { if ((str == null) || (str.length() == 0)) return false; if ((str.indexOf('@') > 0) && (str.indexOf('@') == str.lastIndexOf('@'))) { if ((str.indexOf('.') > 0) && (str.lastIndexOf('.') > str.indexOf('@'))) { return true; } } return false; } /** * 判断是否email地址 */ public static boolean isEmailAddress(String str) { if (str == null || str.length() <= 0) return false; int iCommonCount = 0; int iAltCount = 0; char[] chEmail = str.trim().toCharArray(); for (int i = 0; i < chEmail.length; i++) { if (chEmail[i] == ' ') return false; else if (chEmail[i] == '.') { if (i == 0 || (i == chEmail.length - 1)) return false; } else if (chEmail[i] == '@') { if (++iAltCount > 1 || i == 0 || i == chEmail.length - 1) return false; } } if (str.indexOf('.') < str.indexOf('@')) return false; return true; } /** * 格式化日期 * * @param java * .util.Date date * @param String * newFormat * @return String example formatDate(date, "MMMM dd, yyyy") = July 20, 2000 */ public static String formatDate(Date date, String newFormat) { if (date == null || newFormat == null) return null; java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat( newFormat); return formatter.format(date); } /** * 将日期字符串转换成java.util.Date类型对象 * * @param dateString * @param format * 默认使用yyyy-MM-dd格式 * */ public final static Date string2Date(String dateString, String format) { if (null == dateString || dateString.equals("")) return null; if (null == format || format.equals("")) format = "yyyy-MM-dd"; Date date = new Date(); SimpleDateFormat formatter = new SimpleDateFormat(format); try { date = formatter.parse(dateString); } catch (Exception ex) { // ex.printStackTrace() ; date = null; } return date; } /** * 将Null的String转换为空字符串 */ public static String cEmpty(String s) { if (s == null) return ""; return s; } /** * 将空字符串转换为Null */ public static String cNull(String s) { if (s == null) return null; if (s.trim().length() == 0) return null; return s; } /** * 如果s为空或Null, 则返回"NUll", 否则给s两边加上单引号返回。用在写数据库的时候。 */ public static String nullString(String s) { if (s == null) return "Null"; if (s.trim().length() == 0) return "Null"; return "'" + s.trim() + "'"; } public static String filterString(String s, String t) { String a = s; int i, j; j = t.length(); while ((i = a.indexOf(t)) != -1) { a = a.substring(0, i - 1) + a.substring(i + j); } return a; } /** * The method is used to get the bytes number of string */ public static int getTotalBytes(String srcString) { if (srcString == null) return 0; int result = 0; byte[] bytes = srcString.getBytes(); for (int i = 0; i < bytes.length; i++) { if (bytes[i] != 0) result++; ; } return result; } /** * check the given string to see if it's null or empty string */ public static boolean isEmpty(String s) { if (s == null) return true; if (s.trim().length() == 0) return true; return false; } /** * 检查是否匹配,可以带* * * @param s1 * @param s2 * @return */ public static boolean isStrSuite(String ssub, String sparent) { ssub = ssub.trim(); sparent = sparent.trim(); String[] subarr = StringKit.splitStr(ssub, " "); String[] pararr = StringKit.splitStr(sparent, " "); return isStringArraySuite(subarr, pararr); } /** * 检查是否匹配,可以带* * * @param subarr * @param pararr * @return */ public static boolean isStringArraySuite(String[] subarr, String[] pararr) { if (subarr.length > pararr.length) return false; for (int i = 0; i < subarr.length; i++) { if (subarr[i].equals("*")) continue; if (pararr[i].equals("*")) continue; if (!subarr[i].equals(pararr[i])) return false; } return true; } public static String arrToString(Object arr) { String ret = "\nlen=" + Array.getLength(arr); for (int i = 0; i < Array.getLength(arr); i++) { ret = ret + "\nitem[" + i + "]=" + Array.get(arr, i); } return ret; } public static String mapToString(Map map) { String ret = "\nlen=" + map.keySet().size(); Iterator it = map.keySet().iterator(); while (it.hasNext()) { Object key = it.next(); ret = ret + "\nkey[" + key + "]" + " value=" + map.get(map.get(key)); } return ret; } /** * 判断是否为空指针或者空字符 * * @param str * @return */ public static boolean isNotNullAndBlank(String str) { if (isNullOrBlank(str)) return false; else return true; } /** * 判断是否为空指针或者空字符 * * @param str * @return */ public static boolean isNullOrBlank(String str) { if (isNull(str) || str.equals("") || str.equals("null")) return true; else return false; } /** * 判断是否为空指针 * * @param str * @return */ public static boolean isNull(String str) { if (str == null || str.trim().length() == 0) { return true; } else { return false; } } /** * 判断是否为空指针 * * @param str * @return */ public static boolean isNotNull(String str) { if (str == null || str.trim().length() == 0) return false; else return true; } /** * 将空指针转成空字符 * * @param str * @return */ public static String ifNullToBlank(String str) { if (isNotNull(str) && !(str.trim().equals("null"))) return str.trim(); else return ""; } public static String ifNullToBlank(Object obj) { String ret = ""; String s = String.valueOf(obj); if (s == null || "".equals(s) || "null".equals(s) || "NULL".equals(s)) ret = ""; else ret = s; return ret; } public static final String escapeXML(String string) { // Check if the string is null or zero length -- if so, return // what was sent in. if (string == null || string.length() == 0) { return string; } char[] sArray = string.toCharArray(); StringBuffer buf = new StringBuffer(sArray.length); char ch; for (int i = 0; i < sArray.length; i++) { ch = sArray[i]; if (ch == '<') { buf.append("&lt;"); } else if (ch == '&') { buf.append("&amp;"); } else if (ch == '"') { buf.append("&quot;"); } else { buf.append(ch); } } return buf.toString(); } public static String[] splitStrWithBlank(String str, String delim) { if (str == null) { return null; } if (str.trim().equals("")) { return null; } List list = new ArrayList(); int index = 0; while ((index = str.indexOf(delim)) >= 0) { list.add(str.substring(0, index)); str = str.substring(index + 1, str.length()); } list.add(str); String[] strs = new String[list.size()]; list.toArray(strs); return strs; } public static char getCharAtPosDefaultZero(String s, int pos) { if (s == null) return '0'; if (s.length() <= pos) return '0'; return s.charAt(pos); } /** * 设置字符串的制定位置(0表示第一个字符)字符。 如果字符串长度小于 位置+1 ,则首先给字符串 补充0 允许传入参数为null * * @param extend2 * @param pos_is_allow_sendback * @param flag * @return */ public static String setCharAtPosAppendZero(String s, int pos, char c) { if (s == null) s = ""; while (pos > s.length() - 1) { s = s + '0'; } String preString, afterString; if (pos == 0) preString = ""; else preString = s.substring(0, pos); if (pos == s.length() - 1) afterString = ""; else afterString = s.substring(pos + 1); return preString + c + afterString; } /** * @param stream * @param encode * @throws IOException */ public static String changeStreamToString(InputStream stream, String encode) throws IOException { byte[] b100k = new byte[200000]; int pos = 0; while (true) { int len = stream.read(b100k, pos, b100k.length - pos); if (len <= 0) break; else pos = pos + len; } if (pos >= b100k.length - 1) { throw new IOException("ERROR:The stream size is more than " + b100k.length + " bytes"); } return new String(b100k, 0, pos, encode); } public static String fillBlank(String s, int n, boolean isLeft) { if (s.length() >= n) return s; for (int i = s.length(); i < n; i++) { if (isLeft) { s = " " + s; } else { s = s + " "; } } return s; } public static String replaceBlanks(String s) { Pattern ptn = Pattern.compile("\\t|\r|\n"); Matcher mt = ptn.matcher(s); return mt.replaceAll(""); } public static String replaceScriptKeyword(String src) { Pattern ptn = Pattern.compile("<script>"); Matcher mt = ptn.matcher(src); src = mt.replaceAll("<scriptValue>"); ptn = Pattern.compile("</script>"); mt = ptn.matcher(src); return mt.replaceAll("</scriptValue>"); } /** * * @param version1 * @param version2 * @return 1 0 -1 */ public static int compareVersion(String version1, String version2) { StringTokenizer st1 = new StringTokenizer(version1, "."); StringTokenizer st2 = new StringTokenizer(version2, "."); ArrayList al1 = new ArrayList(); ArrayList al2 = new ArrayList(); while (st1.hasMoreTokens()) { al1.add(st1.nextToken()); } while (st2.hasMoreTokens()) { al2.add(st2.nextToken()); } int size1 = al1.size(); int size2 = al2.size(); for (int i = 0; i < size1 && i < size2; i++) { int v1 = Integer.parseInt((String) al1.get(i)); int v2 = Integer.parseInt((String) al2.get(i)); if (v1 > v2) return 1; if (v1 < v2) return -1; } if (size1 > size2) return 1; if (size1 < size2) return -1; return 0; } /** * 计算String的native字符串长度 * * @return java.lang.String */ public static int nativeLength(String s) { if (s == null || s.length() == 0) { return 0; } int length = 0; for (int i = 0; i < s.length(); i++) { if (s.charAt(i) >= 0x100) { length = length + 3; } else { length++; } } return length; } public final static int MAX_VARCHAR_PREPARE_LENGTH = 1000; /** * 2005-11-7 添加对oracle数据库中长字符串字段的处理, 解决oracle jdbc的setString超过1280字节时的异常。 * * @param aValueList * @param aDataTypes * @return */ public static String varcharSQLString(List retList, String value) { if (value != null && (nativeLength(value) > MAX_VARCHAR_PREPARE_LENGTH)) { // modify by wangkq 2007/4/4 // 原来将字符串进行拆分的算法不正确,采用DataUtil.nativeLength中获取 // 字符串长度方法来进行字符串分割 String sql = "?"; StringBuffer buff = new StringBuffer(""); int len = 0; int sLen = value.length(); for (int i = 0; i < sLen; i++) { char c = value.charAt(i); if (c >= 0x100) { if ((len + 3) > MAX_VARCHAR_PREPARE_LENGTH) { retList.add(buff.toString()); sql = sql.concat(" || ?"); buff = new StringBuffer(String.valueOf(c)); len = 3; continue; } len = len + 3; } else { len++; } buff.append(c); if (len == MAX_VARCHAR_PREPARE_LENGTH) { retList.add(buff.toString()); if (i < (sLen - 1)) sql = sql.concat(" || ?"); buff = new StringBuffer(""); len = 0; } } if (len > 0) { retList.add(buff.toString()); } return sql; } else { retList.add(value); return null; } } /** * @param name * @param name2 * @return */ public static int compare(String s1, String s2) { for (int i=0;i<s1.length() && i<s2.length();i++){ char c1 = s1.charAt(i); char c2 = s2.charAt(i); if (c1>c2) return 1; if (c1<c2) return -1; } //字符比完了,还无结果,比长度 if (s1.length() >s2.length()) return 1; if (s1.length() <s2.length()) return -1; return 0; } public static void main(String[] args) { System.out.println(compare("ab","ab")); System.out.println(compare("","")); System.out.println(compare("ab","ac")); System.out.println(compare("ac","ab")); System.out.println(compare("ab","abc")); } public static String null2Empty(String hcond) { if (hcond==null) return ""; return hcond; } public static String repaceFirst(String s, String toReplace, String replacement) { int pos = s.indexOf(toReplace); if (pos<0) return s; return s.substring(0,pos)+replacement + s.substring(pos + toReplace.length()); } public static String repaceFirstIgnoreCase(String s, String toReplace, String replacement) { int pos = s.toUpperCase().indexOf(toReplace.toUpperCase()); if (pos<0) return s; return s.substring(0,pos)+replacement + s.substring(pos + toReplace.length()); } // public static Map<String, String> trim(Map<String, String> c) { // Map<String,String> result = new HashMap<String, String>(); // for (Entry<String, String> en:c.entrySet()) { // String k = trim(en.getKey()); // String v = trim(en.getValue()); // if (StringKit.isNotNull(k)) { // result.put(k, v); // } // } // return result; // } public static String[] splitStrAndTrim(String str, String spliter) { String[] result = splitStr(str, spliter); if (result==null) return null; String[] newArr = new String[result.length]; for (int i=0;i<result.length;i++) { newArr[i] = result[i].trim(); } return newArr; } public static String list2String(List<Object> bindings) { StringBuffer sb = new StringBuffer(); for (Object b:bindings) { sb.append(b).append(" , "); } return sb.toString(); } }
daf0b9de5253c69036dd52a24a03d33278331e2e
6cfc5a9457ee116759cbfb0798220a073d964b0f
/src/main/java/duke/commands/Delete.java
d5375e8cf468d25cb9769a631549c0b8b031f87f
[]
no_license
zhuoyang125/ip
0925a3589c5adeb3f9b24972d56fe828f907bac1
ac6e073f051999c4762ac7870a1a7ea015f58cd2
refs/heads/master
2023-08-13T00:21:58.095915
2021-09-20T06:34:40
2021-09-20T06:34:40
397,143,428
0
0
null
2021-09-10T05:50:17
2021-08-17T07:00:11
Java
UTF-8
Java
false
false
737
java
package duke.commands; import duke.exceptions.InvalidTaskIdException; import duke.utils.TaskList; /** * Encapsulates a command to delete a task from the task list. */ public class Delete extends Command { private int index; /** * Creates a command that will delete a task, specified by the * task index. * * @param index Index of the task to be deleted. */ public Delete(int index) { this.index = index; } @Override public TaskList execute(TaskList taskList) throws InvalidTaskIdException { if (index <= 0 || index > taskList.getSize()) { throw new InvalidTaskIdException(); } taskList.delete(index - 1); return taskList; } }
60742c9308477ca6518201432f06ec3b86f78329
36d6d9e3b70acf5d310c6fd7e2a36ca6bfc0cd59
/app/src/main/java/com/zstok/itemcompra/dominio/ItemCompra.java
28ef1d26453d6f50c6205cc753627c0a09090d3a
[]
no_license
MatheusDemiro/Zstock
07a02ac1a3d90eb9436c52e19845591c861ccc27
2ad02d883e0aac14ca88ece0dfaabd41b78cfa01
refs/heads/master
2020-03-15T01:08:48.476443
2018-10-25T01:44:12
2018-10-25T01:44:12
131,886,566
0
0
null
null
null
null
UTF-8
Java
false
false
816
java
package com.zstok.itemcompra.dominio; public class ItemCompra { private String idItemCompra; private String idProduto; private double valor; private int quantidade; public String getIdItemCompra() { return idItemCompra; } public void setIdItemCompra(String idItemCompra) { this.idItemCompra = idItemCompra; } public double getValor() { return valor; } public void setValor(double valor) { this.valor = valor; } public Integer getQuantidade() { return quantidade; } public String getIdProduto() { return idProduto; } public void setIdProduto(String idProduto) { this.idProduto = idProduto; } public void setQuantidade(int quantidade) { this.quantidade = quantidade; } }
d09b0675cb7059d5d9cb202d683ab86fd8842773
9cdda29e1436724d4f17627b3e8c41e3af10dbd9
/app/src/main/java/info/androidhive/introslider/MovieActivity.java
38bbda6e69951cbbe6dc57dc4a21b45ee9b95622
[]
no_license
deeamtee/IntroSlider
bf91e2960a559271776eb2135a7ea71a86228892
f5193ceb17ba9eb6bf66f1b46db92db5ad65388b
refs/heads/master
2020-03-17T03:33:44.174129
2018-05-29T16:56:33
2018-05-29T16:56:33
133,240,633
0
0
null
null
null
null
UTF-8
Java
false
false
1,445
java
package info.androidhive.introslider; import android.support.v4.app.NavUtils; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import android.widget.ImageView; import android.widget.TextView; import com.bumptech.glide.Glide; public class MovieActivity extends AppCompatActivity { String title = "Movie"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_movie); Toolbar toolbar = (Toolbar) findViewById(R.id.image_toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); Bundle extras = getIntent().getExtras(); String movieDescription = extras.getString("movieDescription"); String movieTitle = extras.getString("movieTitle"); String urlImage = extras.getString("urlImage"); ImageView imageUrlPoster = (ImageView) findViewById(R.id.imageUrlPoster); Glide.with(this) .load(urlImage) .into(imageUrlPoster); TextView tvMovie = (TextView) findViewById(R.id.tvMovie); tvMovie.setText(movieDescription); getSupportActionBar().setTitle(movieTitle); } @Override public boolean onSupportNavigateUp() { onBackPressed(); return true; } }
a7e87a0139870cfe1c0361d360133d9bbd3be484
08647e59604a41480359dcd29c75aa6ab1bb7402
/Player.java
47ba3bb971f88d6336893a5efdb0d1fca9a59955
[]
no_license
adrianzhang2000/MinMax
9c26035506fb0f0438b3ef6c9955066f90db7525
342bde8800689c5d34f140124f1468a1e2d199d8
refs/heads/main
2023-01-04T05:46:08.861017
2020-10-25T21:48:02
2020-10-25T21:48:02
307,198,399
0
0
null
null
null
null
UTF-8
Java
false
false
2,467
java
import java.util.ArrayList; public class Player { private int maxDepth; int player_color; public Player(int maxDepth, int player_color) { this.maxDepth = maxDepth; this.player_color = player_color; } public Board MiniMax(Board board, boolean prune) { if (player_color == Color.Black) { return max(new Board(board), Integer.MIN_VALUE, Integer.MAX_VALUE, 0, prune); } else { return min(new Board(board), Integer.MIN_VALUE, Integer.MAX_VALUE, 0, prune); } } public Board max(Board board, int a, int b, int depth, boolean prune) { if((board.isFinal()) || (depth == maxDepth)) { return board; } ArrayList<Board> children = board.getChildren(Color.Black); if (children.isEmpty()) return board; Board maxBoard = children.get(0); for (Board child : children) { Board oppBoard = min(child, a, b, depth + 1, prune); if(oppBoard.value > maxBoard.value) { maxBoard = child; } else if(oppBoard.value == maxBoard.value) { maxBoard = child; } if(prune) { //AB Pruning a = Integer.max(a, oppBoard.value); if(b <= a) { break; } } } return maxBoard; } public Board min(Board board, int a, int b, int depth, boolean prune) { if((board.isFinal()) || (depth == maxDepth)) { return board; } ArrayList<Board> children = board.getChildren(Color.White); if (children.isEmpty()) return board; Board minBoard = children.get(0); for (Board child : children) { Board oppBoard = max(child, a, b, depth + 1, prune); if(oppBoard.value < minBoard.value) { minBoard = child; } else if(oppBoard.value == minBoard.value ) { minBoard = child; } if(prune) { //AB Pruning b = Integer.min(b, oppBoard.value); if(b <= a) { break; } } } return minBoard; } public boolean isMyTurn(int c) { return player_color==c; } }
b69070fde899f9f02649d5d2d5d81af7739928ab
e7da152cd44a9cb9bfc9d8b2ecf0fb4995d6f352
/src/main/java/io/memento/infra/security/oauth/OAuthWebFilterProxy.java
01c05008e92f4c2df6c9ad15a0a93f2942ca2f81
[]
no_license
AgileSpirit/memento-api
1fa7a411fb2c9257a3d4d643f8f10149b60bde6d
10b9eaf58da75d329276ab36164db16a455b60a7
refs/heads/master
2020-05-19T11:04:01.699676
2014-09-16T17:14:57
2014-09-16T17:14:57
null
0
0
null
null
null
null
UTF-8
Java
false
false
483
java
package io.memento.infra.security.oauth; import org.springframework.web.filter.DelegatingFilterProxy; import javax.inject.Named; import javax.servlet.annotation.WebFilter; /** * Project: Memento * User: Jérémy Buget * Email: [email protected] * Date: 25/08/2014 */ @Named @WebFilter(filterName = "OAuthWebFilter", urlPatterns = {"/api/*"}, description = "OAuth2 based authentication filter") public class OAuthWebFilterProxy extends DelegatingFilterProxy { }
bcfb7fb3663f1fad2f9f3e8248956ed0e88c6378
f9016f3b0465bb8dbcab2d9613111f286d6f36aa
/src/com/jason/usedcar/presenter/RegisterResellerFragmentPresenter.java
d08496ac02ad5850e0d60e6e909931cc062ddc30
[]
no_license
76260865/usedcar
aa49d2551e9a8324e1e7ba9ba7659d0770df3200
c3c6c949dde61d11a1c1c8208805784d98db9302
refs/heads/master
2021-01-25T05:28:04.259310
2015-01-11T14:08:52
2015-01-11T14:08:52
18,393,833
1
0
null
2015-01-11T14:08:52
2014-04-03T06:47:32
Java
UTF-8
Java
false
false
1,197
java
package com.jason.usedcar.presenter; import android.support.v4.app.Fragment; import com.jason.usedcar.RestClient; import com.jason.usedcar.fragment.LoadingFragment; import com.jason.usedcar.request.RegisterResellerRequest; import retrofit.Callback; import retrofit.RetrofitError; /** * Logic for call buttons. */ public class RegisterResellerFragmentPresenter extends RegisterFragmentPresenter { private static final String TAG = RegisterResellerFragmentPresenter.class.getSimpleName(); public void registerReseller(final Fragment fragment, final RegisterResellerRequest param) { final LoadingFragment loadingFragment = new LoadingFragment(); loadingFragment.show(fragment.getFragmentManager()); new RestClient().registerReseller(param, new Callback<com.jason.usedcar.response.Response>() { @Override public void success(final com.jason.usedcar.response.Response response, final retrofit.client.Response response2) { loadingFragment.dismiss(); } @Override public void failure(final RetrofitError error) { loadingFragment.dismiss(); } }); } }
ece75d6eec1bc1a9499cca563c01622cf7b58f8f
f91161a09b95690066e74c705132b82b6b1f0ecf
/test10/model/src/entity/general/EnumGrade.java
fca58d2364c832c5ad99d175a1e354207f79601f
[]
no_license
Julien-Basquin/test_organisation_projet_M1
553093efb38a3a71698fb6b34222fdc3c2ea4e85
5a226b59d092af329033c0d27ae80b9cbacc6557
refs/heads/master
2020-04-07T09:31:06.922365
2018-11-19T16:25:49
2018-11-19T16:25:49
158,255,216
0
0
null
null
null
null
UTF-8
Java
false
false
787
java
package entity.general; public enum EnumGrade { NOVIS(0,250,500), LIEUTENANT(1,500,1000), COMMANDANT(2,750,2000), AMIRAL(3,1000,4000); private int numero; private int maxPower; private int xpMax; private EnumGrade(int numero, int maxPower, int xpMax) { this.numero = numero; this.maxPower = maxPower; this.xpMax = xpMax; } public EnumGrade gradeSuiant(int num) { for(EnumGrade e : values()) { if((num+1)==e.getNumero()) { return e; } } return null; } public EnumGrade getGrade(int num) { for(EnumGrade e : values()) { if((num)==e.getNumero()) { return e; } } return null; } public int getXpMax() { return xpMax; } public int getNumero() { return numero; } public int getMaxPower() { return maxPower; } }
eeea1a486350a1e706994dfc7fb45837150a273b
edca542ea8bb5e4e598b51c936589ed47481ff61
/src/main/java/gui/EditFrame.java
b62d466ec7034d4e2c41403a408d0ebf794dc45d
[]
no_license
nawespb/HomeAccounting
702076bab4748744e54990a8b3652ad20dd48475
69e168b267a9e37d40d07abf74bb491feb93ad3c
refs/heads/master
2020-03-21T22:43:08.841289
2018-08-27T07:44:45
2018-08-27T07:44:45
139,142,974
0
0
null
null
null
null
UTF-8
Java
false
false
5,794
java
package gui; import app.DBConnector; import app.Filter; import app.MyTableModel; import app.Product; import java.awt.Container; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.util.Date; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTable; import javax.swing.JTextField; public class EditFrame extends JFrame { private final DBConnector db; private final MyTableModel tModel; private final JTable table; private final JTextField date1 = new JTextField(); private final JTextField date2 = new JTextField(); private final JTextField date3 = new JTextField(); private final JTextField group = new JTextField(); private final JTextField product_name = new JTextField(); private final JTextField amount = new JTextField(); private final JTextField price = new JTextField(); private final JTextField id = new JTextField(); private final JButton btn = new JButton("Применить"); private final JLabel date_label = new JLabel("Дата:"); private final JLabel group_label = new JLabel("Товарная группа:"); private final JLabel product_name_label = new JLabel("Наименование:"); private final JLabel amount_label = new JLabel("Кол-во:"); private final JLabel price_label = new JLabel("Цена:"); private final Filter filter = new Filter(); public EditFrame(DBConnector db, JTable table, MyTableModel tModel, int row){ super("Изменение данных"); this.db = db; this.table = table; this.tModel = tModel; setBounds(100, 25, 580, 150); Container container = this.getContentPane(); container.setLayout(null); setResizable(false); addWindowListener(new WindowListener() { @Override public void windowOpened(WindowEvent e) {} @Override public void windowClosing(WindowEvent e) { e.getWindow().setVisible(false); dispose();} @Override public void windowClosed(WindowEvent e) {} @Override public void windowIconified(WindowEvent e) {} @Override public void windowDeiconified(WindowEvent e) {} @Override public void windowActivated(WindowEvent e) {} @Override public void windowDeactivated(WindowEvent e) {} }); //TextFields date1.setSize(23, 25); date1.setLocation(10, 30); date1.setDocument(filter.numberFilter(2)); add(date1); date2.setSize(23, 25); date2.setLocation(35, 30); date2.setDocument(filter.numberFilter(2)); add(date2); date3.setSize(35, 25); date3.setLocation(60, 30); date3.setDocument(filter.numberFilter(4)); add(date3); group.setSize(150, 25); group.setLocation(105, 30); add(group); product_name.setSize(150, 25); product_name.setLocation(265, 30); add(product_name); amount.setSize(50, 25); amount.setLocation(425, 30); amount.setDocument(filter.numberFilter(3)); add(amount); price.setSize(75, 25); price.setLocation(485, 30); price.setDocument(filter.doubleNumberFilter(10)); add(price); date_label.setSize(85, 25); date_label.setLocation(10, 5); add(date_label); group_label.setSize(150, 25); group_label.setLocation(105, 5); add(group_label); product_name_label.setSize(150, 25); product_name_label.setLocation(265, 5); add(product_name_label); amount_label.setSize(50, 25); amount_label.setLocation(425, 5); add(amount_label); price_label.setSize(75, 25); price_label.setLocation(485, 5); add(price_label); btn.setSize(150, 25); btn.setLocation(215, 70); btn.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { edit(row); table.updateUI(); dispose(); } }); add(btn); } private void edit (int row) { Product pr = tModel.getProduct(row); Date date = filter.getDate(date1.getText(), date2.getText(), date3.getText()); String groupE; String nameE; int amountE; double priceE; if (date != null) { tModel.editRowDate(row, date); } else date = pr.getDate(); if (!group.getText().trim().isEmpty()) { tModel.editRowGroup(row, group.getText()); groupE = group.getText(); } else groupE = pr.getGroup(); if (!product_name.getText().trim().isEmpty()) { tModel.editRowProductName(row, product_name.getText()); nameE = product_name.getText(); } else nameE = pr.getName(); if (!amount.getText().trim().isEmpty()) { tModel.editRowAmount(row, Integer.parseInt(amount.getText().trim())); amountE = Integer.parseInt(amount.getText().trim()); } else amountE = pr.getAmount(); if (!price.getText().trim().isEmpty()) { tModel.editRowPrice(row, Double.parseDouble(price.getText().trim())); priceE = Double.parseDouble(price.getText().trim()); } else priceE = pr.getPrice(); db.update(pr.getId(), date, groupE, nameE, amountE, priceE); } }
14b6529e5e17e5e5cf15749a18e9b30ddb9db9b0
2aea3588fac2cf7f12949bbf454817cb4044cbbb
/TW/Main.java
ad9f93ef99dafc0af9fe6376250b2b0aff85def8
[]
no_license
Pysiokot/Studia
47274dce172bbfd948efefec303ce951014fd707
702af9237c42a6d5a1611be22b76aea6d853dc06
refs/heads/master
2021-01-19T04:13:01.273731
2017-12-06T15:08:19
2017-12-06T15:08:19
87,359,697
1
0
null
null
null
null
UTF-8
Java
false
false
405
java
public class Main { public static int Val; public final static int n = 2; public static Thread[] threads = new Thread[n]; public static void main(String[] args) throws InterruptedException { for(int i = 0; i < n; i++) { threads[i] = new MyThread(); threads[i].start(); } for(int i = 0; i < n; i ++) { threads[i].join(); } System.out.println(Val); } }
e09ec62006b30ff0cd1c18ade938605ada5e43f3
3b3b27f3df71359120a0b2bbca7ca56b03d09a1f
/app/src/main/java/com/inhand/milk/fragment/temperature_amount/details/PinnedHeaderListView.java
875814c2325378d7291e35c8dc2fda5f8e4b23bd
[]
no_license
waittrue/inhandAPP
2fc3aaf09e84928b15d5c066d63663399e2977d0
9a135207c9fc65d78b15b9f08b02a09dab540b28
refs/heads/master
2021-01-10T01:31:13.755544
2015-06-19T16:04:32
2015-06-19T16:04:32
36,590,779
0
2
null
2015-06-19T16:04:32
2015-05-31T06:20:42
Java
UTF-8
Java
false
false
3,261
java
package com.inhand.milk.fragment.temperature_amount.details; import android.content.Context; import android.graphics.Canvas; import android.util.AttributeSet; import android.util.Log; import android.view.View; import android.widget.ListAdapter; import android.widget.ListView; public class PinnedHeaderListView extends ListView{ private boolean drawHead = true; private View headView; private PinnedListViewAdapter myAdapter; private int mMeasureWidth; private int mMeasureHeight; public PinnedHeaderListView(Context context) { super(context); } public PinnedHeaderListView(Context context, AttributeSet attrs) { super(context, attrs); } public PinnedHeaderListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public void setAdapter(ListAdapter adapter) { // TODO Auto-generated method stub super.setAdapter(adapter); myAdapter = (PinnedListViewAdapter) adapter; } public void setHeadView(View v){ headView = v; Log.i("setHeadView", "1111111"); requestLayout(); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // TODO Auto-generated method stub super.onMeasure(widthMeasureSpec, heightMeasureSpec); Log.i("onmeasure", "1111111"); if ( headView != null){ measureChild(headView, widthMeasureSpec, heightMeasureSpec); mMeasureHeight = headView.getMeasuredHeight(); mMeasureWidth = headView.getMeasuredWidth(); } } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { // TODO Auto-generated method stub super.onLayout(changed, l, t, r, b); Log.i("onlayout", "1111111"); if (headView != null){ controlHeadView( getFirstVisiblePosition() ); } } @Override protected void dispatchDraw(Canvas canvas) { // TODO Auto-generated method stub super.dispatchDraw(canvas); Log.i("dispatchDraw", "1111111"); if (headView != null && drawHead){ drawChild(canvas, headView, getDrawingTime()); controlHeadView( getFirstVisiblePosition() ); } } private void controlHeadView(int position){ if (headView == null){ drawHead = false; return ; } int state = myAdapter.getHeadViewState(position); switch (state) { case HeadViewManager.HEAD_VIEW_GONE: drawHead = false; break; case HeadViewManager.HEAD_VIEW_VISIBLE: myAdapter.configureHeadView(headView, position); headView.layout(0, 0, mMeasureWidth, mMeasureHeight); drawHead = true; break; case HeadViewManager.HEAD_VIEW_MOVE: myAdapter.configureHeadView(headView, position); drawHead = true; View child = getChildAt(0); if (child != null){ int bottom = child.getBottom(); int height = headView.getHeight();//����Ҫ�� ���ⳤ�� С�� ���ݳ��� int y = bottom - height; if ( y > 0 ) y = 0; headView.layout(0, y, mMeasureWidth, mMeasureHeight + y); } break; } } public interface HeadViewManager{ public static final int HEAD_VIEW_GONE = 0; public static final int HEAD_VIEW_VISIBLE = 1; public static final int HEAD_VIEW_MOVE = 2; int getHeadViewState(int position); void configureHeadView(View view, int position); } }
f2c8053188698deab321f64c2ac1ca02d090908d
709bc2a2bc4b738aa3400278641256056dc057e4
/Usuario/src/main/java/resource/Main.java
f54dc2824a97b24daacc9c85f6981baeff137ea4
[]
no_license
viniroque/WebService
9f0b62f01f75650637ddfa56f882aef5c58fb76e
a917a3ccd198296a6663f2c81469ce5cacab6273
refs/heads/master
2021-08-28T16:41:54.393144
2017-12-12T20:02:36
2017-12-12T20:02:36
114,033,110
0
0
null
null
null
null
UTF-8
Java
false
false
282
java
package resource; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class Main { public static void main(String[]args){ SpringApplication.run(Main.class, args); } }
810d6eadea3a3e4006a454aff3f7a927e3e22e7c
552797c30cfc42a86b369e94ab7f828d50c7aa2c
/src/main/java/com/dev/springrestdemo/api/v1/model/CategoryDTO.java
f10d9365f242c165f68d6e6daf8be353a051cd55
[]
no_license
neagkv/Spring-RESTful-API
d639a5df2d64f89023321f95ca4e9c35b223b927
a0ee3601935cb7b1596b7fc7b8b91035c3f0aa03
refs/heads/master
2020-03-21T20:55:54.973721
2018-07-10T23:51:49
2018-07-10T23:51:49
139,037,240
0
0
null
null
null
null
UTF-8
Java
false
false
179
java
package com.dev.springrestdemo.api.v1.model; import lombok.Data; /** * @author Kevin Neag */ @Data public class CategoryDTO { private Long id; private String name; }
450723bfc90f35e35bf0512a778b45871d5335d4
3e0ec31b0f17008374d9d18637487046bda058f6
/src/main/java/com/fh/service/system/zan_comment_tiwen/Zan_Comment_TiwenService.java
c90efd0ae3527ca0f721d322b9cb3c4cc3724478
[]
no_license
guominzheng/NJK
d1077b61300836640ed23b42a03077a72e4ed404
8c2a7aaf3a47ebc456dd0a182211670d885561f0
refs/heads/master
2020-04-06T13:35:56.519873
2018-11-14T08:06:34
2018-11-14T08:06:34
128,651,806
0
0
null
null
null
null
UTF-8
Java
false
false
1,019
java
package com.fh.service.system.zan_comment_tiwen; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.fh.dao.DaoSupport; import com.fh.util.PageData; @Service @Resource(name="zan_Comment_TiwenService") public class Zan_Comment_TiwenService { @Resource(name="daoSupport") private DaoSupport dao; public void save(PageData pd) throws Exception{ dao.save("Zan_Comment_TiwenMapper.save", pd); } public PageData findById(PageData pd) throws Exception{ return (PageData) dao.findForObject("Zan_Comment_TiwenMapper.findById", pd); } public void delete(PageData pd) throws Exception{ dao.delete("Zan_Comment_TiwenMapper.delete", pd); } public PageData findById1(PageData pd) throws Exception{ return (PageData) dao.findForObject("Zan_Comment_TiwenMapper.findById1", pd); } public PageData findCount(PageData pd) throws Exception{ return (PageData) dao.findForObject("Zan_Comment_TiwenMapper.findCount", pd); } }
f62b6677af3e7b5f9b82a99c5d8afd27edc3da20
825bbf5d69a77f9cf324ca2d1e60cd1874479faf
/CCG/src/main/java/com/fw/ccg/core/IdentifiableBean.java
b4a276530991335e416c2ae39a3882cb112ab9c4
[]
no_license
akranthikiran/utils
61974998aad72cecb4904a0769c89a51fa0aff6a
b23b4270ef614c91ecc563b775987619d69bac42
refs/heads/master
2016-09-03T07:17:41.587686
2015-10-24T03:30:45
2015-10-24T03:30:45
34,916,760
0
0
null
null
null
null
UTF-8
Java
false
false
1,889
java
package com.fw.ccg.core; import java.io.Serializable; /** * <BR><BR> * A Simple implementation of the Identifiable and Validateable interfaces. * <BR> * @author A. Kranthi Kiran */ public class IdentifiableBean implements Identifiable,Validateable,Serializable { private static final long serialVersionUID=1L; private String id; public IdentifiableBean() {} public IdentifiableBean(IdentifiableBean other) { this.id=other.id; } /* (non-Javadoc) * @see com.ccg.core.Identifiable#setID(java.lang.String) */ public void setId(String id) { this.id=id; } /* (non-Javadoc) * @see com.ccg.core.Identifiable#getID() */ public String getId() { return id; } /** * Throws ValidateException if id is not specified. * @see com.fw.ccg.core.Validateable#validate() */ public void validate() throws ValidateException { if(id==null || id.length()==0) throw new ValidateException("Mandatory attribute \"ID\" is missing."); } /** * Specified bean "other" is considered equal if the "other" bean is also identifiable and id of this bean * is equal to the id of the bean. * @see java.lang.Object#equals(java.lang.Object) */ public boolean equals(Object other) { if(this==other) return true; if(!(other instanceof IdentifiableBean)) return false; if(id==null) return (((IdentifiableBean)other).id==null); return id.equals(((IdentifiableBean)other).id); } /** * If id is null, then zero (0) is returned, otherwise hashcode of id string is * returned as hascode of this bean. * @see java.lang.Object#hashCode() */ public int hashCode() { if(id==null) return 0; return id.hashCode(); } public String toString() { return id; } }
f003712368e509c233cb76b3acbb484dfe240ded
7715702429787daa5d64030d557b835592777a03
/6.- Methods/12.- Max of numbers using varags/src/com/company/Main.java
214fb703463a6a045795450cd9a8de85ced59089
[]
no_license
LuisSalas94/Learn-Core-JAVA-Programming
637f80e32b3bfb193ef9008d19e272cd506a6947
1151f9ce347417305fbd282b2a51463cd618fc09
refs/heads/master
2023-04-03T06:10:14.799972
2021-04-08T19:34:12
2021-04-08T19:34:12
344,973,673
0
0
null
null
null
null
UTF-8
Java
false
false
476
java
package com.company; public class Main { static int max (int ...A) { if(A.length == 0)return Integer.MIN_VALUE; int max = A[0]; for(int i = 0; i<A.length; i++) { if(A[i] > max) { max = A[i]; } } return max; } public static void main(String[] args) { System.out.println(max(10, 20 , 40)); System.out.println(max(45, 80, 65)); } }
e6a40b935e592a02e725f746cfe84cad369e5fad
cf1a738a8a36966f683be465ec9572d8e59f137b
/src/DSP/ButtonClass.java
15c4e667f1ac10c74dc3883432a08f5edff40c15
[]
no_license
aaronnahum/DNA
ecae3404a2e8d6d71207edc1ccfceefe1069fa24
b4ae98170c33a1ac9adaf66754fb1a3647a0ef0e
refs/heads/master
2020-03-16T10:02:21.917964
2018-07-23T20:14:22
2018-07-23T20:14:22
132,628,212
0
1
null
null
null
null
UTF-8
Java
false
false
13,703
java
package DSP; import com.itextpdf.text.BadElementException; import java.io.File; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; import javafx.event.ActionEvent; import javafx.geometry.Pos; import javafx.scene.control.Button; import javafx.scene.control.TextField; import javafx.scene.control.Tooltip; import javafx.scene.effect.DropShadow; import javafx.scene.image.Image; import javafx.scene.image.ImageView; import javafx.scene.input.MouseEvent; import javafx.stage.FileChooser; import javax.print.PrintException; public class ButtonClass { /** * * @return This returns an array list which contains all of the buttons that are a part of the revision log screen */ public static ArrayList<Button> revisionLogButtons(){ int screenWidth = ScreenResolutionClass.resolutionWidth(); int screenHeight = ScreenResolutionClass.resolutionHeight(); int fieldWidthAlignment = (int) ScreenResolutionClass.fieldWidthAlignment(screenWidth); int proportionalHeight = ScreenResolutionClass.proportionalHeight(screenHeight); double proportionalWidth = ScreenResolutionClass.proportionalWidth(screenWidth); double numberOfFields = 2.5; double scale = DSP.scale; ArrayList<Button> buttons = new ArrayList<>(); Button btnAddAField = button("Add A New Revision and Unlock the Dashboard", fieldWidthAlignment *4, (proportionalHeight * 1.75), "functionalButtonBiggerText", true, "Adds a New Revision Line"); // btnAddAField.setOnAction(e -> { // ArrayList<TextField> newField = TextfieldClass.revisionLogAddAField(0); // for(int i = 0; i < newField.size(); i++) // RevisionLog.canvas.getChildren().add(newField.get(i)); // }); buttons.add(btnAddAField); Button btnPrint = button("Print", 120, (screenHeight-75), "functionalButtonBiggerText" ,true, "Print the Current Page"); btnPrint.setOnAction((ActionEvent e) -> { try { PrintTest.printPDF(); } catch (IOException ex) { Logger.getLogger(ButtonClass.class.getName()).log(Level.SEVERE, null, ex); } catch (BadElementException ex) { Logger.getLogger(ButtonClass.class.getName()).log(Level.SEVERE, null, ex); } catch (PrintException ex) { Logger.getLogger(ButtonClass.class.getName()).log(Level.SEVERE, null, ex); } }); buttons.add(btnPrint); Button btnDashboard = button("Dashboard", 220, (screenHeight-75), "functionalButtonBiggerText", true, "Redirects to the Dashboard Page"); buttons.add(btnDashboard); Button btnProjectRegistration = button("New Project Registration", 350, (screenHeight-75), "functionalButtonBiggerText" ,true); buttons.add(btnProjectRegistration); // Button btnHelp = button("Help", screenWidth-180, (screenHeight -75), "functionalButtonBiggerText" ,true); // btnHelp.setOnAction(e -> Help.help()); // buttons.add(btnHelp); Button btnSaveDraft = button("Save as PDF", proportionalWidth*7.5, proportionalHeight*1.75, "functionalButtonBiggerText", true, "Save as PDF"); btnSaveDraft.setOnAction(e -> { try { PDFClass.generatePDF2(); } catch (IOException ex) { Logger.getLogger(ButtonClass.class.getName()).log(Level.SEVERE, null, ex); } catch (BadElementException ex) { Logger.getLogger(ButtonClass.class.getName()).log(Level.SEVERE, null, ex); } }); buttons.add(btnSaveDraft); Button btnRelease = button("Release", proportionalWidth*9.25, proportionalHeight*1.75, "functionalButtonBiggerText", true, "Releases the Revision"); btnRelease.setOnAction(e -> { try { ReleaseClass.release(); } catch (SQLException ex) { Logger.getLogger(ButtonClass.class.getName()).log(Level.SEVERE, null, ex); } catch (ClassNotFoundException ex) { Logger.getLogger(ButtonClass.class.getName()).log(Level.SEVERE, null, ex); } }); buttons.add(btnRelease); Button btnRequestToLead = button("Request Lead To Open New Revision", proportionalWidth*11.0, proportionalHeight*1.75, "functionalButtonBiggerText", true); btnRequestToLead.setOnAction(e -> EmailClass.Email("[email protected]", "Kepstrum2005", "Testing Subject", "Dear Lead, \n\nAssociate #1 would like you to open up a new revision\n\nAssociate #1.", "[email protected]")); buttons.add(btnRequestToLead); Button btnScope = button("Scope", fieldWidthAlignment*6, proportionalHeight*numberOfFields, "functionalButton", true, "Redirects to Scope Page"); buttons.add(btnScope); Button btnTermsNorms = button("Terms/Norms", fieldWidthAlignment*8, proportionalHeight*(numberOfFields)-15, "functionalButton", true, 55*scale, "Redirects to Terms/Norms Page"); buttons.add(btnTermsNorms); System.out.println("THE SCALE IS" + scale); Button btnControlVolume = button("Control Volume", fieldWidthAlignment*10, proportionalHeight*numberOfFields-15, "functionalButton", true, 60*scale, "Redirects to Control Volume Page"); buttons.add(btnControlVolume); Button btnSystemModels = button("System Models", fieldWidthAlignment*12, proportionalHeight*numberOfFields-15, "functionalButton", true, 60*scale, "Redirects to System Models Page"); buttons.add(btnSystemModels); Button btnInterface = button("Interface", fieldWidthAlignment*14, proportionalHeight*numberOfFields, "functionalButton", true, "Redirects to Interface Page"); buttons.add(btnInterface); Button btnDIP = button("DIP", fieldWidthAlignment*16, proportionalHeight*numberOfFields, "functionalButton", true, "Redirects to DIP Page"); buttons.add(btnDIP); Button btnDIF = button("DIF", fieldWidthAlignment*17, proportionalHeight*numberOfFields, "functionalButton", true, "Redirects to DIF Page"); buttons.add(btnDIF); Button btnDIL = button("DIL", fieldWidthAlignment*18, proportionalHeight*numberOfFields, "functionalButton", true, "Redirects to DIL Page"); buttons.add(btnDIL); Button btnKPFs = button("KPFs", fieldWidthAlignment*19, proportionalHeight*numberOfFields, "functionalButton", true, "Redirects to KPFs Page"); buttons.add(btnKPFs); Button btnDIPVerification = button("DIP Verification", fieldWidthAlignment*21, proportionalHeight*numberOfFields-15, "functionalButton", true, 80*scale, "Redirects to DIP Verification Page"); buttons.add(btnDIPVerification); Button btnDNAGenerator = button("DNA Generator", fieldWidthAlignment*24, proportionalHeight*numberOfFields-15, "functionalButton", true, 75*scale, "Redirects to DNA Generator Page"); buttons.add(btnDNAGenerator); Button btnDNALibrary = button("DNA Library", fieldWidthAlignment*27, proportionalHeight*numberOfFields, "functionalButton", true, 90*scale, "Redirects to DNA Library Page"); buttons.add(btnDNALibrary); Button btnImportImage = button("Import Image", fieldWidthAlignment*31, proportionalHeight*numberOfFields, "functionalButton", true, "Import an Image to the Program"); btnImportImage.setOnAction(e -> { final FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Import Image"); fileChooser.setInitialDirectory(new File(System.getProperty("user.home"))); fileChooser.getExtensionFilters().addAll( new FileChooser.ExtensionFilter("All Image Files (*.jpg; *.png)", "*.jpg", "*.png"), new FileChooser.ExtensionFilter("JPG", "*.jpg"), new FileChooser.ExtensionFilter("PNG", "*.png")); File file = fileChooser.showOpenDialog(DSP.window); if (file != null) { Image image = new Image(file.toURI().toString(), 100, 150, true, true); ImageView imageView = new ImageView(image); imageView.setFitWidth(100); imageView.setFitHeight(150); imageView.setPreserveRatio(true); RevisionLog.group.getChildren().add(imageView); } }); buttons.add(btnImportImage); return buttons; } /** * * @param text The text on the button * @param positionX The position of the button on the x-axis * @param positionY The position of the button on the y-axis * @param style The CSS style for the button * @param shadow Determines if there is a shadow when the mouse is over the button * @param wrap The max width of the button (used for wrapping the text) * @return This returns a button */ public static Button button(String text, double positionX, double positionY, String style, Boolean shadow, double wrap) { Button button1 = new Button(); button1.setText(text); button1.setLayoutX(positionX); button1.setLayoutY(positionY); button1.setId(style); button1.setAlignment(Pos.BOTTOM_CENTER); if(shadow == true) { DropShadow shadowDrop = new DropShadow(); // Adding the shadow when the mouse cursor is on button1.addEventHandler(MouseEvent.MOUSE_ENTERED, (MouseEvent e) -> { button1.setEffect(shadowDrop); }); //Removing the shadow when the mouse cursor is off button1.addEventHandler(MouseEvent.MOUSE_EXITED, (MouseEvent e) -> { button1.setEffect(null); }); } button1.setMaxWidth(wrap); button1.setWrapText(true); return button1; } public static Button button(String text, double positionX, double positionY, String style, Boolean shadow, double wrap, String tip) { Button button1 = new Button(); button1.setText(text); button1.setLayoutX(positionX); button1.setLayoutY(positionY); button1.setId(style); button1.setAlignment(Pos.BOTTOM_CENTER); if(shadow == true) { DropShadow shadowDrop = new DropShadow(); // Adding the shadow when the mouse cursor is on button1.addEventHandler(MouseEvent.MOUSE_ENTERED, (MouseEvent e) -> { button1.setEffect(shadowDrop); }); //Removing the shadow when the mouse cursor is off button1.addEventHandler(MouseEvent.MOUSE_EXITED, (MouseEvent e) -> { button1.setEffect(null); }); } button1.setMaxWidth(wrap); button1.setWrapText(true); button1.setTooltip(new Tooltip(tip)); return button1; } /** * * @param text The text on the button * @param positionX The position of the button on the x-axis * @param positionY The position of the button on the y-axis * @param style The CSS style for the button * @param shadow Determines if there is a shadow when the mouse is over the button * @return This returns a button */ public static Button button(String text, double positionX, double positionY, String style, Boolean shadow) { Button button1 = new Button(); button1.setText(text); button1.setLayoutX(positionX); button1.setLayoutY(positionY); button1.setId(style); button1.setAlignment(Pos.CENTER); if(shadow == true) { DropShadow shadowDrop = new DropShadow(); // Adding the shadow when the mouse cursor is on button1.addEventHandler(MouseEvent.MOUSE_ENTERED, (MouseEvent e) -> { button1.setEffect(shadowDrop); }); //Removing the shadow when the mouse cursor is off button1.addEventHandler(MouseEvent.MOUSE_EXITED, (MouseEvent e) -> { button1.setEffect(null); }); } return button1; } public static Button button(String text, double positionX, double positionY, String style, Boolean shadow, String tipText ){ Button button1 = new Button(); button1.setText(text); button1.setLayoutX(positionX); button1.setLayoutY(positionY); button1.setId(style); button1.setAlignment(Pos.CENTER); Tooltip tip = new Tooltip(); tip.setText(tipText); tip.setId("tooltip"); button1.setTooltip(tip); if(shadow == true) { DropShadow shadowDrop = new DropShadow(); // Adding the shadow when the mouse cursor is on button1.addEventHandler(MouseEvent.MOUSE_ENTERED, (MouseEvent e) -> { button1.setEffect(shadowDrop); }); //Removing the shadow when the mouse cursor is off button1.addEventHandler(MouseEvent.MOUSE_EXITED, (MouseEvent e) -> { button1.setEffect(null); }); } return button1; } }
b083f5ec70beb8008d7400b615c23c69867c9955
77623d6dd90f2d1a401ee720adb41c3c0c264715
/DiffTGen-result/output/Closure_93_5_sequencer/target/0/15/evosuite-tests/com/google/javascript/jscomp/ProcessClosurePrimitives_ESTest.java
c2d183c9775dab8aff6d7599eec6ecf180ed4595
[]
no_license
wuhongjun15/overfitting-study
40be0f062bbd6716d8de6b06454b8c73bae3438d
5093979e861cda6575242d92ca12355a26ca55e0
refs/heads/master
2021-04-17T05:37:48.393527
2020-04-11T01:53:53
2020-04-11T01:53:53
249,413,962
0
0
null
null
null
null
UTF-8
Java
false
false
682
java
/* * This file was automatically generated by EvoSuite * Fri Mar 27 05:42:33 GMT 2020 */ package com.google.javascript.jscomp; import org.junit.Test; import static org.junit.Assert.*; import org.evosuite.runtime.EvoRunner; import org.evosuite.runtime.EvoRunnerParameters; import org.junit.runner.RunWith; @RunWith(EvoRunner.class) @EvoRunnerParameters(mockJVMNonDeterminism = true, useVFS = true, useVNET = true, resetStaticState = true, separateClassLoader = true, useJEE = true) public class ProcessClosurePrimitives_ESTest extends ProcessClosurePrimitives_ESTest_scaffolding { @Test public void notGeneratedAnyTest() { // EvoSuite did not generate any tests } }
213bd6fb8c1b2e5b2dde4fb6552329a73d634704
18c62892ebc5a7643e195f2cadfbbef6aee5d306
/src/main/java/com/traulko/project/controller/command/impl/LoginCommand.java
3744c37c052ff166efaf8a6e40605af5d3a0a93e
[]
no_license
traulko/EpamFinalProject
63a2c29c04b43dec6b3ee70ed9b031f7cad21fe5
9d26f0bbbe34614f7f5bc7e0ceb800dfb7aa3e72
refs/heads/master
2023-01-13T10:43:27.052294
2020-11-19T00:29:25
2020-11-19T00:29:25
296,344,045
0
1
null
null
null
null
UTF-8
Java
false
false
2,724
java
package com.traulko.project.controller.command.impl; import com.traulko.project.controller.PagePath; import com.traulko.project.controller.RequestParameter; import com.traulko.project.controller.command.CustomCommand; import com.traulko.project.entity.User; import com.traulko.project.exception.ServiceException; import com.traulko.project.service.UserService; import com.traulko.project.service.impl.UserServiceImpl; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import javax.servlet.http.HttpServletRequest; import java.util.Optional; /** * The {@code LoginCommand} class represents login command. * * @author Yan Traulko * @version 1.0 */ public class LoginCommand implements CustomCommand { private static final UserService userService = new UserServiceImpl(); private static final Logger LOGGER = LogManager.getLogger(LoginCommand.class); public String execute(HttpServletRequest request) { String page; String email = request.getParameter(RequestParameter.EMAIL); String password = request.getParameter(RequestParameter.PASSWORD); try { if (userService.isUserExists(email, password)) { Optional<User> optionalUser = userService.findUserByEmail(email); User user = optionalUser.get(); switch (user.getStatus()) { case ENABLE -> { request.getSession().setAttribute(RequestParameter.USER, user); request.getSession().setAttribute(RequestParameter.USER_ID, user.getUserId().toString()); request.getSession().setAttribute(RequestParameter.ROLE, user.getRole().toString()); page = PagePath.MAIN; } case BLOCKED -> { request.setAttribute(RequestParameter.USER_LOGIN_BLOCKED, true); page = PagePath.MESSAGE; } case NOT_CONFIRMED -> { request.setAttribute(RequestParameter.USER_CONFIRM_REGISTRATION_LETTER, true); page = PagePath.MESSAGE; } default -> page = PagePath.MAIN; } } else { request.setAttribute(RequestParameter.REGISTRATION_PARAMETERS, true); page = PagePath.LOGIN; } } catch (ServiceException e) { LOGGER.log(Level.ERROR, "Error while login user", e); request.setAttribute(RequestParameter.ERROR_MESSAGE, e); page = PagePath.ERROR_500; } return page; } }
892b81a178c376bb59f7e9d6df18ecae2706a37a
e75be673baeeddee986ece49ef6e1c718a8e7a5d
/submissions/blizzard/Corpus/tomcat70/1338.java
244ca9bc0fe4fab6a1141cfa3b6675d383955e18
[ "MIT" ]
permissive
zhendong2050/fse18
edbea132be9122b57e272a20c20fae2bb949e63e
f0f016140489961c9e3c2e837577f698c2d4cf44
refs/heads/master
2020-12-21T11:31:53.800358
2018-07-23T10:10:57
2018-07-23T10:10:57
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,580
java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jasper.runtime; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; import java.util.List; import javax.el.CompositeELResolver; import javax.el.ELContextEvent; import javax.el.ELContextListener; import javax.el.ELResolver; import javax.el.ExpressionFactory; import javax.servlet.ServletContext; import javax.servlet.jsp.JspApplicationContext; import javax.servlet.jsp.JspContext; import org.apache.jasper.Constants; import org.apache.jasper.el.ELContextImpl; import org.apache.jasper.el.JasperELResolver; /** * Implementation of JspApplicationContext * * @author Jacob Hookom */ public class JspApplicationContextImpl implements JspApplicationContext { private static final String KEY = JspApplicationContextImpl.class.getName(); private final ExpressionFactory expressionFactory = ExpressionFactory.newInstance(); private final List<ELContextListener> contextListeners = new ArrayList<ELContextListener>(); private final List<ELResolver> resolvers = new ArrayList<ELResolver>(); private boolean instantiated = false; private ELResolver resolver; public JspApplicationContextImpl() { } @Override public void addELContextListener(ELContextListener listener) { if (listener == null) { throw new IllegalArgumentException("ELConextListener was null"); } this.contextListeners.add(listener); } public static JspApplicationContextImpl getInstance(ServletContext context) { if (context == null) { throw new IllegalArgumentException("ServletContext was null"); } JspApplicationContextImpl impl = (JspApplicationContextImpl) context.getAttribute(KEY); if (impl == null) { impl = new JspApplicationContextImpl(); context.setAttribute(KEY, impl); } return impl; } public ELContextImpl createELContext(JspContext context) { if (context == null) { throw new IllegalArgumentException("JspContext was null"); } // create ELContext for JspContext final ELResolver r = this.createELResolver(); ELContextImpl ctx; if (Constants.IS_SECURITY_ENABLED) { ctx = AccessController.doPrivileged(new PrivilegedAction<ELContextImpl>() { @Override public ELContextImpl run() { return new ELContextImpl(r); } }); } else { ctx = new ELContextImpl(r); } ctx.putContext(JspContext.class, context); // alert all ELContextListeners ELContextEvent event = new ELContextEvent(ctx); for (int i = 0; i < this.contextListeners.size(); i++) { this.contextListeners.get(i).contextCreated(event); } return ctx; } private ELResolver createELResolver() { this.instantiated = true; if (this.resolver == null) { CompositeELResolver r = new JasperELResolver(this.resolvers); this.resolver = r; } return this.resolver; } @Override public void addELResolver(ELResolver resolver) throws IllegalStateException { if (resolver == null) { throw new IllegalArgumentException("ELResolver was null"); } if (this.instantiated) { throw new IllegalStateException("cannot call addELResolver after the first request has been made"); } this.resolvers.add(resolver); } @Override public ExpressionFactory getExpressionFactory() { return expressionFactory; } }
53df440140ad4af3b26456cc10a934a7d610e603
f87956520dbb112943449443b9299c9609b9e9b7
/src/Test_TYSS.java
56e4a826a656c9954659fe414a0cfbcd8cc060cc
[]
no_license
Soundarya9871/eletter
5d7ffd3468653f4c65a0a7aeac1b821d92023994
2f4a0c363d5d103d9f926f61c746e965278d655c
refs/heads/master
2021-02-14T21:10:42.725803
2020-03-04T07:41:47
2020-03-04T07:41:47
244,835,245
0
0
null
2020-03-04T07:41:48
2020-03-04T07:28:34
Java
UTF-8
Java
false
false
111
java
public class Test_TYSS { public static void main(String[] args) { System.out.println("sdjgfvicfhb"); } }
[ "Soundarya VijayKumar@LAPTOP-UORTPMG3" ]
Soundarya VijayKumar@LAPTOP-UORTPMG3
376ff6d25c7c6c7af5e50df5889d55740bf37958
5d7c8d78e72ae3ea6e61154711fdd23248c19614
/sources/com/taobao/atlas/dexmerge/dx/util/MutabilityControl.java
555fa93ca5af838f6076fcf4e55da9304fbeebbc
[]
no_license
activeliang/tv.taobao.android
8058497bbb45a6090313e8445107d987d676aff6
bb741de1cca9a6281f4c84a6d384333b6630113c
refs/heads/master
2022-11-28T10:12:53.137874
2020-08-06T05:43:15
2020-08-06T05:43:15
285,483,760
7
6
null
null
null
null
UTF-8
Java
false
false
792
java
package com.taobao.atlas.dexmerge.dx.util; public class MutabilityControl { private boolean mutable; public MutabilityControl() { this.mutable = true; } public MutabilityControl(boolean mutable2) { this.mutable = mutable2; } public void setImmutable() { this.mutable = false; } public final boolean isImmutable() { return !this.mutable; } public final boolean isMutable() { return this.mutable; } public final void throwIfImmutable() { if (!this.mutable) { throw new MutabilityException("immutable instance"); } } public final void throwIfMutable() { if (this.mutable) { throw new MutabilityException("mutable instance"); } } }
45cc67ca05883f52a41be63a6b574405e860e75a
504293c8c94c1874b9b67265a114fc39d9fbad57
/springboot-demo/springboot-demo/src/main/java/cn/lwb/加签/Test1.java
a52ad3548d3ce88389ebf5b19093cb7772f1ba5b
[]
no_license
mrh167/Springboot
b57a3f28019776a272c09bed6919838c185600bc
b64e9453699cdbb595831b23085b7fef7deeaf04
refs/heads/master
2023-04-14T03:35:00.176499
2020-12-19T07:15:59
2020-12-19T07:15:59
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,160
java
package cn.lwb.加签; import java.security.InvalidKeyException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.util.Base64; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; /** * RSA加密解密操作步骤 */ public class Test1 { public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException { //先给出一个待加密的字符串 String data = "青青子衿,悠悠我心。但为君故,沉吟至今。"; //1.构建公私钥匙对 KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); KeyPair keyPair = keyPairGenerator.generateKeyPair(); //2.获取钥匙对中的公钥 PublicKey publicKey = keyPair.getPublic(); System.out.println("公钥数据:"); //3.获取钥匙对中的私钥 PrivateKey privateKey = keyPair.getPrivate(); System.out.println("公钥数据:" + privateKey.toString()); //4.对待加密的数据进行加密 Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] bytesEncrypt = cipher.doFinal(data.getBytes());//产生的是乱码,需要用Base64进行转码 //5.Base64编码 byte[] encodeBase64 = Base64.getEncoder().encode(bytesEncrypt); System.out.println("加密后的数据:" + new String(encodeBase64)); //6.在解密时,先对用Base64编码的信息进行解码 byte[] bytesDecode = Base64.getDecoder().decode(encodeBase64); //7.解密 Cipher cipher2 = Cipher.getInstance("RSA"); cipher2.init(Cipher.DECRYPT_MODE, privateKey); byte[] bytesDecrypt = cipher2.doFinal(bytesDecode); System.out.println("解密后的数据:" + new String(bytesDecrypt)); } }
11aca4d84829407af0627b8ae678f27688f86742
a451242c8f04d27f75722c748484de2754e90e72
/Java final edition/MyDBWithNativeDriver.java
dc0a30b70cc7f7c3cfa0abe91d6a0ea6c111583d
[]
no_license
sunil-lulla/JAVA
f64495d663f1c149986d5178e563e5d18600ff28
a7375692a10cf62b78c5bcd0dcfc83077fd79d93
refs/heads/master
2021-05-04T06:47:57.850851
2016-10-10T18:00:52
2016-10-10T18:00:52
70,514,478
0
0
null
null
null
null
UTF-8
Java
false
false
163
java
import oracle.jdbc.driver.*; class MyDBWithNativeDriver { public static void main(String[] args) { OracleDriver a= new OracleDriver(); System.out.print("sam"); } }
5dcbd1a226018475ec95754e2576bb6166d298c6
7fbc568f5f502eb0ae405022f7f34c79e0c49234
/baifei-logistics/src/main/java/org/baifei/modules/entity/request/vova/VovaSender.java
b89ccffe7a45b286e3bba84fbe8d07c51c14645d
[ "MIT" ]
permissive
yourant/logistics
c6271bae3e2d6add20df0ee7c815652f423e50de
3989d2f7b3213c6973bc76e7031248b8643ab5b1
refs/heads/master
2023-03-23T16:44:34.938698
2020-07-03T04:42:31
2020-07-03T04:42:31
null
0
0
null
null
null
null
UTF-8
Java
false
false
623
java
/** * Copyright 2020 bejson.com */ package org.baifei.modules.entity.request.vova; import lombok.Data; /** * Auto-generated: 2020-06-22 17:20:39 * * @author bejson.com ([email protected]) * @website http://www.bejson.com/java2pojo/ */ @Data public class VovaSender { private String company; private String phone; private String email; private String country_code; private String chinapost_province_code; private String chinapost_city_code; private String chinapost_county_code; private String zipcode; private VovaAddressLocal address_local; private VovaAddressEn address_en; }
e7d1195f6f82daabe7817661178877fdab17bdf9
8191bea395f0e97835735d1ab6e859db3a7f8a99
/f737922a0ddc9335bb0fc2f3ae5ffe93_source_from_JADX/com/google/android/gms/analytics/o.java
0912939070f8e9621857492ea2f742d9bcea2fbc
[]
no_license
msmtmsmt123/jadx-1
5e5aea319e094b5d09c66e0fdb31f10a3238346c
b9458bb1a49a8a7fba8b9f9a6fb6f54438ce03a2
refs/heads/master
2021-05-08T19:21:27.870459
2017-01-28T04:19:54
2017-01-28T04:19:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
893
java
package com.google.android.gms.analytics; import afq; import com.google.android.gms.common.internal.b; import java.util.ArrayList; import java.util.List; public abstract class o<T extends o> { private final p DW; private final List<m> FH; protected final l j6; protected o(p pVar, afq afq) { b.j6((Object) pVar); this.DW = pVar; this.FH = new ArrayList(); l lVar = new l(this, afq); lVar.EQ(); this.j6 = lVar; } protected void DW(l lVar) { for (m j6 : this.FH) { j6.j6(this, lVar); } } public l J0() { return this.j6; } public List<r> J8() { return this.j6.FH(); } protected p Ws() { return this.DW; } protected void j6(l lVar) { } public l we() { l j6 = this.j6.j6(); DW(j6); return j6; } }
63119309f21e73f9ee4fef4bc61d68a70725b45c
107a73cd7557b3cbc7839058e58c362164d4c5d1
/src/main/java/xander479/events/TweetEvent.java
21cdc78c51cbdc52f10cd04c4e3612e6dfb1a28d
[]
no_license
Xander479/XanderBot479
5aee1eb10390a8d3ce5b19b9646c47fcd46c10a4
1b94819aeff67232cac9877ada63d5939f1c8fee
refs/heads/master
2021-04-22T14:59:35.639764
2021-03-29T01:14:23
2021-03-29T01:14:23
249,855,245
0
0
null
null
null
null
UTF-8
Java
false
false
2,366
java
package xander479.events; import static xander479.TwitterBot.TWITTER_CHAR_LIMIT; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.text.JTextComponent; import org.w3c.dom.Document; import twitter4j.Twitter; import twitter4j.TwitterFactory; import twitter4j.auth.AccessToken; import xander479.Launcher; import xander479.TwitterBot; public class TweetEvent implements ActionListener { final static String CONFIG_FILE = "src/main/resources/twitter.xml"; private static Document config; private final static String CONSUMER_KEY; private final static String CONSUMER_KEY_SECRET; private final static String ACCESS_TOKEN; private final static String ACCESS_TOKEN_SECRET; static { try { config = Launcher.getConfig(CONFIG_FILE); } catch(Exception e) { e.printStackTrace(); System.err.println("Check that there are valid tokens in the " + CONFIG_FILE + " file."); } CONSUMER_KEY = config.getElementsByTagName("consumerKey").item(0).getTextContent(); CONSUMER_KEY_SECRET = config.getElementsByTagName("consumerKeySecret").item(0).getTextContent(); ACCESS_TOKEN = config.getElementsByTagName("accessToken").item(0).getTextContent(); ACCESS_TOKEN_SECRET = config.getElementsByTagName("accessTokenSecret").item(0).getTextContent(); } private JTextComponent tweetInput; private javax.swing.text.Document tweetDocument; public TweetEvent(JTextComponent tweetInput) { this.tweetInput = tweetInput; tweetDocument = tweetInput.getDocument(); } public void actionPerformed(ActionEvent e) { int chars = tweetDocument.getLength(); // Won't allow you to send a tweet over the character limit if(chars > TWITTER_CHAR_LIMIT) { TwitterBot.charsLeft.setText("You can only have " + TWITTER_CHAR_LIMIT + " characters in a tweet."); } else { try { Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_KEY_SECRET); twitter.setOAuthAccessToken(new AccessToken(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)); // THIS IS THE LINE WHICH SENDS THE TWEET twitter.updateStatus(tweetDocument.getText(0, tweetDocument.getLength())); // THIS IS THE LINE WHICH SENDS THE TWEET tweetInput.setText(""); TwitterBot.charsLeft.setText("Tweet sent!"); } catch(Exception ex) { ex.printStackTrace(); } } } }
8ab8d3391f904dc0fc23f8ee6ddbc76f483fc819
b3a6c37d1e039439a8abbd4739426c44f1cfa660
/src/main/java/com/example/demo/repository/UserReository.java
a0dec39a23c171dfefac29444fdc419af16d1a98
[]
no_license
rajveer-singh-nathawat/security_with_jwt_demo
b5cae40d822d49a5c87e4d196556580e962c02a5
ce21aad0d6fcfcd5872dc0d55c78e9e5f53c0ca9
refs/heads/master
2020-12-22T21:35:37.312500
2020-01-29T12:33:13
2020-01-29T12:33:13
236,938,378
0
0
null
null
null
null
UTF-8
Java
false
false
1,464
java
package com.example.demo.repository; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import com.example.demo.dto.SignupInfo; import com.example.demo.dto.TokenInfo; import com.example.demo.model.UserEntity; @Repository public interface UserReository extends JpaRepository<UserEntity, Long>{ @Query(value = "SELECT new com.example.demo.dto.SignupInfo" + "(u.userName,u.password,u.active,ure.roles)" + " FROM UserEntity u " + " JOIN UserRolesUserMappingEntity urm on urm.userEntity.userId=u.userId" + " JOIN UserRolesEntity ure on ure.userRolesId = urm.userRolesEntity.userRolesId " + " WHERE u.userName =:userName") public Optional<SignupInfo> findUserSignupInfo(@Param("userName") String userName); @Query(value = "SELECT new com.example.demo.dto.TokenInfo" + "(u.userId,u.userName,upe.fullName,ure.roles)" + " FROM UserEntity u " + " JOIN UserRolesUserMappingEntity urm on urm.userEntity.userId=u.userId" + " JOIN UserRolesEntity ure on ure.userRolesId = urm.userRolesEntity.userRolesId " + " JOIN UserProfileEntity upe on upe.userEntity.userId = u.userId" + " WHERE u.userName =:userName") public TokenInfo findTokenInfo(@Param("userName") String userName); Optional<UserEntity> findByUserName(String userName); }
98adcabc56dae69890b67b8811bc389f890389e4
77aaa0f888710410f34dfc4efbf463af6a3d59e2
/aaa/src/main/java/net/mindview/util/Print.java
b82bf5938581e746c57afd8803863bbeb215286f
[]
no_license
McLoy/Thinking-In-Java
2fe342aa40c52fb955a33b918a6e3f32786a0427
9a2bae43b8698e4c68ac652886c7de4344c47043
refs/heads/master
2021-01-10T16:16:41.382800
2016-03-11T13:46:26
2016-03-11T13:46:26
53,670,038
0
0
null
null
null
null
UTF-8
Java
false
false
496
java
package net.mindview.util; import java.io.*; /** * Created by Ostin on 25.06.2015. */ public class Print { public static void print(Object obj){ System.out.println(obj); } public static void print(){ System.out.println(); } public static void printnb(Object obj){ System.out.print(obj); } //public static PrintStream; // public static void printf(String format, Object... args){ // return System.out.printf(format, args); // } }
20061f65d8530a8dba560b455b9f7130bafd2260
065c1f648e8dd061a20147ff9c0dbb6b5bc8b9be
/checkstyle_cluster/4748/src_0.java
8f5e47e538c062e6b13f7d36ecd35d2abbb31e35
[]
no_license
martinezmatias/GenPat-data-C3
63cfe27efee2946831139747e6c20cf952f1d6f6
b360265a6aa3bb21bd1d64f1fc43c3b37d0da2a4
refs/heads/master
2022-04-25T17:59:03.905613
2020-04-15T14:41:34
2020-04-15T14:41:34
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,776
java
//////////////////////////////////////////////////////////////////////////////// // checkstyle: Checks Java source code for adherence to a set of rules. // Copyright (C) 2001-2005 Oliver Burn // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library 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 // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA //////////////////////////////////////////////////////////////////////////////// package com.puppycrawl.tools.checkstyle.checks.design; import com.puppycrawl.tools.checkstyle.api.DetailAST; import com.puppycrawl.tools.checkstyle.api.TokenTypes; import com.puppycrawl.tools.checkstyle.checks.AbstractFormatCheck; import java.util.Stack; /** * <p> Ensures that exceptions (defined as any class name conforming * to some regular expression) are immutable. That is, have only final * fields.</p> * <p> Rationale: Exception instances should represent an error * condition. Having non final fields not only allows the state to be * modified by accident and therefore mask the original condition but * also allows developers to accidentally forget to initialise state * thereby leading to code catching the exception to draw incorrect * conclusions based on the state.</p> * * @author <a href="mailto:[email protected]">Simon Harris</a> */ public final class MutableExceptionCheck extends AbstractFormatCheck { /** Default value for format property. */ private static final String DEFAULT_FORMAT = "^.*Exception$|^.*Error$"; /** Stack of checking information for classes. */ private final Stack mCheckingStack = new Stack(); /** Should we check current class or not. */ private boolean mChecking; /** Creates new instance of the check. */ public MutableExceptionCheck() { super(DEFAULT_FORMAT); } /** @see com.puppycrawl.tools.checkstyle.api.Check */ public int[] getDefaultTokens() { return new int[] {TokenTypes.CLASS_DEF, TokenTypes.VARIABLE_DEF}; } /** @see com.puppycrawl.tools.checkstyle.api.Check */ public int[] getRequiredTokens() { return getDefaultTokens(); } /** @see com.puppycrawl.tools.checkstyle.api.Check */ public void visitToken(DetailAST aAST) { switch (aAST.getType()) { case TokenTypes.CLASS_DEF: visitClassDef(aAST); break; case TokenTypes.VARIABLE_DEF: visitVariableDef(aAST); break; default: throw new IllegalStateException(aAST.toString()); } } /** @see com.puppycrawl.tools.checkstyle.api.Check */ public void leaveToken(DetailAST aAST) { switch (aAST.getType()) { case TokenTypes.CLASS_DEF: leaveClassDef(); break; default: // Do nothing } } /** * Called when we start processing class definition. * @param aAST class definition node */ private void visitClassDef(DetailAST aAST) { mCheckingStack.push(mChecking ? Boolean.TRUE : Boolean.FALSE); mChecking = isExceptionClass(aAST.findFirstToken(TokenTypes.IDENT).getText()); } /** Called when we leave class definition. */ private void leaveClassDef() { mChecking = ((Boolean) mCheckingStack.pop()).booleanValue(); } /** * Checks variable definition. * @param aAST variable def node for check. */ private void visitVariableDef(DetailAST aAST) { if (mChecking && aAST.getParent().getType() == TokenTypes.OBJBLOCK) { final DetailAST modifiersAST = aAST.findFirstToken(TokenTypes.MODIFIERS); if (!(modifiersAST.findFirstToken(TokenTypes.FINAL) != null)) { log(aAST.getLineNo(), aAST.getColumnNo(), "mutable.exception", aAST.findFirstToken(TokenTypes.IDENT).getText()); } } } /** * @param aClassName class name to check * @return true if a given class name confirms specified format */ private boolean isExceptionClass(String aClassName) { return getRegexp().match(aClassName); } }
19d939a67a275931bc4b03eb4b3c02d0291a7f64
d5a9ceeb7cc37e8d50a75bc939cbe5e7d753b2dd
/src/test/java/es/garocaru/web/rest/UserJWTControllerIntTest.java
e5661a2d3f570f2a0d51b9c4005952dfb7af1ffa
[]
no_license
Ginzox/jhipsterSampleApplication
10270f0436ef524b04bf1e236bac8a704b4be60a
96389f5c5e3eda68aea1b804b147c9f02a6f2181
refs/heads/master
2021-04-03T07:43:16.818026
2018-03-08T21:45:46
2018-03-08T21:45:46
124,444,987
0
0
null
2018-03-08T21:45:47
2018-03-08T20:33:59
Java
UTF-8
Java
false
false
4,851
java
package es.garocaru.web.rest; import es.garocaru.JhipsterSampleApplicationApp; import es.garocaru.domain.User; import es.garocaru.repository.UserRepository; import es.garocaru.security.jwt.TokenProvider; import es.garocaru.web.rest.vm.LoginVM; import es.garocaru.web.rest.errors.ExceptionTranslator; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.transaction.annotation.Transactional; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.header; import static org.hamcrest.Matchers.nullValue; import static org.hamcrest.Matchers.isEmptyString; import static org.hamcrest.Matchers.not; /** * Test class for the UserJWTController REST controller. * * @see UserJWTController */ @RunWith(SpringRunner.class) @SpringBootTest(classes = JhipsterSampleApplicationApp.class) public class UserJWTControllerIntTest { @Autowired private TokenProvider tokenProvider; @Autowired private AuthenticationManager authenticationManager; @Autowired private UserRepository userRepository; @Autowired private PasswordEncoder passwordEncoder; @Autowired private ExceptionTranslator exceptionTranslator; private MockMvc mockMvc; @Before public void setup() { UserJWTController userJWTController = new UserJWTController(tokenProvider, authenticationManager); this.mockMvc = MockMvcBuilders.standaloneSetup(userJWTController) .setControllerAdvice(exceptionTranslator) .build(); } @Test @Transactional public void testAuthorize() throws Exception { User user = new User(); user.setLogin("user-jwt-controller"); user.setEmail("[email protected]"); user.setActivated(true); user.setPassword(passwordEncoder.encode("test")); userRepository.saveAndFlush(user); LoginVM login = new LoginVM(); login.setUsername("user-jwt-controller"); login.setPassword("test"); mockMvc.perform(post("/api/authenticate") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(login))) .andExpect(status().isOk()) .andExpect(jsonPath("$.id_token").isString()) .andExpect(jsonPath("$.id_token").isNotEmpty()) .andExpect(header().string("Authorization", not(nullValue()))) .andExpect(header().string("Authorization", not(isEmptyString()))); } @Test @Transactional public void testAuthorizeWithRememberMe() throws Exception { User user = new User(); user.setLogin("user-jwt-controller-remember-me"); user.setEmail("[email protected]"); user.setActivated(true); user.setPassword(passwordEncoder.encode("test")); userRepository.saveAndFlush(user); LoginVM login = new LoginVM(); login.setUsername("user-jwt-controller-remember-me"); login.setPassword("test"); login.setRememberMe(true); mockMvc.perform(post("/api/authenticate") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(login))) .andExpect(status().isOk()) .andExpect(jsonPath("$.id_token").isString()) .andExpect(jsonPath("$.id_token").isNotEmpty()) .andExpect(header().string("Authorization", not(nullValue()))) .andExpect(header().string("Authorization", not(isEmptyString()))); } @Test @Transactional public void testAuthorizeFails() throws Exception { LoginVM login = new LoginVM(); login.setUsername("wrong-user"); login.setPassword("wrong password"); mockMvc.perform(post("/api/authenticate") .contentType(TestUtil.APPLICATION_JSON_UTF8) .content(TestUtil.convertObjectToJsonBytes(login))) .andExpect(status().isUnauthorized()) .andExpect(jsonPath("$.id_token").doesNotExist()) .andExpect(header().doesNotExist("Authorization")); } }
c707b74b1866739966b061013912781276aa7375
4dfc5c280624ac005d41dc18d17849ce235cc40f
/SpongeLauncher/src/org/bruddasmc/spongelauncher/listeners/StandOnSpongeListener.java
a715a451552f4e80af68c60c9cb9edb0eea97fa9
[]
no_license
Estremadoyro/BruddasMCustomPlugins
c375b439065984f044625124c5cb0532e00e05e0
e1dd2eaeb8d163dcdd91c0d401a3acf39d850f9c
refs/heads/main
2022-12-28T06:05:50.985595
2020-10-14T03:21:54
2020-10-14T03:21:54
303,890,986
1
0
null
null
null
null
UTF-8
Java
false
false
1,946
java
package org.bruddasmc.spongelauncher.listeners; import java.util.ArrayList; import java.util.List; import org.bruddasmc.spongelauncher.Main; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerJoinEvent; import org.bukkit.event.player.PlayerMoveEvent; //import org.bukkit.event.player.PlayerToggleFlightEvent; public class StandOnSpongeListener implements Listener{ @SuppressWarnings("unused") private static Main plugin ; @SuppressWarnings("static-access") public StandOnSpongeListener (Main plugin) { this.plugin = plugin ; Bukkit.getPluginManager().registerEvents(this, plugin); } private List<String> players = new ArrayList<String>() ; @EventHandler public void setFly(PlayerJoinEvent e) { e.getPlayer().setAllowFlight(true); e.getPlayer().setFlying(false); } @EventHandler public void setVelocity(PlayerMoveEvent e) { Player player = (Player) e.getPlayer() ; Location loc = e.getPlayer().getLocation() ; //loc.setY(loc.getY() -2); Block block = loc.getBlock().getRelative(BlockFace.DOWN); if(block.getType() == Material.SPONGE && !(players.contains(player.getName()))) { e.setCancelled(true) ; //e.setCancelled(true); //player.setAllowFlight(false); //player.setFlying(false); //player.setVelocity(e.getPlayer().getLocation().getDirection().multiply(1.5).setY(1)); //player.playSound(player.getLocation(), Sound.BAT_TAKEOFF, 1.0f, -5.0f); //player.setFallDistance(100); player.sendMessage(player.getName() + "is standing on " + block.getType()); players.add(player.getName()) ; } else { if (players.contains(player.getName())){ e.setCancelled(true) ; players.remove(player.getName()) ; } } } }
0c0886ca8703653604151f6b5a20d02ef5c85b06
8f70fe0e87e308fe3dc8cfe9a515a315ed131d18
/src/test/java/com/sugarcrm/test/contacts/Contacts_23673.java
755b62331d42c98156b4c4a354292efdf45f8c6e
[]
no_license
mustaeenbasit/LKW-Walter_Automation
76fd02c34c766bc34a5c300e3f5943664c70d67b
a97f4feca8e51c21f3cef1949573a8e4909e7143
refs/heads/master
2020-04-09T17:54:32.252374
2018-12-05T09:49:29
2018-12-05T09:49:29
160,495,697
0
0
null
null
null
null
UTF-8
Java
false
false
1,654
java
package com.sugarcrm.test.contacts; import org.junit.Assert; import org.junit.Test; import com.sugarcrm.sugar.VoodooUtils; import com.sugarcrm.sugar.records.NoteRecord; import com.sugarcrm.sugar.views.StandardSubpanel; import com.sugarcrm.test.SugarTest; public class Contacts_23673 extends SugarTest{ public void setup() throws Exception { sugar().login(); sugar().contacts.create(); } /** * Test Case 23673: Delete note or attachment_Verify that a related note or attachment * can be deleted from contact detail view. * * @throws Exception */ @Test public void Contacts_23673_execute() throws Exception { VoodooUtils.voodoo.log.info("Running " + testName + "..."); // Go to Contacts record view sugar().contacts.listView.clickRecord(1); // Link Notes record to the Contact StandardSubpanel notesSub = sugar().contacts.recordView.subpanels.get(sugar().notes.moduleNamePlural); NoteRecord noteRecord = (NoteRecord) notesSub.create(sugar().notes.getDefaultData()); // Go to Contacts record view sugar().contacts.navToListView(); sugar().contacts.listView.clickRecord(1); // Select "Unlink" action in Notes sub-panel. notesSub.unlinkRecord(1); // Verify that the Note record is not displayed in "Notes" sub-panel Assert.assertTrue("Notes subpanel is not empty", notesSub.isEmpty()); // Verify that the Note record is still available in Notes module sugar().notes.navToListView(); sugar().notes.listView.getDetailField(1, "subject").assertEquals(noteRecord.getRecordIdentifier(), true); VoodooUtils.voodoo.log.info(testName + " complete."); } public void cleanup() throws Exception {} }
637a96f2dd108ab6731a6dbe31c352d4a621a089
fd945c643a8235089ae03f5c9cca1df43da93045
/ZoneModule/src/main/java/edu/ncu/chattingsys/zone/controller/ZoneController.java
7fcc411173036be2e99d8e5357c7b67c365cc192
[]
no_license
Tyleryq/chatting_system
391a7c32d615d53243eb295280bc8d64af758e23
5f0908fbc6c1adbd92ead30acfa88c97e892aa8a
refs/heads/master
2023-07-02T07:24:20.292099
2021-08-05T15:16:13
2021-08-05T15:16:13
379,899,778
0
0
null
null
null
null
UTF-8
Java
false
false
2,017
java
package edu.ncu.chattingsys.zone.controller; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONArray; import edu.ncu.chattingsys.commonsapi.model.domain.Message; import edu.ncu.chattingsys.commonsapi.model.domain.Zone; import edu.ncu.chattingsys.commonsapi.model.responseData.ZoneResponseData; import edu.ncu.chattingsys.zone.service.IMQSend; import edu.ncu.chattingsys.zone.service.MQSend; import edu.ncu.chattingsys.zone.service.ZoneService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping(value = "/zone") public class ZoneController { @Autowired private ZoneService zoneService; @RequestMapping(value = "/publishZone") public void publishZone(Integer uid,String content){ zoneService.publishZone(uid, content); } @RequestMapping(value = "/deleteZone") public void deleteZone(Integer uid,Integer zone_id){ zoneService.deleteZone(zone_id,uid); } @RequestMapping(value = "/likeZone") public void likeZone(Integer zid,Integer uid){ zoneService.likeZone(zid,uid); } @RequestMapping(value = "/addComment") public void addComment(Integer zid,Integer uid,String content){ zoneService.addComment(zid, uid, content); } @RequestMapping(value = "/setZonePermission") public void setZonePermission(Integer uid,Integer fid,Boolean p){ zoneService.setZonePermission(uid, fid, p); } @RequestMapping(value = "/getFriendsZones") public List<ZoneResponseData> getFriendsZonesByUid(Integer uid){ return zoneService.getFriendsZonesByUid(uid); } @RequestMapping(value = "/getFriendZonesByFid") public List<ZoneResponseData> getFriendZonesByFid(Integer uid,Integer fid){ return zoneService.getFriendZonesByFid(uid,fid); } }
798a6296fb2adf8aa6df5f4399512b83a8a74218
4bdf5eba0ed2b6864169c4a0fbee635ad8e71955
/app/src/test/java/com/broadstar/blecarddemo/ExampleUnitTest.java
43ff40e9e713987d61c4670cce8519bcaed95c40
[]
no_license
BroadStar/BleCardDemo
60b0550e7a8b5134fc17ac37cbbb169751bf2d60
e3fa142ba85f936e507959ee693f2d5a1c7a6f12
refs/heads/master
2020-05-29T08:46:53.635995
2016-09-23T02:30:09
2016-09-23T02:30:09
null
0
0
null
null
null
null
UTF-8
Java
false
false
303
java
package com.broadstar.blecarddemo; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
ea11358f244eea55e1c95c35fa6c6136ee663457
ca0e9689023cc9998c7f24b9e0532261fd976e0e
/src/com/tencent/mm/protocal/g$c.java
202e46df46d7b248043011bae9a08b05cff15a25
[]
no_license
honeyflyfish/com.tencent.mm
c7e992f51070f6ac5e9c05e9a2babd7b712cf713
ce6e605ff98164359a7073ab9a62a3f3101b8c34
refs/heads/master
2020-03-28T15:42:52.284117
2016-07-19T16:33:30
2016-07-19T16:33:30
null
0
0
null
null
null
null
UTF-8
Java
false
false
474
java
package com.tencent.mm.protocal; import com.tencent.mm.network.o; public abstract interface g$c { public abstract o L(int paramInt1, int paramInt2); public abstract void a(g.g paramg, int paramInt1, int paramInt2, String paramString); public abstract int tV(); public static final class a { public static g.c iUy; } } /* Location: * Qualified Name: com.tencent.mm.protocal.g.c * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
c04288d343fb1888c6d70d22af3137a9a3c409c5
dcfeff72e78bc9ee173ad9355f9000690d336f21
/src/test/java/com/sd/Drivers_Definition.java
ba06a004e5be206a0ba6136fffda609158322c95
[]
no_license
pathaabhishek/softpedia_application
a83222e496e1c2c7445ca5d904cfc2eeb28588e5
18d30847bcc4b2ad9dbe034e63915973321c670c
refs/heads/master
2021-12-24T15:45:43.800639
2020-04-10T06:48:35
2020-04-10T06:48:35
254,055,223
0
0
null
2021-12-14T21:43:46
2020-04-08T10:22:42
Java
UTF-8
Java
false
false
1,266
java
package com.sd; import cucumber.api.java.en.Given; import cucumber.api.java.en.And; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.cts.Seleniumutility.seleniumutil; import com.cts.baseclass.Wrapperclass; import com.pages.Driver_page; public class Drivers_Definition extends Wrapperclass { Driver_page ab; seleniumutil screenshot; final static Logger LOG = LogManager.getLogger(Drivers_Definition.class.getName()); @Given("^Launch the sp applicaion$") public void launch_the_sp_applicaion() throws Throwable { launchApp(); LOG.info("Browser sp launched sucessfully"); } @And("^The user on click to the DRIVERS in the application$") public void the_user_on_click_to_the_drivers_in_the_application() { screenshot = new seleniumutil(driver); screenshot.takeSnapShot("C:\\abhishek\\Softpedia\\src\\test\\resources\\screenshot\\Drive.png"); ab=new Driver_page(driver); ab.gdrivers(); ab.gnetgear(); //ab.gfirmware(); LOG.info("the user clicks the drivers"); } @Given("^Browser is quit$") public void browser_is_quit() { driver.quit(); LOG.info("Browser sucessfully quited"); } }
[ "abhil@LAPTOP-KCS1GBLE" ]
abhil@LAPTOP-KCS1GBLE
015387ad373f558c2d35191c69b71be36c11b191
e9f68a2333b9d1ea0df4837b917b548e4629f236
/com.microfocus.awmplugins.git/src/com/microfocus/awmplugins/git/commands/GitBranch.java
4896c27a01f872baa8167e27775f159844cbbd46
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
csabimf/awm-git
111ccb2621b2d6646dff9c816d3405434a5200eb
630e8902b62eb2ec926dcb798e138096ca178c5b
refs/heads/master
2022-12-14T01:56:25.513237
2020-09-13T23:32:12
2020-09-13T23:32:12
266,887,394
1
0
null
null
null
null
UTF-8
Java
false
false
203
java
package com.microfocus.awmplugins.git.commands; public class GitBranch extends BasicCommand { public GitBranch(final Repository repository) { super(repository, "branch"); } }
[ "" ]
7b63f3e5872fc02888147dce561fada6da39f4a6
7c22fa05a0634ed4487e484d36d9e4f943983967
/sdk/redisenterprise/azure-resourcemanager-redisenterprise/src/main/java/com/azure/resourcemanager/redisenterprise/implementation/DatabaseImpl.java
9156ad5627431eef89c5b2c1b4601c743430d78f
[ "BSD-3-Clause", "LicenseRef-scancode-warranty-disclaimer", "LGPL-2.1-or-later", "Apache-2.0", "MIT", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-generic-cla" ]
permissive
sima-zhu/azure-sdk-for-java
88c3af0dcb61a80d9a8bcc3d4361eb172aa6e18b
b0c8cddc0d9f02761f6986367d1027c18b45e94c
refs/heads/master
2023-01-12T07:26:44.449066
2022-05-19T22:50:31
2022-05-19T22:50:31
176,790,225
0
1
MIT
2021-02-23T19:03:19
2019-03-20T18:03:30
Java
UTF-8
Java
false
false
10,227
java
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // Code generated by Microsoft (R) AutoRest Code Generator. package com.azure.resourcemanager.redisenterprise.implementation; import com.azure.core.http.rest.Response; import com.azure.core.util.Context; import com.azure.resourcemanager.redisenterprise.RedisEnterpriseManager; import com.azure.resourcemanager.redisenterprise.fluent.models.DatabaseInner; import com.azure.resourcemanager.redisenterprise.models.AccessKeys; import com.azure.resourcemanager.redisenterprise.models.ClusteringPolicy; import com.azure.resourcemanager.redisenterprise.models.Database; import com.azure.resourcemanager.redisenterprise.models.DatabasePropertiesGeoReplication; import com.azure.resourcemanager.redisenterprise.models.DatabaseUpdate; import com.azure.resourcemanager.redisenterprise.models.EvictionPolicy; import com.azure.resourcemanager.redisenterprise.models.ExportClusterParameters; import com.azure.resourcemanager.redisenterprise.models.ForceUnlinkParameters; import com.azure.resourcemanager.redisenterprise.models.ImportClusterParameters; import com.azure.resourcemanager.redisenterprise.models.Module; import com.azure.resourcemanager.redisenterprise.models.Persistence; import com.azure.resourcemanager.redisenterprise.models.Protocol; import com.azure.resourcemanager.redisenterprise.models.ProvisioningState; import com.azure.resourcemanager.redisenterprise.models.RegenerateKeyParameters; import com.azure.resourcemanager.redisenterprise.models.ResourceState; import java.util.Collections; import java.util.List; public final class DatabaseImpl implements Database, Database.Definition, Database.Update { private DatabaseInner innerObject; private final RedisEnterpriseManager serviceManager; public String id() { return this.innerModel().id(); } public String name() { return this.innerModel().name(); } public String type() { return this.innerModel().type(); } public Protocol clientProtocol() { return this.innerModel().clientProtocol(); } public Integer port() { return this.innerModel().port(); } public ProvisioningState provisioningState() { return this.innerModel().provisioningState(); } public ResourceState resourceState() { return this.innerModel().resourceState(); } public ClusteringPolicy clusteringPolicy() { return this.innerModel().clusteringPolicy(); } public EvictionPolicy evictionPolicy() { return this.innerModel().evictionPolicy(); } public Persistence persistence() { return this.innerModel().persistence(); } public List<Module> modules() { List<Module> inner = this.innerModel().modules(); if (inner != null) { return Collections.unmodifiableList(inner); } else { return Collections.emptyList(); } } public DatabasePropertiesGeoReplication geoReplication() { return this.innerModel().geoReplication(); } public DatabaseInner innerModel() { return this.innerObject; } private RedisEnterpriseManager manager() { return this.serviceManager; } private String resourceGroupName; private String clusterName; private String databaseName; private DatabaseUpdate updateParameters; public DatabaseImpl withExistingRedisEnterprise(String resourceGroupName, String clusterName) { this.resourceGroupName = resourceGroupName; this.clusterName = clusterName; return this; } public Database create() { this.innerObject = serviceManager .serviceClient() .getDatabases() .create(resourceGroupName, clusterName, databaseName, this.innerModel(), Context.NONE); return this; } public Database create(Context context) { this.innerObject = serviceManager .serviceClient() .getDatabases() .create(resourceGroupName, clusterName, databaseName, this.innerModel(), context); return this; } DatabaseImpl(String name, RedisEnterpriseManager serviceManager) { this.innerObject = new DatabaseInner(); this.serviceManager = serviceManager; this.databaseName = name; } public DatabaseImpl update() { this.updateParameters = new DatabaseUpdate(); return this; } public Database apply() { this.innerObject = serviceManager .serviceClient() .getDatabases() .update(resourceGroupName, clusterName, databaseName, updateParameters, Context.NONE); return this; } public Database apply(Context context) { this.innerObject = serviceManager .serviceClient() .getDatabases() .update(resourceGroupName, clusterName, databaseName, updateParameters, context); return this; } DatabaseImpl(DatabaseInner innerObject, RedisEnterpriseManager serviceManager) { this.innerObject = innerObject; this.serviceManager = serviceManager; this.resourceGroupName = Utils.getValueFromIdByName(innerObject.id(), "resourceGroups"); this.clusterName = Utils.getValueFromIdByName(innerObject.id(), "redisEnterprise"); this.databaseName = Utils.getValueFromIdByName(innerObject.id(), "databases"); } public Database refresh() { this.innerObject = serviceManager .serviceClient() .getDatabases() .getWithResponse(resourceGroupName, clusterName, databaseName, Context.NONE) .getValue(); return this; } public Database refresh(Context context) { this.innerObject = serviceManager .serviceClient() .getDatabases() .getWithResponse(resourceGroupName, clusterName, databaseName, context) .getValue(); return this; } public AccessKeys listKeys() { return serviceManager.databases().listKeys(resourceGroupName, clusterName, databaseName); } public Response<AccessKeys> listKeysWithResponse(Context context) { return serviceManager.databases().listKeysWithResponse(resourceGroupName, clusterName, databaseName, context); } public AccessKeys regenerateKey(RegenerateKeyParameters parameters) { return serviceManager.databases().regenerateKey(resourceGroupName, clusterName, databaseName, parameters); } public AccessKeys regenerateKey(RegenerateKeyParameters parameters, Context context) { return serviceManager .databases() .regenerateKey(resourceGroupName, clusterName, databaseName, parameters, context); } public void importMethod(ImportClusterParameters parameters) { serviceManager.databases().importMethod(resourceGroupName, clusterName, databaseName, parameters); } public void importMethod(ImportClusterParameters parameters, Context context) { serviceManager.databases().importMethod(resourceGroupName, clusterName, databaseName, parameters, context); } public void export(ExportClusterParameters parameters) { serviceManager.databases().export(resourceGroupName, clusterName, databaseName, parameters); } public void export(ExportClusterParameters parameters, Context context) { serviceManager.databases().export(resourceGroupName, clusterName, databaseName, parameters, context); } public void forceUnlink(ForceUnlinkParameters parameters) { serviceManager.databases().forceUnlink(resourceGroupName, clusterName, databaseName, parameters); } public void forceUnlink(ForceUnlinkParameters parameters, Context context) { serviceManager.databases().forceUnlink(resourceGroupName, clusterName, databaseName, parameters, context); } public DatabaseImpl withClientProtocol(Protocol clientProtocol) { if (isInCreateMode()) { this.innerModel().withClientProtocol(clientProtocol); return this; } else { this.updateParameters.withClientProtocol(clientProtocol); return this; } } public DatabaseImpl withPort(Integer port) { this.innerModel().withPort(port); return this; } public DatabaseImpl withClusteringPolicy(ClusteringPolicy clusteringPolicy) { if (isInCreateMode()) { this.innerModel().withClusteringPolicy(clusteringPolicy); return this; } else { this.updateParameters.withClusteringPolicy(clusteringPolicy); return this; } } public DatabaseImpl withEvictionPolicy(EvictionPolicy evictionPolicy) { if (isInCreateMode()) { this.innerModel().withEvictionPolicy(evictionPolicy); return this; } else { this.updateParameters.withEvictionPolicy(evictionPolicy); return this; } } public DatabaseImpl withPersistence(Persistence persistence) { if (isInCreateMode()) { this.innerModel().withPersistence(persistence); return this; } else { this.updateParameters.withPersistence(persistence); return this; } } public DatabaseImpl withModules(List<Module> modules) { if (isInCreateMode()) { this.innerModel().withModules(modules); return this; } else { this.updateParameters.withModules(modules); return this; } } public DatabaseImpl withGeoReplication(DatabasePropertiesGeoReplication geoReplication) { if (isInCreateMode()) { this.innerModel().withGeoReplication(geoReplication); return this; } else { this.updateParameters.withGeoReplication(geoReplication); return this; } } private boolean isInCreateMode() { return this.innerModel().id() == null; } }
04efbe90e262c3941b38a7f5362220bf738ce49f
c5a5a92ac6e972a9be80deb13b3b6c67e5436b95
/workspace/exemplo-di/src/com/algaworks/di/service/AtivacaoClienteService.java
d27fb64ecc269b698614e934b438a298037b307d
[]
no_license
celsofurtado/algaworks
5628eb2aaa03537353206e05377a40f0e83ff6dc
598ae716c7030d383cae1448d873beaca6f97e30
refs/heads/main
2023-04-13T16:58:46.168186
2021-04-19T22:30:30
2021-04-19T22:30:30
359,615,373
0
0
null
null
null
null
UTF-8
Java
false
false
449
java
package com.algaworks.di.service; import com.algaworks.di.modelo.Cliente; import com.algaworks.di.notificacao.Notificador; public class AtivacaoClienteService { private Notificador notificador; public AtivacaoClienteService(Notificador notificador) { this.notificador = notificador; } public void ativar(Cliente cliente) { cliente.ativar(true); this.notificador.notificar(cliente, "Seu cadastro no sistema foi ativado!"); } }
[ "Celso Furtado" ]
Celso Furtado
b1a37cee56422c770cf46c6f7716213f089dd45a
e803bb6408cef90ab0fd831c04b6555b268dea0c
/PawarisaClinicApp/app/src/main/java/com/example/aoyler/pawarisaclinicapp/ViewPatientActivity.java
402a4d016b3e0a282c131d629f8bc54df6d00a27
[]
no_license
wannisa/Project2Update
d298146373da82f6259878d1bd0083d34fdae1ef
60f6609b0e3a82ea90ef225bfe291c02d6daec16
refs/heads/master
2020-07-18T02:38:56.851664
2016-09-09T07:50:45
2016-09-09T07:50:45
67,778,494
0
0
null
null
null
null
UTF-8
Java
false
false
2,035
java
package com.example.aoyler.pawarisaclinicapp; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.Window; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.squareup.picasso.Picasso; public class ViewPatientActivity extends AppCompatActivity { String Title, valID; private WebView webview; private static final String TAG = "Main"; private ProgressDialog progressBar; WebView browser; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_view_patient); //https://surasak.io/pawarisaclinic/view.php?ID= Bundle b = getIntent().getExtras(); Title = b.getString("valTitle"); valID = b.getString("valID"); TextView textView = (TextView) findViewById(R.id.Title); if(valID.isEmpty()){ textView.setText("ไม่พบข้อมูล"); } else { textView.setText("Title: " + Title); } // find the WebView by name in the main.xml of step 2 browser = (WebView) findViewById(R.id.webview); // Enable javascript browser.getSettings().setJavaScriptEnabled(true); // Set WebView client browser.setWebChromeClient(new WebChromeClient()); browser.setWebViewClient(new WebViewClient() { @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } }); // Load the webpage browser.loadUrl("https://surasak.io/pawarisaclinic/view.php?ID="+valID); } }
cd2d0ec0718716d58b79950bd76663dec97de2fc
e41ef7cd577206b364620d5e1758f04443642e52
/app/src/main/java/com/askonlinesolutions/user/tabqyclient/RecentSearchAdapter.java
b9d80d426c276f1fdb529e0030ba8c234cff6ff2
[]
no_license
askonlinesolutions/TABQYClient
864c2e6dbf7a1809f1d3f16a091d8039a29b67f7
036b26091deb64eb64216c573d119d6b61b4e9e6
refs/heads/master
2020-03-30T16:14:17.374293
2019-01-23T13:44:15
2019-01-23T13:44:15
151,399,820
0
0
null
null
null
null
UTF-8
Java
false
false
1,519
java
package com.askonlinesolutions.user.tabqyclient; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import java.util.ArrayList; class RecentSearchAdapter extends RecyclerView.Adapter<RecentSearchAdapter.ViewHolder> { ArrayList name; Context context; public RecentSearchAdapter(CheckoutAddAddressActivity checkoutAddAddressActivity, ArrayList name) { this.context = checkoutAddAddressActivity; this.name =name; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recent_searches,parent,false); RecentSearchAdapter.ViewHolder vh =new RecentSearchAdapter.ViewHolder(view); return new RecentSearchAdapter.ViewHolder(view) { }; } @Override public void onBindViewHolder(@NonNull ViewHolder holder, int position) { holder.textView.setText(name.get(position).toString()); } @Override public int getItemCount() { return name.size(); } public class ViewHolder extends RecyclerView.ViewHolder { TextView textView; public ViewHolder(View itemView) { super(itemView); textView =(TextView)itemView.findViewById(R.id.text); } } }
7f811e9ab525d16861460508e6d952c8f1dfae73
0cc7b3a89090de4ec41b61aadf78ee6eb40c0850
/ex02/src/main/java/org/zerock/domain/BoardVO.java
e342ae245ab177b9240221a1de78a79c153bc45b
[]
no_license
TheRei3/Code-Learning-Spring-Web-Project
db01dc3552e37fe4929afe38a1c420cdd4a45e0e
2de2e3e7ce19e1ad8b3a8912a3d7c09925bcaa57
refs/heads/master
2023-06-14T04:29:53.101979
2021-07-05T06:19:45
2021-07-05T06:19:45
375,955,421
1
0
null
null
null
null
UTF-8
Java
false
false
972
java
package org.zerock.domain; import java.util.Date; public class BoardVO { private Long bno; private String title; private String content; private String writer; private Date regdate; private Date updatedate; public Long getBno() { return bno; } public void setBno(Long bno) { this.bno = bno; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getWriter() { return writer; } public void setWriter(String writer) { this.writer = writer; } public Date getRegdate() { return regdate; } public void setRegdate(Date regdate) { this.regdate = regdate; } public Date getUpdatedate() { return updatedate; } public void setUpdatedate(Date updatedate) { this.updatedate = updatedate; } }
[ "admin@DESKTOP-8L2IG92" ]
admin@DESKTOP-8L2IG92
a532c1b58cb20ee3880352ffc83b79cb4d86c6dd
404beff133aa4b9f287e32233c499a6c8ec44d23
/super_paint/src/super_paint/ventana_histograma.java
9503927b79608a8f9056c34b36f4b538c0d65576
[]
no_license
galleta/rock-and-paint
2724bd88503fe48f405dce88d98aeca3044b6f11
511023bf0aac09ad22ad63e3109e285dfab9cff9
refs/heads/master
2021-01-07T14:49:08.287707
2020-02-19T21:38:39
2020-02-19T21:38:39
241,731,469
0
0
null
null
null
null
ISO-8859-1
Java
false
false
4,700
java
package super_paint; import javax.swing.*; import java.awt.*; import java.awt.image.BufferedImage; import java.awt.image.DataBuffer; import java.awt.geom.*; import java.awt.geom.AffineTransform; import java.awt.image.AffineTransformOp; import javax.swing.event.*; /** * <p>Título: Práctica de Sistemas Multimedia</p> * <p>Descripción: Práctica de Sistemas Multimedia</p> * <p>Copyright: Copyright (c) 2009</p> * <p>Empresa: Piratas Sin Fronteras S.A.</p> * @author Francisco Jesús Delgado Almirón * @version 1.0 */ public class ventana_histograma extends JInternalFrame { BufferedImage ima; Ventana_imagen creador; private int[] datos_histograma = new int[256]; private int veces_que_se_ha_dibujado_el_histograma = 0; BorderLayout borderLayout1 = new BorderLayout(); Lienzo_no_dibujar jPanelHistograma; public ventana_histograma(Ventana_imagen i) { try { creador = i; ima = creador.jPanelDibujar.getImagen(); jbInit(); } catch(Exception ex) { ex.printStackTrace(); } } /** * <p><u>Descripción</u>: Esta función calcula el máximo de un array de enteros.</p> * @param v Array para calcular el máximo * @return Máximo del array */ int maximo(int[] v) { int resultado = v[0]; for(int i = 0; i < v.length; i++) { if (v[i] > resultado) { resultado = v[i]; } } return resultado; } public void paint(Graphics g) { super.paint(g); Graphics2D g_histograma = (Graphics2D) g; g_histograma = (Graphics2D) jPanelHistograma.getImagen().getGraphics(); if( veces_que_se_ha_dibujado_el_histograma == 0 ) dibujar(g_histograma); } /** * <p><u>Descripción</u>: Esta función dibuja el histograma de la imagen.</p> * @param g Objeto Graphics2D para dibujar */ void dibujar(Graphics2D g) { int max = maximo(datos_histograma); for(int i = 0; i < 256; i++) { if( datos_histograma[i] > 0 ) { Point inicio = new Point(i + 22, 0), p_final = new Point(i + 22, (datos_histograma[i] * 256) / max); Shape linea = new Line2D.Float(inicio, p_final); g.setPaint(Color.BLACK); g.draw(linea); } } BufferedImage imgSource = jPanelHistograma.getImagen(); AffineTransform at = AffineTransform.getRotateInstance(Math.toRadians(180.0), 150,150); AffineTransformOp atop = new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR); BufferedImage imgdest = atop.filter( imgSource, null); jPanelHistograma.setImagen(imgdest); repaint(); veces_que_se_ha_dibujado_el_histograma++; } void jbInit() throws Exception { ImageIcon icono_frame = new ImageIcon("iconos/imagen.gif"); this.setFrameIcon(icono_frame); jPanelHistograma = new Lienzo_no_dibujar(); this.setTitle("Histograma de: " + creador.getTitle().substring(0, creador.getTitle().length() - 15)); this.addInternalFrameListener(new ventana_histograma_this_internalFrameAdapter(this)); this.setClosable(true); this.getContentPane().setLayout(borderLayout1); jPanelHistograma.setBackground(Color.white); this.getContentPane().add(jPanelHistograma, BorderLayout.CENTER); DataBuffer datos = ima.getRaster().getDataBuffer(); int[] datos_imagen = new int[ datos.getSize() ]; for(int i = 0; i < 256; i++) datos_histograma[i] = 0; for(int i = 0; i < datos.getSize(); i++) datos_imagen[i] = datos.getElem(i); try { for (int i = 0; i < datos_imagen.length; i++) { if( datos_imagen[i]%256 < 0 ) datos_histograma[255]++; else datos_histograma[datos_imagen[i] % 256]++; } } catch(Exception ex) { ex.printStackTrace(); } } void this_internalFrameActivated(InternalFrameEvent e) { creador.creador.jMenuGuardar.setEnabled(false); creador.creador.jMenuImprimir.setEnabled(false); creador.creador.jMenuHistograma.setEnabled(false); creador.creador.jMenuDeshacer.setEnabled(false); creador.creador.jMenuRehacer.setEnabled(false); creador.creador.setUltimaVentanaImagenSeleccionada(null); } } class ventana_histograma_this_internalFrameAdapter extends javax.swing.event.InternalFrameAdapter { ventana_histograma adaptee; ventana_histograma_this_internalFrameAdapter(ventana_histograma adaptee) { this.adaptee = adaptee; } public void internalFrameActivated(InternalFrameEvent e) { adaptee.this_internalFrameActivated(e); } }
d176ded6baf04c8c060bff8c4a12cff90465907f
e0734741fdd756f26d063a29341e231a94fcb5a4
/src/main/java/br/com/alelo/consumer/consumerpat/exception/InternalException.java
dc30aafd614e6616ef5fb34256cedb39fda2feea
[]
no_license
DiegoRamalho/consumer-pat
26c73f3642388f9c5b247abf5d7215ff2988f44d
99190142b75f35801cc13803f3c1bb535da18770
refs/heads/main
2023-07-23T01:06:01.251970
2021-07-30T14:27:42
2021-07-30T14:27:42
389,720,095
0
0
null
2021-07-26T17:44:20
2021-07-26T17:44:19
null
UTF-8
Java
false
false
449
java
package br.com.alelo.consumer.consumerpat.exception; import lombok.Getter; @Getter public class InternalException extends RuntimeException { private String details; public InternalException(String message, String details) { super(message); this.details = details; } public InternalException(String message, Throwable cause, String details) { super(message, cause); this.details = details; } }
29c997bae82afc27d7a1b150072c72c57ec8c557
eaeaf5ecc604e84f47ddbdc4791197d96c0018ce
/src/java/thoth/controle/RedirecionaPaginaProfessor.java
451f651a37fdfe419a9f0facd66b015fe72f9317
[]
no_license
GabrielGalucio/THOTH-Certification
df217ec681f30134052347ac267c9ac3bd9872cd
cac759c2266c0daf4764a6bdbc17ce5eb317a065
refs/heads/master
2020-12-06T06:08:44.359656
2020-03-27T06:26:52
2020-03-27T06:26:52
232,361,668
0
0
null
null
null
null
UTF-8
Java
false
false
2,753
java
package thoth.controle; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author moise */ @WebServlet(name = "RedirecionaPaginaProfessor", urlPatterns = {"/RedirecionaPaginaProfessor"}) public class RedirecionaPaginaProfessor extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet RedirecionaPaginaProfessor</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>Servlet RedirecionaPaginaProfessor at " + request.getContextPath() + "</h1>"); out.println("</body>"); out.println("</html>"); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // processRequest(request, response); int tela = Integer.parseInt( request.getParameter("cd") ); if( tela == 1 ){ request.getRequestDispatcher("TelaEquipeProfessor.jsp").forward(request, response); } } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
72fc442617c73e9e621a6fba396bfe27bd4fbc47
0568ed6d61ee2b7e18b1a98f860332cf2021ea6d
/src/main/java/me/imoko/job/Worker.java
a46a43b016327da7f99580466fe6ca10c7b15975
[]
no_license
sutoo/MysqlJobQueue
173d7aa7f0fda625cb62b1ecc603182ceb677be0
09324a7acc994fe0ce0d910871691638975dceab
refs/heads/master
2021-01-25T04:53:03.455541
2015-02-03T11:47:46
2015-02-03T11:47:46
30,234,576
0
0
null
null
null
null
UTF-8
Java
false
false
3,325
java
package me.imoko.job; import org.joda.time.DateTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.List; import java.util.concurrent.TimeUnit; /** * Created by sutao on 15/1/20. */ public class Worker implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(Worker.class); final QueueDao queueDao; final String queueName; final String workerId; final IProcessor processor; private volatile boolean isRunning; public Worker(String queueName, String processorId, IProcessor processor, QueueDao queueDao) { this.queueDao = queueDao; this.isRunning = true; this.queueName = queueName; this.workerId = processorId; this.processor = processor; } private int doWork() { int locked = queueDao.lock(this.queueName, this.workerId); LOG.info("{}|{}", this.workerId, locked); List<QueueEntry> queueEntries = this.queueDao.fetchLocked(this.queueName, this.workerId); if (queueEntries.size() < locked) { LOG.warn("FetchLocked size < locked size."); } int processed = 0; for (QueueEntry entry : queueEntries) { LOG.info("processQueueEntry|{}|{}", this.workerId, entry.getId()); String jobEntry = entry.getJobEntry(); boolean isDone = false; try { isDone = this.processor.process(entry.getId(), jobEntry); } catch (Exception e) { LOG.warn("processQueueEntry|FAILED|{}|{}", this.workerId, entry.getId(), e); this.queueDao.changeStatus(entry.getId(), JobStatus.FAILED.getValue()); } if (!isDone) { reSchedule(entry); } processed++; } return processed; } private void dropJob(QueueEntry entry) { this.queueDao.deleteJob(entry.getId()); } private boolean rebuildJobEntry(QueueEntry entry) { int scheduleIntervalBySec = entry.getScheduledAt() - entry.getCreateTime(); if (scheduleIntervalBySec <= 0) { return false; } int nowSecond = (int) (DateTime.now().getMillis() / 1000); entry.setCreateTime(nowSecond); entry.setScheduledAt(nowSecond + scheduleIntervalBySec); entry.setStatus(JobStatus.PENDING.getValue()); entry.setRetryCnt(entry.getRetryCnt() - 1); return true; } private void reSchedule(QueueEntry entry) { int retryCnt = entry.getRetryCnt(); if (retryCnt <= 0) { dropJob(entry); return; } if (rebuildJobEntry(entry)) { this.queueDao.enqueue(entry); this.queueDao.deleteJob(entry.getId()); } else { this.queueDao.changeStatus(entry.getId(), JobStatus.FAILED.getValue()); } } @Override public void run() { try { while (isRunning) { int doneCnt = doWork(); if (doneCnt == 0) { //punish TimeUnit.SECONDS.sleep(10); } TimeUnit.SECONDS.sleep(1); } } catch (Exception e) { LOG.error("Worker run exception|{}", this.workerId, e); } } }
69e2a2e160ea600503e1933cafecad944e6b391c
0529524c95045b3232f6553d18a7fef5a059545e
/app/src/androidTest/java/TestCase_com_active_aps_pbk__687586932.java
9ed2de6517cd9d6262c9773fda43c43904cf8573
[]
no_license
sunxiaobiu/BasicUnitAndroidTest
432aa3e10f6a1ef5d674f269db50e2f1faad2096
fed24f163d21408ef88588b8eaf7ce60d1809931
refs/heads/main
2023-02-11T21:02:03.784493
2021-01-03T10:07:07
2021-01-03T10:07:07
322,577,379
0
0
null
null
null
null
UTF-8
Java
false
false
407
java
import android.system.Os; import androidx.test.runner.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; @RunWith(AndroidJUnit4.class) public class TestCase_com_active_aps_pbk__687586932 { public static void testCase() throws Exception { String var0 = "android"; Os.chmod(var0, 436); } @Test public void staticTest() throws Exception { testCase(); } }
1cb49a631eedc25d470f54c0b3f99201d69ed0cd
63ccda330f5af0eab97565fa1558db50ae57ed83
/surpre/java/test/jp/co/ziro/surpre/model/SurpreDataTest.java
7cd7c61cb1a1a5557abe3e9b1898c25fe018ba33
[]
no_license
weimingtom/enginee-ring
fd31467b8c0e95743754e12d1c8441b81569c84a
c13d11042ce7d56cdd8e49e1610d3cdd086a91e0
refs/heads/master
2021-01-10T01:36:36.546525
2010-05-05T09:49:03
2010-05-05T09:49:03
36,991,507
0
0
null
null
null
null
UTF-8
Java
false
false
408
java
package jp.co.ziro.surpre.model; import org.slim3.tester.AppEngineTestCase; import org.junit.Test; import static org.junit.Assert.*; import static org.hamcrest.CoreMatchers.*; public class SurpreDataTest extends AppEngineTestCase { private SurpreData model = new SurpreData(); @Test public void test() throws Exception { assertThat(model, is(notNullValue())); } }
f5e22a352af986c3ba48a7d46600ed0966a52beb
704507754a9e7f300dfab163e97cd976b677661b
/src/com/sun/org/apache/bcel/internal/classfile/ConstantUtf8.java
fb3c1738bb9ea9018e5f7b64bde9c1899dc43c7f
[]
no_license
ossaw/jdk
60e7ca5e9f64541d07933af25c332e806e914d2a
b9d61d6ade341b4340afb535b499c09a8be0cfc8
refs/heads/master
2020-03-27T02:23:14.010857
2019-08-07T06:32:34
2019-08-07T06:32:34
145,785,700
0
0
null
null
null
null
UTF-8
Java
false
false
4,991
java
/* * Copyright (c) 2007, 2017, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ package com.sun.org.apache.bcel.internal.classfile; /* * ==================================================================== * The Apache Software License, Version 1.1 * Copyright (c) 2001 The Apache Software Foundation. All rights * reserved. * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * 4. The names "Apache" and "Apache Software Foundation" and * "Apache BCEL" must not be used to endorse or promote products * derived from this software without prior written permission. For * written permission, please contact [email protected]. * 5. Products derived from this software may not be called "Apache", * "Apache BCEL", nor may "Apache" appear in their name, without * prior written permission of the Apache Software Foundation. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ import com.sun.org.apache.bcel.internal.Constants; import java.io.*; /** * This class is derived from the abstract * <A HREF="com.sun.org.apache.bcel.internal.classfile.Constant.html">Constant * </A> class and represents a reference to a Utf8 encoded string. * * @author <A HREF="mailto:[email protected]">M. Dahm</A> * @see Constant */ public final class ConstantUtf8 extends Constant { private String bytes; /** * Initialize from another object. */ public ConstantUtf8(ConstantUtf8 c) { this(c.getBytes()); } /** * Initialize instance from file data. * * @param file * Input stream * @throws IOException */ ConstantUtf8(DataInputStream file) throws IOException { super(Constants.CONSTANT_Utf8); bytes = file.readUTF(); } /** * @param bytes * Data */ public ConstantUtf8(String bytes) { super(Constants.CONSTANT_Utf8); if (bytes == null) throw new IllegalArgumentException("bytes must not be null!"); this.bytes = bytes; } /** * Called by objects that are traversing the nodes of the tree implicitely * defined by the contents of a Java class. I.e., the hierarchy of methods, * fields, attributes, etc. spawns a tree of objects. * * @param v * Visitor object */ public void accept(Visitor v) { v.visitConstantUtf8(this); } /** * Dump String in Utf8 format to file stream. * * @param file * Output file stream * @throws IOException */ public final void dump(DataOutputStream file) throws IOException { file.writeByte(tag); file.writeUTF(bytes); } /** * @return Data converted to string. */ public final String getBytes() { return bytes; } /** * @param bytes. */ public final void setBytes(String bytes) { this.bytes = bytes; } /** * @return String representation */ public final String toString() { return super.toString() + "(\"" + Utility.replace(bytes, "\n", "\\n") + "\")"; } }
9805c62c5fa5f43796599363f912c0cf1ec6181c
fb9b8cd6344df24d7446e01ac8429cf1cd92895e
/bekool/src/main/java/services/UserServicesRemote.java
d610f6df926a686ad5fdbf370894d3d1f9c64caa
[]
no_license
hassayoun/bokoolRepo
be39be4905cf61065873d3ecae95b4eb04ac04cc
e0120d049a4bf1761f9fc1dc4b8227f6ca262dac
refs/heads/master
2016-09-05T19:07:48.542984
2015-02-03T16:19:33
2015-02-03T16:19:33
30,029,466
0
1
null
null
null
null
UTF-8
Java
false
false
259
java
package services; import javax.ejb.Remote; import domain.User; @Remote public interface UserServicesRemote { Boolean addUser(User user); Boolean deleteUser(Integer id); Boolean updateUser(User user); User findUserById(Integer id); }
a8c87d1b8afd0c917fa8ee2a2495db4edb993a4f
ab846442deae0de1cadd8b679877837ea9f05398
/CentraleApp/src/com/example/centraleapp/GoogleMapActivity.java
ddfee6974165acca2f382cdd58cc954e53dd7ed6
[]
no_license
fmajeric/CentraleApp
6e67de8a07cd1f5903a114c0bacbe60e1e3594e0
d95a87a0c7944e59c27375e2156588997806e291
refs/heads/master
2016-09-08T00:31:06.481187
2013-01-27T19:42:53
2013-01-27T19:42:53
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,602
java
package com.example.centraleapp; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.graphics.drawable.Drawable; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.widget.Toast; import com.google.android.maps.GeoPoint; import com.google.android.maps.ItemizedOverlay; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.OverlayItem; public class GoogleMapActivity extends MapActivity implements LocationListener { MapView maMap = null; MapController monControler = null; double latitude = 0; double longitude = 0; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.googlemaplayout); latitude = Double.parseDouble(getIntent().getStringExtra("latitude")); longitude = Double.parseDouble(getIntent().getStringExtra("longitude")); maMap = (MapView) findViewById(R.id.myGmap); maMap.setBuiltInZoomControls(true); GeoPoint point = new GeoPoint(microdegrees(latitude), microdegrees(longitude)); ItemizedOverlayPerso pinOverlay = new ItemizedOverlayPerso( getResources().getDrawable(R.drawable.marker)); pinOverlay.addPoint(point); maMap.getOverlays().add(pinOverlay); monControler = maMap.getController(); monControler.setZoom(12); monControler.setCenter(point); LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f, this); } @Override public void onLocationChanged(Location location) { if (location != null) { Toast.makeText( this, "Nouvelle position : " + location.getLatitude() + ", " + location.getLongitude(), Toast.LENGTH_SHORT) .show(); monControler.animateTo(new GeoPoint(microdegrees(location .getLatitude()), microdegrees(location.getLongitude()))); } } @Override public boolean onCreateOptionsMenu(Menu menu) { menu.add(0, 100, 0, "Zoom In"); menu.add(0, 101, 0, "Zoom Out"); menu.add(0, 102, 0, "Satellite"); menu.add(0, 103, 0, "Trafic"); menu.add(0, 104, 0, "Street view"); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case 100: monControler.setZoom(maMap.getZoomLevel() + 1); break; case 101: monControler.setZoom(maMap.getZoomLevel() - 1); break; case 102: maMap.setSatellite(!maMap.isSatellite()); break; case 103: maMap.setTraffic(!maMap.isTraffic()); break; case 104: maMap.setStreetView(!maMap.isStreetView()); break; } return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { menu.findItem(102).setIcon( maMap.isSatellite() ? android.R.drawable.checkbox_on_background : android.R.drawable.checkbox_off_background); menu.findItem(103).setIcon( maMap.isTraffic() ? android.R.drawable.checkbox_on_background : android.R.drawable.checkbox_off_background); menu.findItem(104) .setIcon( maMap.isStreetView() ? android.R.drawable.checkbox_on_background : android.R.drawable.checkbox_off_background); return true; } private int microdegrees(double value) { return (int) (value * 1000000); } public class ItemizedOverlayPerso extends ItemizedOverlay<OverlayItem> { private List<GeoPoint> points = new ArrayList<GeoPoint>(); public ItemizedOverlayPerso(Drawable defaultMarker) { super(boundCenterBottom(defaultMarker)); } @Override protected OverlayItem createItem(int i) { GeoPoint point = points.get(i); return new OverlayItem(point, "Titre", "Description"); } @Override public int size() { return points.size(); } public void addPoint(GeoPoint point) { this.points.add(point); populate(); } public void clearPoint() { this.points.clear(); populate(); } } @Override protected boolean isRouteDisplayed() { // TODO Auto-generated method stub return false; } @Override public void onProviderDisabled(String provider) { // TODO Auto-generated method stub } @Override public void onProviderEnabled(String provider) { // TODO Auto-generated method stub } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // TODO Auto-generated method stub } }
[ "fmajeric@fmajeric.(none)" ]
fmajeric@fmajeric.(none)
d352f7d99b108fe487353c4f08846303c6c0c6b6
46d4680739cb15d16f4f0c66acb881c94e982677
/LeetCode/MergeKLists.java
9563c5ea25154393af6a753c46d089537950da97
[]
no_license
mail2vcnu/Algorithms-and-Data-Structures
189e81ad447c0131c0b17aa9a091f682b701b330
4a841fe56d9ac95013cdfd6a3644b2d712a67467
refs/heads/master
2023-03-19T22:17:36.670837
2019-12-08T10:07:49
2019-12-08T10:07:49
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,138
java
//https://leetcode.com/problems/merge-k-sorted-lists/ /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class MergeKLists { public ListNode mergeKLists(ListNode[] lists) { return mergeKLists(lists, 0, lists.length-1); } private ListNode mergeKLists(ListNode[] lists, int s, int e) { if (s == e) { return lists[s]; } else if (s < e) { int q = (s+e)/2; ListNode l1 = mergeKLists(lists, s, q); ListNode l2 = mergeKLists(lists, q+1, e); return mergeKLists(l1, l2); } else { return null; } } private ListNode mergeKLists(ListNode l1, ListNode l2) { if (l1 == null) { return l2; } if (l2 == null) { return l1; } if (l1.val < l2.val) { l1.next = mergeKLists(l1.next, l2); return l1; } else { l2.next = mergeKLists(l1, l2.next); return l2; } } }
4fb698f9acf6d2c36e79511b1f5f45dfc1b59c0f
010d84c74aef94be8a994416945d419405011b87
/app/src/main/java/com/nonk/gaocongdeweibo/Bean/StatusTimeLineResponse.java
3e0a32e64de950ac8968b71ee8a25fd42331b13c
[]
no_license
gaocong0511/gccWeibo
f066d2f58312e1557b8fed870e0e853c64689a0b
3932600afc8eeb4bfa1ceb2cab94f2718585ac14
refs/heads/master
2021-01-25T13:28:28.054892
2018-08-29T13:27:46
2018-08-29T13:27:46
123,573,778
0
0
null
null
null
null
UTF-8
Java
false
false
474
java
package com.nonk.gaocongdeweibo.Bean; import java.util.ArrayList; public class StatusTimeLineResponse { private ArrayList<Status> statuses; private int total_number; public ArrayList<Status> getStatuses() { return statuses; } public void setStatuses(ArrayList<Status> statuses) { this.statuses = statuses; } public int getTotal_number() { return total_number; } public void setTotal_number(int total_number) { this.total_number = total_number; } }
c7cad7a39b9baab888e02a1e2d5197b00d33af2f
417f480c2c73d3f33ad355899c9abbf227cc9161
/Odile/app/src/main/java/com/wolfie/odile/view/activity/OdileActivity.java
ad3dae19c12d87f4edbc2382acdf2d6066a9773d
[]
no_license
manangatangy/odile
3eb98c9f5167534cda96f0203b1f71553ec98b10
143f719c85018356d56393d69fc62b5a8d114279
refs/heads/master
2021-01-01T05:37:38.561794
2017-04-23T12:32:38
2017-04-23T12:32:38
77,760,985
0
0
null
null
null
null
UTF-8
Java
false
false
9,760
java
package com.wolfie.odile.view.activity; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import android.content.Intent; import android.os.Bundle; import android.speech.tts.TextToSpeech; import android.support.annotation.LayoutRes; import android.support.v4.view.MenuItemCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.widget.SearchView; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.drive.DriveId; import com.google.android.gms.drive.OpenFileActivityBuilder; import com.wolfie.odile.R; import com.wolfie.odile.presenter.DrawerPresenter; import com.wolfie.odile.presenter.ListPresenter; import com.wolfie.odile.presenter.MainPresenter; import com.wolfie.odile.view.fragment.DriveFragment; import com.wolfie.odile.view.fragment.EditFragment; import com.wolfie.odile.view.fragment.FileFragment; import com.wolfie.odile.view.fragment.ListFragment; import com.wolfie.odile.view.fragment.DrawerFragment; import com.wolfie.odile.view.fragment.TalkFragment; import butterknife.BindView; public class OdileActivity extends SimpleActivity { public static final int REQUEST_TTS_DATA_CHECK = 345; // public static final int REQUEST_DRIVE_RESOLUTION = 346; // public static final int REQUEST_DRIVE_OPENER = 347; @BindView(R.id.layout_activity_drawer) public DrawerLayout mDrawer; @BindView(R.id.progress_overlay) View mProgressOverlayView; @BindView(R.id.progress_overlay_text) TextView mProgressOverlayText; private MainPresenter mMainPresenter; @Override public MainPresenter getPresenter() { return mMainPresenter; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mMainPresenter = new MainPresenter(null, getApplicationContext()); // Set the initial values for some settings. May be changed later by SettingsPresenter // SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); // int sessionTimeout = prefs.getInt(SettingsPresenter.PREF_SESSION_TIMEOUT, TimeoutMonitor.DEFAULT_TIMEOUT); // mMainPresenter.setTimeout(sessionTimeout, false); // No need to start; we are not yet logged in // int enumIndex = prefs.getInt(SettingsPresenter.PREF_SESSION_BACKGROUND_IMAGE, 0); setBackgroundImage(0); // Create the main content fragment into it's container. setupFragment(ListFragment.class.getName(), R.id.fragment_container_activity_simple, null); // Create the drawer fragment into it's container. setupFragment(DrawerFragment.class.getName(), R.id.fragment_container_activity_drawer, null); // Create the entry edit (activity sheet) fragment into it's container. setupFragment(EditFragment.class.getName(), R.id.fragment_container_edit, null); // Create the file (activity sheet) fragment into it's container. setupFragment(FileFragment.class.getName(), R.id.fragment_container_file, null); // Create the drive (activity sheet) fragment into it's container. setupFragment(DriveFragment.class.getName(), R.id.fragment_container_drive, null); // Create the talk (activity sheet) fragment into it's container. setupFragment(TalkFragment.class.getName(), R.id.fragment_container_talk, null); // Create the settings (activity sheet) fragment into it's container. // setupFragment(SettingsFragment.class.getName(), R.id.fragment_container_settings, null); Intent checkIntent = new Intent(); checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA); startActivityForResult(checkIntent, REQUEST_TTS_DATA_CHECK); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch (requestCode) { case REQUEST_TTS_DATA_CHECK: if (resultCode != TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) { Intent installIntent = new Intent(); installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA); startActivity(installIntent); } break; // case REQUEST_DRIVE_RESOLUTION: // if (resultCode == RESULT_OK) { // mMainPresenter.restoreFromGoogleDrive(); // } else { // Toast.makeText(this, "Can't resolve Google Drive connection", Toast.LENGTH_LONG).show(); // } // break; // case REQUEST_DRIVE_OPENER: // DriveId driveId = null; // Null means no file selected. // if (resultCode == RESULT_OK) { // driveId = data.getParcelableExtra(OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID); // } // mMainPresenter.retrieveFileContents(driveId); //// } else { //// } // break; default: super.onActivityResult(requestCode, resultCode, data); } } @Override @LayoutRes public int getLayoutResource() { // Specify the layout to use for the OdileActivity. This layout include // the activity_simple layout, which contains the toolbar and the // fragment_container_activity_simple container (for ListFragment) as // well as fragment_container_activity_drawer for the DrawerFragment return R.layout.activity_drawer; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main_menu, menu); ListPresenter listPresenter = findPresenter(ListFragment.class); SearchViewHandler searchViewHandler = new SearchViewHandler(listPresenter); // Retrieve the SearchView and setup the callbacks. MenuItem searchItem = menu.findItem(R.id.action_search); SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem); searchView.setOnQueryTextListener(searchViewHandler); searchView.setOnSearchClickListener(searchViewHandler); MenuItemCompat.setOnActionExpandListener(searchItem, searchViewHandler); return true; } @Override protected void onResume() { super.onResume(); // mMainPresenter.setActivity(this); // Hacky. } @Override public void onPause() { super.onPause(); } public void closeMenuDrawer() { DrawerPresenter drawerPresenter = findPresenter(DrawerFragment.class); drawerPresenter.closeDrawer(); } /** * @param view View to animate * @param toVisibility Visibility at the end of animation * @param toAlpha Alpha at the end of animation * @param duration Animation duration in ms * Ref: http://stackoverflow.com/a/29542951 */ private void animateView(final View view, final int toVisibility, float toAlpha, int duration) { boolean show = (toVisibility == View.VISIBLE); if (show) { view.setAlpha(0); } view.setVisibility(View.VISIBLE); view.animate().setDuration(duration).alpha(show ? toAlpha : 0).setListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { view.setVisibility(toVisibility); } }); } public void showLoadingOverlay(String text) { mProgressOverlayText.setText(text); animateView(mProgressOverlayView, View.VISIBLE, 0.4f, 200); } public void hideLoadingOverlay() { animateView(mProgressOverlayView, View.GONE, 0, 200); } /** * The behaviour of the SearchView is as follows: * When the view is open, then the cross in the right hand side will only appear if there is * some text in the field. Clicking this cross will then clear the text but won't close (which * is called iconify in the SearchView code) the searchView. To iconify, must either click * back-press (after the keyboard is first hidden), or must click the left arrow in the top * left of the app bar. When either of these is done, then the onMenuItemActionCollapse * is called. * ref: http://stackoverflow.com/a/18186164 */ private class SearchViewHandler implements MenuItemCompat.OnActionExpandListener, SearchView.OnQueryTextListener, View.OnClickListener { private SearchListener mSearchListener; public SearchViewHandler(SearchListener searchListener) { mSearchListener = searchListener; } @Override public boolean onMenuItemActionCollapse(MenuItem item) { mSearchListener.onQueryClose(); return true; // Return true to collapse action view } @Override public boolean onMenuItemActionExpand(MenuItem item) { return true; // Return true to expand action view } @Override public void onClick(View v) { mSearchListener.onQueryClick(); } @Override public boolean onQueryTextSubmit(String query) { return true; } @Override public boolean onQueryTextChange(String newText) { mSearchListener.onQueryTextChange(newText); return true; } } public interface SearchListener { void onQueryClick(); void onQueryTextChange(String newText); void onQueryClose(); } }
34b5f243311596f699c10174bb71580a11e2fcd3
fe1ee5b914ffd6f227398ef9e339ec1d8067aba5
/src/AES.java
210d5ef8709163fa4c18127822ea6de3f55f6277
[]
no_license
anastasiakova/aes3
4e8efbe500b25d9fe3ec13353a8f9079e409381f
3ce9fabf27a74e27d8642c6aa6933773972f9205
refs/heads/master
2020-05-04T21:38:06.562729
2019-04-04T11:39:10
2019-04-04T11:39:10
179,483,268
0
0
null
null
null
null
UTF-8
Java
false
false
1,615
java
public class AES { private byte[][][] _keys; private RoundKey roundKey = new RoundKey(); private Shift shift = new Shift(); public byte[][][] encrypt(byte[][][] massege, byte[][][] keys) { this._keys = keys; byte[][][] encrypted = new byte[massege.length][massege[0].length][massege[0][0].length]; for (int blocksNumber = 0 ; blocksNumber < massege.length ; blocksNumber++){ encrypted[blocksNumber] = encryptBlock(massege[blocksNumber]); } return encrypted; } private byte[][] encryptBlock(byte[][] block) { System.out.println("newblock:"); byte[][] encryptedBlock = block; for (int key = 0 ; key < _keys.length ; key++){ encryptedBlock = roundKey.addRoundKey(shift.shift(encryptedBlock), _keys[key]); } return encryptedBlock; } public byte[][][] decrypt(byte[][][] cypher, byte[][][] keys) { this._keys = keys; byte[][][] decrypted = new byte[cypher.length][cypher[0].length][cypher[0][0].length]; for (int blocksNumber = 0 ; blocksNumber < cypher.length ; blocksNumber++){ decrypted[blocksNumber] = decryptBlock(cypher[blocksNumber]); } return decrypted; } private byte[][] decryptBlock(byte[][] block) { byte[][] decryptedBlock = block; for (int key = _keys.length - 1 ; key >= 0 ; key--){ decryptedBlock = shift.shift(shift.shift(shift.shift(roundKey.addRoundKey(block,_keys[key])))); } return decryptedBlock; } }
25103b8c18ed045d5225ecb8ffb55af8ea1ff47e
7f6edbbfeee027dca0e09e1edf10d98e66b7baf4
/src/bean/Enseignant.java
f5c1f195a0ac84901cdcca83ef5dfaa7dbe9aaef
[]
no_license
jihanesebbani/Gestion-Scolarit-FST-Settat
cb19fba9c939ab1cbba9a7858c5b3bb0cfdd3fa0
341cc9eb9e9e461011aef7d8e0f9142bc8a46c7c
refs/heads/master
2021-01-20T00:02:35.754530
2017-12-30T12:46:05
2017-12-30T12:46:05
89,070,676
1
0
null
null
null
null
UTF-8
Java
false
false
2,040
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package bean; import java.sql.Date; /** * * @author lenovo */ public class Enseignant { private int id; private String nom; private String prenom; private long tel; private String mail; private Departement departement; private Date dateFonction; private int statut;//1 enseignant principal 0 enseignant contractuel private Date fin; public Enseignant() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getNom() { return nom; } public void setNom(String nom) { this.nom = nom; } public String getPrenom() { return prenom; } public void setPrenom(String prenom) { this.prenom = prenom; } public long getTel() { return tel; } public void setTel(long tel) { this.tel = tel; } public String getMail() { return mail; } public void setMail(String mail) { this.mail = mail; } public Departement getDepartement() { if(departement==null){ departement=new Departement(); } return departement; } public void setDepartement(Departement departement) { this.departement = departement; } public Date getDateFonction() { return dateFonction; } public void setDateFonction(Date dateFonction) { this.dateFonction = dateFonction; } public int getStatut() { return statut; } public void setStatut(int statut) { this.statut = statut; } public Date getFin() { return fin; } public void setFin(Date fin) { this.fin = fin; } }
5f552c0d648b1553b7aa2677bbba1ed0265a6ef7
8769ce755fdf5a82ab79527d4fe5be28e67ab449
/ML/src/com/jivan/RemoveDup.java
36c9e31c43cd12b89f8d5cbc1c2fbf6f6e76dee5
[]
no_license
kcreddy/Machine-Learning
24976b2c3963470cc8f26ad226eba9d892eb345a
5e23ffecd984f72dcfcaeaf949b1debb819c5865
refs/heads/master
2021-01-21T13:52:44.624008
2016-05-24T01:51:44
2016-05-24T01:51:44
51,535,175
0
0
null
null
null
null
UTF-8
Java
false
false
2,123
java
package com.jivan; import java.util.*; public class RemoveDup{ public double calculate_Info_Gain(List<String> peArray_list,List<Integer> pe_freq_count,double mainEntropy, int listSize) { seperatePE(peArray_list); this.dataCleaning(peArray_list,pe_freq_count); int num_dis_ele=peArray_list.size(); double ele_p=0,ele_e=0,total=0; double first_term=0,second_term=0; // double info_gain_of_element=0; for(int element_num=0;element_num<num_dis_ele;element_num+=2) { ele_p=pe_freq_count.get(element_num); ele_e=pe_freq_count.get(element_num+1); total=ele_p+ele_e; first_term=-(ele_p/listSize)*(Math.log(ele_p/total))/Math.log(2); second_term=-(ele_e/listSize)*(Math.log(ele_e/total))/Math.log(2); mainEntropy=mainEntropy-(first_term+second_term); } return mainEntropy; } public void dataCleaning(List<String> pe_list_to_be_cleaned,List<Integer> corresponding_freq_count) { int currentPosition=0; while(currentPosition<pe_list_to_be_cleaned.size()){ if(Collections.frequency(pe_list_to_be_cleaned,pe_list_to_be_cleaned.get(currentPosition))==1) {pe_list_to_be_cleaned.remove(currentPosition); corresponding_freq_count.remove(currentPosition);} else{currentPosition+=2;} } //seperatePE(pe_list_to_be_cleaned); } public void seperatePE(List<String> list_arr) { String getLetter; for(int i=0;i<list_arr.size();i++) { getLetter= Character.toString(list_arr.get(i).charAt(0)); list_arr.remove(i); list_arr.add(i, getLetter);} } }
[ "cd" ]
cd
a739b12c04417fe18ce757890ff6b1f0e2cf9b76
16b2e5a479dad04c1cd8eb83fdf0fba4f2fc9357
/src/com/javarush/test/level08/lesson11/home05/Solution.java
d6697c3e99345d3072e238de827b47d6e78e1b61
[]
no_license
jtumano/JavaRushHomeWork
84823c5148b44f9e861a4f921f07618d0d26048c
b9ed19341d10eced119039ffb68cec9586118019
refs/heads/master
2021-01-14T08:25:42.390389
2017-01-15T16:41:26
2017-01-15T16:41:26
49,190,563
0
0
null
null
null
null
UTF-8
Java
false
false
1,501
java
package com.javarush.test.level08.lesson11.home05; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /* Мама Мыла Раму. Теперь с большой буквы Написать программу, которая вводит с клавиатуры строку текста. Программа заменяет в тексте первые буквы всех слов на заглавные. Вывести результат на экран. Пример ввода: мама мыла раму. Пример вывода: Мама Мыла Раму. */ public class Solution { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); String s = reader.readLine(); char [] charArray = s.toCharArray(); // стринг аррей в чар charArray[0] = Character.toUpperCase(charArray[0]); // символ в ячейке с индексом 0 получает метод заглавной буквы for (int i=0; i < charArray.length - 1; i++) { if (charArray[i] == ' ') // если встречаешь пробел, тогда charArray [i + 1] = Character.toUpperCase(charArray[i + 1]); // переходи в следующюю ячейку и делай ей апперКейс метод } System.out.println(charArray); } }
f89e813f01abd5684021849147842238d23d170e
84883652e38e3f2f4baf3fe5a9eb67bc223f4d1c
/app/src/main/java/edu/pitt/infsci2560/androidclient/Profile.java
d15f90625a8eb8d0d717aeeb91d33d8f50d8ab32
[]
no_license
infsci2560sp16/finalclass-androidclient
8096d6661aa99df983f73a22690666eebabda9cf
696c9e5ef941b4b2fc7e51025961ef35aff28bdd
refs/heads/master
2021-07-13T11:24:57.823244
2016-12-06T01:31:40
2016-12-06T01:31:40
56,731,987
0
0
null
null
null
null
UTF-8
Java
false
false
4,407
java
package edu.pitt.infsci2560.androidclient; import android.app.Activity; import android.app.Dialog; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.webkit.WebView; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class Profile extends Activity { SharedPreferences pref; String token, grav, oldpasstxt, newpasstxt; WebView web; Button chgpass, chgpassfr, cancel, logout; Dialog dlg; EditText oldpass, newpass; List<NameValuePair> params; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_profile); web = (WebView) findViewById(R.id.webView); chgpass = (Button) findViewById(R.id.chgbtn); logout = (Button) findViewById(R.id.logout); logout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SharedPreferences.Editor edit = pref.edit(); //Storing Data using SharedPreferences edit.putString("token", ""); edit.commit(); Intent loginactivity = new Intent(Profile.this, Login.class); startActivity(loginactivity); finish(); } }); pref = getSharedPreferences("AppPref", MODE_PRIVATE); token = pref.getString("token", ""); grav = "https:" + pref.getString("grav", ""); // note : probably need a better way to do this web.getSettings().setUseWideViewPort(true); web.getSettings().setLoadWithOverviewMode(true); web.loadUrl(grav); chgpass.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dlg = new Dialog(Profile.this); dlg.setContentView(R.layout.fragment_chg_password); dlg.setTitle("Change Password"); chgpassfr = (Button) dlg.findViewById(R.id.chgbtn); chgpassfr.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { oldpass = (EditText) dlg.findViewById(R.id.oldpass); newpass = (EditText) dlg.findViewById(R.id.newpass); oldpasstxt = oldpass.getText().toString(); newpasstxt = newpass.getText().toString(); params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("oldpass", oldpasstxt)); params.add(new BasicNameValuePair("newpass", newpasstxt)); params.add(new BasicNameValuePair("id", token)); ServerRequest sr = new ServerRequest(); JSONObject json = sr.getJSON(getString(R.string.server_url) + "api/chgpass", params); if (json != null) { try { String jsonstr = json.getString("response"); if (json.getBoolean("res")) { dlg.dismiss(); Toast.makeText(getApplication(), jsonstr, Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplication(), jsonstr, Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } } } }); cancel = (Button) dlg.findViewById(R.id.cancelbtn); cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { dlg.dismiss(); } }); dlg.show(); } }); } }
1c335846248388f832461a4516363f898a7714c4
6024fc9dbd51b273b6a6eeb2d7db3f8cc10fe0fb
/DoctorsOnDemandDevelopmentGradle/DoctorsOnDemandDevelopment/app/src/main/java/com/globussoft/readydoctors/patient/pediatrics_static_views/ScreeningTrainingPediatrics.java
201f1ef526e6d9cc8b87ecf96d2061a2784c9680
[]
no_license
devbose07/Doctors-on-Demand_Android
8b829378304a2f4604df37be66d8db415ee18d88
a296c6531f8408d91455d8567c86d35873287955
refs/heads/master
2021-01-21T16:27:53.324388
2016-02-29T11:58:50
2016-02-29T11:58:52
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,140
java
package com.globussoft.readydoctors.patient.pediatrics_static_views; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import com.globussoft.readydoctors.patient.R; /** * Created by GLB-276 on 10/15/2015. */ public class ScreeningTrainingPediatrics extends Activity { ImageView backImage; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.screening_training); initUI(); } public void initUI() { backImage=(ImageView)findViewById(R.id.backImage); backImage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); } @Override public void onBackPressed() { super.onBackPressed(); Intent intent = new Intent(getApplicationContext(),MeetTheDoctorsPediatrics.class); startActivity(intent); ScreeningTrainingPediatrics.this.finish(); } }
7be1251e198afdb60912218b8770d3fe63ca4097
149be5f4983156d0dde204d1473706530b337790
/lab/src/androidTest/java/com/tufusi/omphalos/ExampleInstrumentedTest.java
0647211b9938a56c62306ea864d1d3d4807fa767
[]
no_license
LeoCheung0221/Lab
97401741bf8dae0c7f6611145a2508a8791068ad
f757eb2868d36eaa6309361df33946c68182911f
refs/heads/master
2021-03-13T23:51:10.408852
2020-03-18T09:20:46
2020-03-18T09:20:46
246,721,702
1
0
null
null
null
null
UTF-8
Java
false
false
759
java
package com.tufusi.omphalos; import android.content.Context; import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); assertEquals("com.tufusi.omphalos.test", appContext.getPackageName()); } }
44194ddf8cbded681312b56d57a4d73177a59ac2
5a2b567e2a611cb55b16894957207d1cdb203593
/src/main/java/org/delphy/testredis/service/TestSmartCar.java
e010cb9599493601012035d06b33c310b89b011e
[]
no_license
mutouji/testredis
3375d4d543a87e5439137bcd8406c229296fd654
3f4ce895be30a1f44c256f9d412c74f6a373d73e
refs/heads/master
2020-03-19T02:02:56.386208
2018-06-01T08:21:35
2018-06-01T08:21:35
135,593,770
0
0
null
null
null
null
UTF-8
Java
false
false
1,078
java
package org.delphy.testredis.service; import org.aopalliance.intercept.MethodInterceptor; import org.springframework.aop.AfterReturningAdvice; import org.springframework.aop.MethodBeforeAdvice; import org.springframework.aop.ThrowsAdvice; import org.springframework.aop.framework.ProxyFactory; public class TestSmartCar { public static void main(String[] args) { ISmartCar car = new MySmartCar(); MethodBeforeAdvice adviceBefore = new BeforeAdviceDemo(); // like an interceptor AfterReturningAdvice adviceAfter = new BibiAdvice(); // like an after MethodInterceptor methodInterceptor = new AroundAdviceDemo(); ThrowsAdvice throwsAdvice = new ThrowsAdviceDemo(); ProxyFactory pf = new ProxyFactory(); pf.setTarget(car); pf.setInterfaces(car.getClass().getInterfaces()); pf.addAdvice(adviceAfter); pf.addAdvice(adviceBefore); pf.addAdvice(methodInterceptor); pf.addAdvice(throwsAdvice); ISmartCar proxy = (ISmartCar)pf.getProxy(); proxy.lock("duoduo"); } }
b373c577033bfbb4e5fe692e80526b3fef9dba9c
c78e8338af6575af291754da1f51e0bccd00521d
/dev-timeline-app-api/src/main/java/com/sky7th/devtimeline/api/comment/repository/CommentWebRepository.java
8c1ec217d5356206ac06ac615e377cd545267f4d
[]
no_license
sky7th/dev-timeline
0099153c440ae15dbebb1fa089c91b06e960d239
f46fc6cd37a9ef85fa61d42cdad3499466793e56
refs/heads/master
2023-04-08T23:55:49.860902
2021-04-19T16:33:28
2021-04-19T16:33:28
250,259,244
7
1
null
2020-11-25T06:47:49
2020-03-26T12:59:05
Java
UTF-8
Java
false
false
223
java
package com.sky7th.devtimeline.api.comment.repository; import com.sky7th.devtimeline.post.comment.domain.CommentRepository; public interface CommentWebRepository extends CommentRepository, CommentWebRepositoryCustom { }
eba286c65d91e6b96fc113a94fa24492052f9589
e6fc35c0d003250f89f71d8704b47d98067a56e3
/bts/graphics/Menu.java
c8dd4a8a1d7a7a3e6c68549756ea193248ca5629
[]
no_license
nguyenqkhoa/introWinterProject
8c631e0e4a487c7276fda92a165e7f64a179a1c0
3fc28a67ce618595072ce27c5764cbb52f3b8157
refs/heads/master
2023-08-04T12:09:11.508630
2021-09-22T19:46:11
2021-09-22T19:46:11
409,335,668
0
0
null
null
null
null
UTF-8
Java
false
false
2,964
java
package graphics; import data_container.Data; import javafx.geometry.Insets; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.RadioButton; import javafx.scene.control.TextField; import javafx.scene.control.ToggleGroup; import javafx.scene.layout.VBox; public class Menu extends VBox { private Data data = Data.getInstance(); private final Label modeLabel = new Label("Choose game mode:"); private final ToggleGroup group = new ToggleGroup(); private final RadioButton button1 = new RadioButton("PVP"); private final RadioButton button2 = new RadioButton("AI"); private final Label countLabel = new Label("Enter number of ships:"); private final String countText = "Number of ships"; private final TextField countTextField = new TextField(); private final TextField nameP1 = new TextField(); private final TextField nameP2 = new TextField(); private final Button exeMenu = new Button("Enter"); public Menu() { button1.setToggleGroup(group); button1.setSelected(true); button1.requestFocus(); button2.setToggleGroup(group); VBox modeScreen = new VBox(modeLabel, button1, button2); this.getChildren().add(modeScreen); modeScreen.setSpacing(10); modeScreen.setPadding(new Insets(10)); VBox nShipScreen = new VBox(countLabel, countTextField, exeMenu); countTextField.setMaxWidth(300); countTextField.setPromptText(countText); countTextField.setText(countText); this.getChildren().add(nShipScreen); nShipScreen.setSpacing(10); nShipScreen.setPadding(new Insets(10)); VBox nameScreen = new VBox(nameP1, nameP2); nameP1.setPromptText("Enter player 1's name"); nameP2.setPromptText("Enter player 2's name"); this.getChildren().add(nameScreen); nameScreen.setSpacing(10); nameScreen.setPadding(new Insets(10)); button1.setOnAction(e -> nameP2.setVisible(true)); button2.setOnAction(e -> nameP2.setVisible(false)); exeMenu.setOnAction(e -> { data.setNumShip(data.convert(countTextField.getText())); if (group.getSelectedToggle() == button1 && valid()) { data.getFirst().setName(nameP1.getText()); data.getSecond().setName(nameP2.getText()); data.setMode(1); switchScene(1); } else if (group.getSelectedToggle() == button2 && valid()) { data.getFirst().setName(nameP1.getText()); data.getSecond().setName("AI"); data.setMode(2); data.setAI(); switchScene(1); } else { countTextField.clear(); nameP1.clear(); nameP2.clear(); } }); } private boolean valid() { String name1 = nameP1.getText(); String name2 = nameP2.getText(); if (data.getNumShip()[0] <= 0 || data.getNumShip()[0] > 5 || name1.contains(",") || name2.contains(",") || name1.length() > 10 || name2.length() > 10) { return false; } else return true; } /** * method to switch scene, meant to be used by GameGUI * @param target scene to switch to */ public void switchScene(int target) { } }
ad5ac062dd61bb4e46849ff2be7abfd5f0d39696
afba1609f90a1e4efb5d58d1bd5213790e139b7d
/src/concordia/dems/client/CustomerClient.java
8be880eb02bda6fde076c02d7adfdf8dbf117f01
[]
no_license
MayankJariwala/comp6231-webservices
9e8c2edef77af41e586e513046ae16354a6fb4c6
3afc53a225626802f7caf8927dd7f8b6813ce882
refs/heads/master
2020-06-22T11:00:05.076083
2019-07-19T05:09:21
2019-07-19T05:09:21
197,703,120
0
0
null
null
null
null
UTF-8
Java
false
false
5,772
java
package concordia.dems.client; import concordia.dems.communication.IEventManagementCommunicationServer; import concordia.dems.helpers.*; import concordia.dems.model.WebServiceObjectFactory; import concordia.dems.model.enumeration.Servers; import javax.xml.namespace.QName; import javax.xml.ws.Service; import java.net.MalformedURLException; import java.net.URL; import java.util.Scanner; import java.util.concurrent.atomic.AtomicInteger; /** * @author Mayank Jariwala * @version 1.0.0 */ public class CustomerClient { private Scanner readInput = new Scanner(System.in); public static void main(String[] args) { System.out.println("Welcome to customer application :)"); CustomerClient customerClient = new CustomerClient(); customerClient.execute(); } private void execute() { String customerId; for (; ; ) { System.out.print("Enter your id : "); customerId = readInput.nextLine(); String from = Helper.getServerNameFromID(customerId); Servers server = Helper.getServerFromId(customerId); IEventManagementCommunicationServer communication = WebServiceObjectFactory.getInstance(server); String requestBody; try { listCustomerOperations(); System.out.print("Select operation id : "); int operationID = readInput.nextInt(); String operationName = ManagerAndClientInfo.clientOperations.get(operationID - 1); switch (operationName) { case EventOperation.BOOK_EVENT: requestBody = from + "," + this.bookEventInformation(customerId); String bookEventResponse = communication.performOperation(requestBody); System.out.println(bookEventResponse); Logger.writeLogToFile("client", customerId, requestBody, bookEventResponse, Constants.TIME_STAMP); break; case EventOperation.CANCEL_EVENT: requestBody = from + "," + this.cancelEventInformation(customerId); String cancelEventResponse = communication.performOperation(requestBody); System.out.println(cancelEventResponse); Logger.writeLogToFile("client", customerId, requestBody, cancelEventResponse, Constants.TIME_STAMP); break; case EventOperation.GET_BOOKING_SCHEDULE: requestBody = from + "," + from + "," + EventOperation.GET_BOOKING_SCHEDULE + "," + customerId; String bookingScheduleResponse = communication.performOperation(requestBody); System.out.println(bookingScheduleResponse); Logger.writeLogToFile("client", customerId, requestBody, bookingScheduleResponse, Constants.TIME_STAMP); break; case EventOperation.SWAP_EVENT: requestBody = from + "," + this.swapEvent(customerId); String swapEventResponse = communication.performOperation(requestBody); System.out.println(swapEventResponse); Logger.writeLogToFile("client", customerId, requestBody, swapEventResponse, Constants.TIME_STAMP); break; } readInput.nextLine(); } catch (Exception e) { e.printStackTrace(); System.out.println(e.getMessage()); } } } /** * Swap Event Function will allow user to swap the old event with new event * * @return String Request Body */ private String swapEvent(String customerID) { String requestBody = customerID; System.out.print("Enter NEW EVENT ID : "); requestBody += "," + readInput.next(); System.out.print("Enter NEW EVENT Type(SEMINAR/CONFERENCE/TRADESHOW) : "); requestBody += "," + readInput.next(); System.out.print("Enter OLD EVENT ID : "); requestBody += "," + readInput.next(); System.out.print("Enter OLD EVENT Type(SEMINAR/CONFERENCE/TRADESHOW) : "); requestBody += "," + readInput.next(); return " " + "," + EventOperation.SWAP_EVENT + "," + requestBody; } /** * Ask Certain Information While Booking an Event from User or Manager * * @return String : Request Body */ private String bookEventInformation(String customerID) { String requestBody = customerID; System.out.print("Enter EVENT ID : "); String eventID = readInput.next(); String to = Helper.getServerNameFromID(eventID); requestBody += "," + eventID; System.out.print("Enter EVENT Type(SEMINAR/CONFERENCE/TRADESHOW) : "); requestBody += "," + readInput.next(); return to + "," + EventOperation.BOOK_EVENT + "," + requestBody; } private String cancelEventInformation(String customerId) { String body = customerId; System.out.print("Enter Event ID : "); String eventID = readInput.next(); body += "," + eventID; String to = Helper.getServerNameFromID(eventID); return to + "," + EventOperation.CANCEL_EVENT + "," + body; } private void listCustomerOperations() { AtomicInteger idCounter = new AtomicInteger(1); System.out.println("Select number from below option for performing any operation"); ManagerAndClientInfo.clientOperations .forEach(clientId -> System.out.println(idCounter.getAndIncrement() + " " + clientId)); } }
9e2468c69a9866de64bac4dc5c2230197d419b00
cbb2d1e191f1c2ac7e42d1a26f357b3e1a52a41b
/tensquare_parent/tensquare_friend/src/main/java/com/tensquare/friend/interceptors/JwtInterceptor.java
cc4e5df28e8bf0620b2841ee857850b214d0f38e
[]
no_license
hxryy/tensquares
271ff9e70cb949c8e90e32e82b44b1335269d0c2
e7d9ff8b6ac69e22be06622a2b025ba5e3bc2a5f
refs/heads/master
2020-04-27T08:18:16.083420
2019-03-06T14:57:09
2019-03-06T14:57:17
174,165,584
2
0
null
null
null
null
UTF-8
Java
false
false
2,112
java
package com.tensquare.friend.interceptors; import io.jsonwebtoken.Claims; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import util.JwtUtil; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 自定义拦截器,用于判断是否有权限(包含管理员和用户) * @author 黑马程序员 * @Company http://www.ithiema.com */ @Component public class JwtInterceptor extends HandlerInterceptorAdapter { @Autowired private JwtUtil jwtUtil; /** * 在控制器方法执行之前,先执行 * @param request * @param response * @param handler * @return 当返回值是true的时候表示放行。false表示不放行 * @throws Exception */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { //1.获取请求消息头 String header = request.getHeader("Authorization"); //2.判断是否有此消息头,同时还要判断是否以Bearer开头 if(!StringUtils.isEmpty(header) && header.startsWith("Bearer ")){ //3.获取token String token = header.split(" ")[1]; //4.解析token Claims claims = jwtUtil.parseJWT(token); //5.如果claims不为null的话,验证是管理员还是用户 if(claims != null){ String roles = (String)claims.get("roles"); if("admin_role".equals(roles)){ //管理员 request.setAttribute("admin_claims",claims); }else if("user_role".equals(roles)){ //普通用户 request.setAttribute("user_claims",claims); }else { //其他权限 } } } return true;//拦截器无论什么情况都放行 } }
4b71db9aa67747c7363e259862339114c342f787
7a497a8372818e251ec7df4bdc4fa202cbd77875
/ch24/APKClient/src/mobile/android/apk/client/APKClientActivity.java
85371a4ca4f56f7adcb52fcc59332ab93d6de590
[]
no_license
solotic/android_definitive_guide
dc6fafd5708671a6ec7b0b36a1928f42ca7f8cd8
4077d6851de1e0eb9dea1a5162b8b18b592ce3a0
refs/heads/master
2021-06-02T03:22:48.398109
2016-07-18T14:32:58
2016-07-18T14:32:58
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,280
java
package mobile.android.apk.client; import java.lang.reflect.Method; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.os.Bundle; import android.os.Environment; import android.view.View; import android.widget.Toast; import dalvik.system.DexClassLoader; public class APKClientActivity extends Activity { private DexClassLoader mDexClassLoader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_apkclient); String optimizedDirectory = Environment.getDataDirectory().toString() + "/data/" + getPackageName(); mDexClassLoader = new DexClassLoader("/sdcard/APKLibrary.apk", optimizedDirectory, null, ClassLoader.getSystemClassLoader()); } public void onClick_InvokeGetName(View view) { try { Class c = mDexClassLoader .loadClass("mobile.android.apk.library.MyClass"); Object obj = c.newInstance(); Method method = obj.getClass().getMethod("getName", null); String name = String.valueOf(method.invoke(obj, null)); Toast.makeText(this, name, Toast.LENGTH_LONG).show(); } catch (Exception e) { Toast.makeText(this, "error:" + e.getMessage(), Toast.LENGTH_LONG) .show(); } } }
16b8fdcec9518b4c688e064320fb263a778dd1f6
18cbe14187097d9009abcead2203231aeff880d7
/src/com/cats/adapter/CatsFragmentPagerAdapter.java
57b5660866684f5a75f8f219153627987a33e13a
[]
no_license
imsuu/Cats
fec2785c9d9136c4ad50732c78dfc90dc4c57422
f67ba86473b513a00e9235b65f49fa5c7dd400df
refs/heads/master
2021-09-10T05:40:28.332103
2018-03-21T06:36:10
2018-03-21T06:36:10
103,220,615
1
0
null
null
null
null
UTF-8
Java
false
false
810
java
package com.cats.adapter; import java.util.List; import com.cats.weights.baseWeights.BaseFragment; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; public class CatsFragmentPagerAdapter extends FragmentPagerAdapter{ private List<BaseFragment> fragments; public CatsFragmentPagerAdapter(FragmentManager manager,List<BaseFragment> fragments) { super(manager); this.fragments = fragments; } @Override public Fragment getItem(int position) { if(fragments != null) return fragments.get(position); return null; } @Override public int getCount() { if(fragments != null) return fragments.size(); return 0; } @Override public int getItemPosition(Object object) { return POSITION_NONE; } }
7219cdea187fe0e2bf5dae8a741cb85ebb2a3f5b
b31120cefe3991a960833a21ed54d4e10770bc53
/modules/org.llvm.ir/extra_members/brc_matchExtraMembers.java
a9e95b2bcd2db5bc4c89b5684e03914a5f578ecf
[]
no_license
JianpingZeng/clank
94581710bd89caffcdba6ecb502e4fdb0098caaa
bcdf3389cd57185995f9ee9c101a4dfd97145442
refs/heads/master
2020-11-30T05:36:06.401287
2017-10-26T14:15:27
2017-10-26T14:15:27
null
0
0
null
null
null
null
UTF-8
Java
false
false
223
java
public brc_match(brc_match<Cond_t> other) { this.Cond = /*ParenListExpr*/$Clone(other.Cond); this./*&*/T=/*&*/other.T; this./*&*/F=/*&*/other.T; } @Override public brc_match clone() { return new brc_match(this); }
8427f92591fdef5961dca3d905edc24c022ca8b9
5945f6454415ca83b51f97673d1abef3ce77a6b9
/framework/src/main/java/org/openo/client/cli/fw/error/OpenOCommandNotFound.java
2d88cf52666a059279adc03a53e07b5b615bab20
[]
no_license
open-o/client-cli
55ba44037e81c15674923e3a12937bd8343a0feb
3e6e2dfba7de53902cd096e5ef2f0a4feb195877
refs/heads/master
2021-01-19T11:29:27.593318
2017-04-27T09:11:04
2017-04-27T09:11:04
87,971,723
0
0
null
null
null
null
UTF-8
Java
false
false
976
java
/* * Copyright 2017 Huawei Technologies Co., Ltd. * * 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.openo.client.cli.fw.error; /** * Command not registered in CLI registrar. * */ public class OpenOCommandNotFound extends OpenOCommandException { private static final long serialVersionUID = 6676137916079057963L; public OpenOCommandNotFound(String cmdName) { super("0x0011", "Command " + cmdName + " is not registered"); } }
a702f0c48cc8be03a4908a452614f3e28e066a27
7f08e9725b0bf32c5e88075f31928455cacbc02f
/src/com/bhanu/dataclass/DataClass.java
107c736b64d07818e0587ae1644e63a45e36fe2f
[]
no_license
bhanu1306/Server-using-Java
2bc2292f17b01ff6eb4b3f9fa9a61e421225cd1c
cac0526225cc89c38954cca8f34b0bb701c657b4
refs/heads/master
2021-01-15T14:50:06.022340
2017-08-08T14:09:37
2017-08-08T14:09:37
99,695,436
0
0
null
null
null
null
UTF-8
Java
false
false
339
java
package com.bhanu.dataclass; import java.io.Serializable; public class DataClass implements Serializable { /** * DataClass for transferring the data between the application and the server */ private static final long serialVersionUID = -6630029850977740840L; public String Name; public String Address; public String Problem; }
5e4e300d9aa0b4f60426972704b9a6a7cd409404
7aaf2a0287672bf70d7a1c39663e47e0b3b2809e
/code/ComputeFibonacci.java
a56aa2b6a1ca87bb43cbe3f9a6fee256f895f2b7
[]
no_license
leungyukshing/javacode
e4cdb234618e8d9c0bb1571045fe35d3539de38c
f5a6bb0f32c6bd3feea2120f122858996906faf5
refs/heads/master
2021-06-25T09:03:59.952921
2017-09-08T02:28:30
2017-09-08T02:28:30
102,364,303
0
0
null
null
null
null
UTF-8
Java
false
false
652
java
import java.util.Scanner; public class ComputeFibonacci { public static void main(String[] args) { // Create a Scanner Scanner input = new Scanner(System.in); System.out.print("Enter an index for the Fibonacci number: "); int index = input.nextInt(); // Find and display the Fibonacci number System.out.println("Fibonacci number at index " + index + " is " + fib(index)); } // The method for finding the Fibonacci number public static long fib(long index) { if(index == 0) // Base case return 0; else if(index == 1) // Base return 1; else // Reduction and recursive calls return fib(index - 1) + fib(index - 2); } }
0327f6796e0da60301b1041c6a14eb16effbc525
5fe4fb5631d93a9972568d883bfb6344f32d59b0
/src/ch05homework/ArrayCreateByValueListExample2.java
896226721626ee4fed2649a91da173f32223d0ff
[]
no_license
angelatto/Java_Study
d95ee4f5a38faeefc7648d1a431c3addf88a5653
ac938f116b8b4dc6101b7bdc891df0d8f5096b8f
refs/heads/main
2023-03-18T14:43:44.476294
2021-03-07T13:14:52
2021-03-07T13:14:52
339,274,549
0
0
null
null
null
null
ISO-8859-6
Java
false
false
559
java
package ch05homework; public class ArrayCreateByValueListExample2 { public static void main(String[] args) { int[] scores; scores = new int[] {83, 90, 87}; int sum1 = 0; for(int i=0; i<3; i++) { sum1 += scores[i]; } System.out.println("أراص : " + sum1); int sum2 = add(new int[] {83,90,87}); System.out.println("أراص : " + sum2); System.out.println(); } public static int add(int[] scores) { int sum = 0; for(int i=0; i<3; i++) { sum += scores[i]; } return sum; } }
83b3724ae91877fe6b66729d3d2ecd9dd3cebb77
7a81815f7f50e29a1ddb7c0edd44cc0c0ea11086
/src/main/java/mx/edu/utez/sad/repository/UserRepository.java
7852d9bc47df75310eaedc6dfcfc5fccc3cc5338
[]
no_license
carlosarce10/dulceria-back
3a57b6496f77baa0c32380960a3d976cfb2b7d36
838e7683701259680c69508a7066023e0680bb9d
refs/heads/main
2023-04-04T16:08:33.770726
2021-04-20T18:21:17
2021-04-20T18:21:17
359,911,765
0
0
null
null
null
null
UTF-8
Java
false
false
698
java
package mx.edu.utez.sad.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import mx.edu.utez.sad.entity.RoleEntity; import mx.edu.utez.sad.entity.UserEntity; @Repository public interface UserRepository extends JpaRepository<UserEntity, Long>{ public List<UserEntity> findByStatusOrderByIdDesc(boolean status); public List<UserEntity> findByStatusAndRoleOrderByIdDesc(boolean status, RoleEntity role); public UserEntity findByUsernameOrderByIdDesc(String username); public boolean existsByUsernameOrderByIdDesc(String username); public List<UserEntity> findAllByOrderByIdDesc(); }
a45bb90780f98a90ddf3e5699d4ad3acf4423966
7b45b9daa4b2a4da847371ceb988b874df5c2192
/workspace/helloworld/HelloSqlAzure/src/hellosqlazure/SqlAzure.java
8dc0e03ddd7756f308585bbd42250091ccae2488
[]
no_license
DRavnaas/CS5200
60cf6946298143775312250f8dcf5c4ea508a410
4ec8018944fff90530c5d7093a0193d21448cca3
refs/heads/master
2016-09-06T15:23:27.857411
2014-12-18T06:22:34
2014-12-18T06:23:44
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,404
java
package hellosqlazure; import java.sql.*; // http://azure.microsoft.com/en-us/documentation/articles/sql-data-java-how-to-use-sql-database/#use_sql_azure_in_java public class SqlAzure { // Add ctor with server, database, user and password private static String connectionString = "jdbc:sqlserver://ovong4chs8.database.windows.net:1433" + ";" + "database=?" + ";" + "user=?@ovong4chs8" + ";" + "password=?" + ";" + "encrypt=true" + ";" + "hostnameincertificate=*.database.windows.net" + ";" + "logintimeout=30" + ";" ; public static String GetMessageFromDb() { String message = "could not make connection"; // The types for the following variables are // defined in the java.sql library. Connection connection = null; // For making the connection Statement statement = null; // For the SQL statement ResultSet resultSet = null; // For the result set, if applicable try { // Ensure the SQL Server driver class is available. Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); // Establish the connection. connection = DriverManager.getConnection(connectionString); // Define the SQL string. String sqlString = "SELECT TOP 1 * FROM Person"; // Use the connection to create the SQL statement. statement = connection.createStatement(); // Execute the statement. resultSet = statement.executeQuery(sqlString); resultSet.next(); message = resultSet.getString("FirstName"); } // Exception handling catch (ClassNotFoundException cnfe) { System.out.println("ClassNotFoundException " + cnfe.getMessage()); } catch (Exception e) { System.out.println("Exception " + e.getMessage()); e.printStackTrace(); } finally { try { // Close resources. if (null != connection) connection.close(); if (null != statement) statement.close(); if (null != resultSet) resultSet.close(); } catch (SQLException sqlException) { // No additional action if close() statements fail. } } return message; } }
7a785a307476d84774169aad66e612cf42014e16
dbeee684cc48e11b2a9295b5d12a0ce0e471db7d
/java0228/src/java0228/FormatStringMain.java
2f0870f0b915013f591ca04140ec2602f20fdaac
[]
no_license
seonwoojin813/java0211-0321
dcf0b5fb0ceb7202291ae04f40524a6c6428d603
d8105c1343e03726134dbae31e2beb6a945cf15d
refs/heads/master
2020-04-25T21:27:02.727225
2019-05-07T09:40:22
2019-05-07T09:40:22
null
0
0
null
null
null
null
UHC
Java
false
false
1,976
java
package java0228; import java.text.ChoiceFormat; import java.text.DecimalFormat; import java.text.MessageFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class FormatStringMain { public static void main(String[] args) { //Calendar 인스턴스를 이용한 Date 인스턴스 생성 Calendar cal = Calendar.getInstance(); Date today = new Date(cal.getTimeInMillis()); //날짜서식을 생성 SimpleDateFormat sdf = new SimpleDateFormat("G YYYY-MM-dd hh:mm:ss (EEEE)"); //날짜를 문자열로 변환 String formatString = sdf.format(today); System.out.printf("%s\n", formatString); double number = 67821.78549; //위의 숫자는 \67,821.79로 출력하기 //숫자 서식을 설정 DecimalFormat df = new DecimalFormat("\u00A4 #,###.00"); formatString =df.format(number); System.out.printf("%s\n", formatString); //ChoiceFormat은 실수 배열과 문자열 배열을 이용해서 생성 //살수 배열 만의 숫자 범위에 해당하는 문자열을 리턴하는 클래스 double [] score = {0,60,70,80,90}; String [] grade = {"가", "양", "미", "우", "수"}; double [ ] jumsu = {98,87,26,56,99,76,87}; //ChoiceFormat 인스턴스 생성 ChoiceFormat cf = new ChoiceFormat(score, grade); for(double temp : jumsu) { System.out.printf("%s\n", cf.format(temp)); } //포맷 문자열 생성 String msg = "이름:{0} 나이:{1}"; Object [] p1 = {"선우진", "26"}; Object [] p2 = {"최은정", "27"}; System.out.printf("%s\n", MessageFormat.format(msg, p1)); System.out.printf("%s\n", MessageFormat.format(msg, p2)); } }
[ "503_08@DESKTOP-7RBI65N" ]
503_08@DESKTOP-7RBI65N
85518f88ce5ab4e1f6c79ba85129b54f2a961e35
0039dc07de2e539748e40db7b060367f0f2a3d99
/CreditAnalytics/2.1/src/org/drip/param/definition/Quote.java
cfdc360520240b758d40783f58488c31f98eea41
[ "Apache-2.0" ]
permissive
tech2bg/creditanalytics
a4318518e42a557ffb3396be9350a367d3a208b3
b24196a76f98b1c104f251d74ac22a213ae920cf
refs/heads/master
2020-04-05T23:46:29.529999
2015-05-07T01:40:52
2015-05-07T01:40:52
35,299,804
0
1
null
null
null
null
UTF-8
Java
false
false
2,455
java
package org.drip.param.definition; /* * -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /*! * Copyright (C) 2013 Lakshmi Krishnamurthy * Copyright (C) 2012 Lakshmi Krishnamurthy * Copyright (C) 2011 Lakshmi Krishnamurthy * * This file is part of CreditAnalytics, a free-software/open-source library for fixed income analysts and * developers - http://www.credit-trader.org * * CreditAnalytics is a free, full featured, fixed income credit analytics library, developed with a special * focus towards the needs of the bonds and credit products community. * * 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. */ /** * This interface contains the stubs corresponding to a product quote. It contains the quote value, quote * instant for the different quote sides (bid/ask/mid). * * @author Lakshmi Krishnamurthy */ public abstract class Quote extends org.drip.service.stream.Serializer { /** * Get the quote value for the given side * * @param strSide bid/ask/mid * * @return Quote Value */ public abstract double getQuote ( final java.lang.String strSide); /** * Get the quote size for the given side * * @param strSide bid/ask/mid * * @return Size */ public abstract double getSize ( final java.lang.String strSide); /** * Get the time of the quote * * @param strSide bid/ask/mid * * @return DateTime */ public abstract org.drip.analytics.date.DateTime getQuoteTime ( final java.lang.String strSide); /** * Set the quote for the specified side * * @param strSide bid/ask/mid * @param dblQuote Quote value * @param dblSize Size * * @return Success (true) or failure (false) */ public abstract boolean setSide ( final java.lang.String strSide, final double dblQuote, final double dblSize); }
[ "OpenCredit@DRIP" ]
OpenCredit@DRIP
5ef230109ddf9e8d17ea59f0cd3cf96f215aaebc
c6c5e85e41ff2f2f105616f9bbe55b9ed807fee7
/JavaSource/org/unitime/timetable/events/ListAcademicSessions.java
bb2f7f7fbd5ed0b876964e1cd933fe57def6a6f0
[ "BSD-3-Clause", "EPL-1.0", "CC-BY-3.0", "LGPL-3.0-only", "LGPL-2.1-only", "LicenseRef-scancode-freemarker", "LicenseRef-scancode-warranty-disclaimer", "CDDL-1.0", "MIT", "Apache-2.0", "LicenseRef-scancode-public-domain", "LGPL-2.1-or-later", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-free-unknown", "LicenseRef-scancode-unknown-license-reference" ]
permissive
apetro/unitime
60616c21a5caaeb11ec1f839a30aca910ed8f9de
0c8e78fe85b1296de03d4eabe4fbf8c7eb2e8493
refs/heads/master
2023-04-07T06:34:57.713178
2017-06-29T15:46:18
2017-06-29T15:46:18
95,915,875
0
0
Apache-2.0
2023-04-04T00:41:58
2017-06-30T18:57:36
Java
UTF-8
Java
false
false
8,902
java
/* * Licensed to The Apereo Foundation under one or more contributor license * agreements. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. * * The Apereo Foundation licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. * */ package org.unitime.timetable.events; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.TreeSet; import org.unitime.localization.impl.Localization; import org.unitime.timetable.defaults.ApplicationProperty; import org.unitime.timetable.gwt.client.events.AcademicSessionSelectionBox; import org.unitime.timetable.gwt.client.events.AcademicSessionSelectionBox.AcademicSession; import org.unitime.timetable.gwt.command.client.GwtRpcException; import org.unitime.timetable.gwt.command.client.GwtRpcResponseList; import org.unitime.timetable.gwt.command.server.GwtRpcImplementation; import org.unitime.timetable.gwt.command.server.GwtRpcImplements; import org.unitime.timetable.gwt.resources.GwtConstants; import org.unitime.timetable.gwt.resources.GwtMessages; import org.unitime.timetable.model.Session; import org.unitime.timetable.model.dao.SessionDAO; import org.unitime.timetable.security.SessionContext; import org.unitime.timetable.security.context.UniTimeUserContext; import org.unitime.timetable.security.qualifiers.SimpleQualifier; import org.unitime.timetable.security.rights.Right; import org.unitime.timetable.util.Formats; /** * @author Tomas Muller */ @GwtRpcImplements(AcademicSessionSelectionBox.ListAcademicSessions.class) public class ListAcademicSessions implements GwtRpcImplementation<AcademicSessionSelectionBox.ListAcademicSessions, GwtRpcResponseList<AcademicSession>>{ protected static GwtMessages MESSAGES = Localization.create(GwtMessages.class); protected static GwtConstants CONSTANTS = Localization.create(GwtConstants.class); @Override public GwtRpcResponseList<AcademicSession> execute(AcademicSessionSelectionBox.ListAcademicSessions command, SessionContext context) { Formats.Format<Date> df = Formats.getDateFormat(Formats.Pattern.DATE_EVENT); org.hibernate.Session hibSession = SessionDAO.getInstance().getSession(); Session selected = null; if (command.hasTerm()) { try { selected = findSession(hibSession, command.getTerm()); } catch (GwtRpcException e) {} } else { Long sessionId = (context.isAuthenticated() && context.getUser().getCurrentAuthority() != null ? context.getUser().getCurrentAcademicSessionId() : null); if (sessionId != null) selected = SessionDAO.getInstance().get(sessionId, hibSession); } if (selected == null) try { selected = findSession(hibSession, "current"); } catch (GwtRpcException e) {} Right permission = Right.Events; if (command.hasSource()) permission = Right.valueOf(command.getSource()); TreeSet<Session> sessions = new TreeSet<Session>(); if (ApplicationProperty.ListSessionsReverse.isTrue()) { sessions = new TreeSet<Session>(new Comparator<Session>() { @Override public int compare(Session s1, Session s2) { int cmp = s1.getAcademicInitiative().compareTo(s2.getAcademicInitiative()); if (cmp!=0) return cmp; cmp = s2.getSessionBeginDateTime().compareTo(s1.getSessionBeginDateTime()); if (cmp!=0) return cmp; return s1.getUniqueId().compareTo(s2.getUniqueId()); } }); } for (Session session: (List<Session>)hibSession.createQuery("select s from Session s").list()) { if (session.getStatusType() == null || session.getStatusType().isTestSession()) continue; if (!context.hasPermissionAnyAuthority(permission, new SimpleQualifier("Session", session.getUniqueId()))) continue; sessions.add(session); } if (sessions.isEmpty()) throw new GwtRpcException(MESSAGES.noSessionAvailable()); if (selected == null || !sessions.contains(selected)) selected = UniTimeUserContext.defaultSession(sessions, null); if (selected == null) selected = sessions.last(); if (!command.hasTerm() && !context.hasPermissionAnyAuthority(selected, Right.EventAddSpecial)) { TreeSet<Session> preferred = new TreeSet<Session>(); for (Session session: sessions) if (context.hasPermissionAnyAuthority(session, Right.EventAddSpecial, new SimpleQualifier("Session", session.getUniqueId()))) preferred.add(session); else if (context.hasPermissionAnyAuthority(session, Right.EventAddCourseRelated, new SimpleQualifier("Session", session.getUniqueId()))) preferred.add(session); else if (context.hasPermissionAnyAuthority(session, Right.EventAddUnavailable, new SimpleQualifier("Session", session.getUniqueId()))) preferred.add(session); if (!preferred.isEmpty()) { Session defaultSession = UniTimeUserContext.defaultSession(preferred, null); if (defaultSession != null) selected = defaultSession; } } GwtRpcResponseList<AcademicSession> ret = new GwtRpcResponseList<AcademicSession>(); for (Session session: sessions) { AcademicSession acadSession = new AcademicSession( session.getUniqueId(), session.getLabel(), session.getAcademicTerm() + session.getAcademicYear() + session.getAcademicInitiative(), df.format(session.getEventBeginDate()) + " - " + df.format(session.getEventEndDate()), session.equals(selected)); if (session.canNoRoleReportClass()) acadSession.set(AcademicSession.Flag.HasClasses); if (session.canNoRoleReportExamFinal()) acadSession.set(AcademicSession.Flag.HasFinalExams); if (session.canNoRoleReportExamMidterm()) acadSession.set(AcademicSession.Flag.HasMidtermExams); if (context.hasPermissionAnyAuthority(session, Right.Events, new SimpleQualifier("Session", session.getUniqueId()))) acadSession.set(AcademicSession.Flag.HasEvents); if (context.hasPermissionAnyAuthority(session, Right.EventAddSpecial, new SimpleQualifier("Session", session.getUniqueId()))) acadSession.set(AcademicSession.Flag.CanAddEvents); else if (context.hasPermissionAnyAuthority(session, Right.EventAddCourseRelated, new SimpleQualifier("Session", session.getUniqueId()))) acadSession.set(AcademicSession.Flag.CanAddEvents); else if (context.hasPermissionAnyAuthority(session, Right.EventAddUnavailable, new SimpleQualifier("Session", session.getUniqueId()))) acadSession.set(AcademicSession.Flag.CanAddEvents); Session prev = null, next = null; for (Session s: sessions) { if (s.getUniqueId().equals(session.getUniqueId()) || !s.getAcademicInitiative().equals(session.getAcademicInitiative())) continue; if (s.getSessionEndDateTime().before(session.getSessionBeginDateTime())) { // before if (prev == null || prev.getSessionBeginDateTime().before(s.getSessionBeginDateTime())) { prev = s; } } else if (s.getSessionBeginDateTime().after(session.getSessionEndDateTime())) { // after if (next == null || next.getSessionBeginDateTime().after(s.getSessionBeginDateTime())) { next = s; } } } if (next != null) acadSession.setNextId(next.getUniqueId()); if (prev != null) acadSession.setPreviousId(prev.getUniqueId()); ret.add(acadSession); } return ret; } public static Session findSession(org.hibernate.Session hibSession, String term) { try { Session ret = SessionDAO.getInstance().get(Long.parseLong(term), hibSession); if (ret != null) return ret; } catch (NumberFormatException e) {} List<Session> sessions = hibSession.createQuery("select s from Session s where " + "s.academicTerm || s.academicYear = :term or " + "s.academicTerm || s.academicYear || s.academicInitiative = :term"). setString("term", term).list(); if (!sessions.isEmpty()) { for (Session session: sessions) { if (session.getStatusType() == null || session.getStatusType().isTestSession()) continue; return session; } } if ("current".equalsIgnoreCase(term)) { sessions = hibSession.createQuery("select s from Session s where " + "s.eventBeginDate <= :today and s.eventEndDate >= :today"). setDate("today",new Date()).list(); if (!sessions.isEmpty()) { for (Session session: sessions) { if (session.getStatusType() == null || session.getStatusType().isTestSession()) continue; return session; } } } throw new GwtRpcException("Academic session " + term + " not found."); } }
8906d67f490661b1ea4342a88d2399f3f98608d7
fa91450deb625cda070e82d5c31770be5ca1dec6
/Diff-Raw-Data/22/22_ccffaa31740213b9e6edad2475d7a18153d0cc05/SGLR/22_ccffaa31740213b9e6edad2475d7a18153d0cc05_SGLR_t.java
1f4c33d1ec6acb7780f5e710bba22261e43f49c5
[]
no_license
zhongxingyu/Seer
48e7e5197624d7afa94d23f849f8ea2075bcaec0
c11a3109fdfca9be337e509ecb2c085b60076213
refs/heads/master
2023-07-06T12:48:55.516692
2023-06-22T07:55:56
2023-06-22T07:55:56
259,613,157
6
2
null
2023-06-22T07:55:57
2020-04-28T11:07:49
null
UTF-8
Java
false
false
33,712
java
/* * Created on 03.des.2005 * * Copyright (c) 2005, Karl Trygve Kalleberg <karltk near strategoxt.org> * * Licensed under the GNU Lesser General Public License, v2.1 */ package org.spoofax.jsglr.client; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.List; import java.util.Queue; import java.util.Set; import org.spoofax.PushbackStringIterator; import org.spoofax.interpreter.terms.ITermFactory; import org.spoofax.jsglr.shared.ArrayDeque; import org.spoofax.jsglr.shared.BadTokenException; import org.spoofax.jsglr.shared.SGLRException; import org.spoofax.jsglr.shared.TokenExpectedException; import org.spoofax.jsglr.shared.Tools; public class SGLR { private RecoveryPerformance performanceMeasuring; private final Set<BadTokenException> collectedErrors = new LinkedHashSet<BadTokenException>(); public static final int EOF = ParseTable.NUM_CHARS; static final int TAB_SIZE = 4;//8; protected static boolean WORK_AROUND_MULTIPLE_LOOKAHEAD; //Performance testing private static long parseTime=0; private static int parseCount=0; protected Frame startFrame; private long startTime; protected volatile boolean asyncAborted; protected Frame acceptingStack; protected final ArrayDeque<Frame> activeStacks; private ParseTable parseTable; protected int currentToken; protected int tokensSeen; protected int lineNumber; protected int columnNumber; private int startOffset; private final ArrayDeque<ActionState> forShifter; private ArrayDeque<Frame> forActor; private ArrayDeque<Frame> forActorDelayed; private int maxBranches; private int maxToken; private int maxLine; private int maxColumn; private int maxTokenNumber; private AmbiguityManager ambiguityManager; protected Disambiguator disambiguator; private int rejectCount; private int reductionCount; protected PushbackStringIterator currentInputStream; private PathListPool pathCache = PathListPool.getInstance(); private ArrayDeque<Frame> activeStacksWorkQueue = new ArrayDeque<Frame>(); private ArrayDeque<Frame> recoverStacks; private ParserHistory history; private RecoveryConnector recoverIntegrator; private ITreeBuilder treeBuilder; protected boolean useIntegratedRecovery; public ParserHistory getHistory() { return history; } private boolean fineGrainedOnRegion; protected ArrayDeque<Frame> getRecoverStacks() { return recoverStacks; } public Set<BadTokenException> getCollectedErrors() { return collectedErrors; } /** * Attempts to set a timeout for parsing. * Default implementation throws an * {@link UnsupportedOperationException}. * * @see org.spoofax.jsglr.io.SGLR#setTimeout(int) */ public void setTimeout(int timeout) { throw new UnsupportedOperationException("Use org.spoofax.jsglr.io.SGLR for setting a timeout"); } protected void initParseTimer() { // Default does nothing (not supported by GWT) } @Deprecated public SGLR(ITermFactory pf, ParseTable parseTable) { this(new Asfix2TreeBuilder(pf), parseTable); } @Deprecated public SGLR(ParseTable parseTable) { this(new Asfix2TreeBuilder(), parseTable); } public SGLR(ITreeBuilder treeBuilder, ParseTable parseTable) { assert parseTable != null; // Init with a new factory for both serialized or BAF instances. this.parseTable = parseTable; activeStacks = new ArrayDeque<Frame>(); forActor = new ArrayDeque<Frame>(); forActorDelayed = new ArrayDeque<Frame>(); forShifter = new ArrayDeque<ActionState>(); disambiguator = new Disambiguator(); useIntegratedRecovery = false; recoverIntegrator = null; history = new ParserHistory(); setTreeBuilder(treeBuilder); } public void setUseStructureRecovery(boolean useRecovery, IRecoveryParser parser) { useIntegratedRecovery = useRecovery; recoverIntegrator = new RecoveryConnector(this, parser); } /** * Enables error recovery based on region recovery and, if available, recovery rules. * Does not enable bridge parsing. * * @see ParseTable#hasRecovers() Determines if the parse table supports recovery rules */ public final void setUseStructureRecovery(boolean useRecovery) { setUseStructureRecovery(useRecovery, null); } protected void setFineGrainedOnRegion(boolean fineGrainedMode) { fineGrainedOnRegion = fineGrainedMode; recoverStacks = new ArrayDeque<Frame>(); } @Deprecated protected void setUseFineGrained(boolean useFG) { recoverIntegrator.setUseFineGrained(useFG); } // FIXME: we have way to many of these accessors; does this have to be public? // if not for normal use, it should at least be 'internalSet....' @Deprecated public void setCombinedRecovery(boolean useBP, boolean useFG, boolean useOnlyFG) { recoverIntegrator.setOnlyFineGrained(useOnlyFG); recoverIntegrator.setUseBridgeParser(useBP); recoverIntegrator.setUseFineGrained(useFG); } public RecoveryPerformance getPerformanceMeasuring() { return performanceMeasuring; } /** * @deprecated Use {@link #asyncCancel()} instead. */ @Deprecated public void asyncAbort() { asyncCancel(); } /** * Aborts an asynchronously running parse job, causing it to throw an exception. * * (Provides no guarantee that the parser is actually cancelled.) */ public void asyncCancel() { asyncAborted = true; } public void asyncCancelReset() { asyncAborted = false; } @Deprecated public static boolean isDebugging() { return Tools.debugging; } public static boolean isLogging() { return Tools.logging; } /** * Initializes the active stacks. At the start of parsing there is only one * active stack, and this stack contains the start symbol obtained from the * parse table. * * @return top-level frame of the initial stack */ private Frame initActiveStacks() { activeStacks.clear(); final Frame st0 = newStack(parseTable.getInitialState()); addStack(st0); return st0; } @Deprecated public Object parse(String input) throws BadTokenException, TokenExpectedException, ParseException, SGLRException { return parse(input, null, null); } @Deprecated public final Object parse(String input, String filename) throws BadTokenException, TokenExpectedException, ParseException, SGLRException { return parse(input, filename, null); } /** * Parses a string and constructs a new tree using the tree builder. * * @param input The input string. * @param filename The source filename of the string, or null if not available. * @param startSymbol The start symbol to use, or null if any applicable. */ public Object parse(String input, String filename, String startSymbol) throws BadTokenException, TokenExpectedException, ParseException, SGLRException { logBeforeParsing(); initParseVariables(input, filename); startTime = System.currentTimeMillis(); initParseTimer(); Object result = sglrParse(startSymbol); return result; } private Object sglrParse(String startSymbol) throws BadTokenException, TokenExpectedException, ParseException, SGLRException { getPerformanceMeasuring().startParse(); try { do { readNextToken(); //System.out.print((char)currentToken); history.keepTokenAndState(this); doParseStep(); } while (currentToken != SGLR.EOF && activeStacks.size() > 0); if (acceptingStack == null) { collectedErrors.add(createBadTokenException()); } if(useIntegratedRecovery && acceptingStack==null){ recoverIntegrator.recover(); if(acceptingStack==null && activeStacks.size()>0) { return sglrParse(startSymbol); } } getPerformanceMeasuring().endParse(acceptingStack!=null); } catch (final TaskCancellationException e) { throw new ParseTimeoutException(this, currentToken, tokensSeen - 1, lineNumber, columnNumber, collectedErrors); } finally { activeStacks.clear(); activeStacksWorkQueue.clear(); forShifter.clear(); history.clear(); if (recoverStacks != null) recoverStacks.clear(); } logAfterParsing(); final Link s = acceptingStack.findDirectLink(startFrame); if (s == null) { throw new ParseException(this, "Accepting stack has no link"); } logParseResult(s); Tools.debug("avoids: ", s.recoverCount); //Tools.debug(s.label.toParseTree(parseTable)); if (getTreeBuilder() instanceof NullTreeBuilder) { return null; } else { return disambiguator.applyFilters(this, s.label, startSymbol, tokensSeen); } } void readNextToken() { logCurrentToken(); currentToken = getNextToken(); } protected void doParseStep() { logBeforeParseCharacter(); parseCharacter(); //applies reductions on active stack structure and fills forshifter shifter(); //renewes active stacks with states in forshifter } private void initParseVariables(String input, String filename) { forActor.clear(); forActorDelayed.clear(); forShifter.clear(); history.clear(); startFrame = initActiveStacks(); tokensSeen = 0; currentInputStream = new PushbackStringIterator(input); acceptingStack = null; collectedErrors.clear(); history=new ParserHistory(); performanceMeasuring=new RecoveryPerformance(); getTreeBuilder().initializeInput(input, filename); PooledPathList.resetPerformanceCounters(); PathListPool.resetPerformanceCounters(); ambiguityManager = new AmbiguityManager(input.length()); if (getTreeBuilder().getTokenizer() != null) { // Make sure we use the same starting offsets as the tokenizer, if any // (crucial for parsing fragments at a time) lineNumber = getTreeBuilder().getTokenizer().getEndLine(); columnNumber = getTreeBuilder().getTokenizer().getEndColumn(); startOffset = getTreeBuilder().getTokenizer().getStartOffset(); } else { lineNumber = 1; columnNumber = 0; } } private BadTokenException createBadTokenException() { final Frame singlePreviousStack = activeStacks.size() == 1 ? activeStacks.get(0) : null; if (singlePreviousStack != null) { Action action = singlePreviousStack.peek().getSingularAction(); if (action != null && action.getActionItems().length == 1) { final StringBuilder expected = new StringBuilder(); do { final int token = action.getSingularRange(); if (token == -1) { break; } expected.append((char) token); final ActionItem[] items = action.getActionItems(); if (!(items.length == 1 && items[0].type == ActionItem.SHIFT)) { break; } final Shift shift = (Shift) items[0]; action = parseTable.getState(shift.nextState).getSingularAction(); } while (action != null); if (expected.length() > 0) { return new TokenExpectedException(this, expected.toString(), currentToken, tokensSeen + startOffset - 1, lineNumber, columnNumber); } } } return new BadTokenException(this, currentToken, tokensSeen + startOffset - 1, lineNumber, columnNumber); } private void shifter() { logBeforeShifter(); activeStacks.clear(); final AbstractParseNode prod = parseTable.lookupProduction(currentToken); while (forShifter.size() > 0) { final ActionState as = forShifter.remove(); if (!parseTable.hasRejects() || !as.st.allLinksRejected()) { Frame st1=findStack(activeStacks, as.s); if(st1==null){ st1 = newStack(as.s); addStack(st1); } st1.addLink(as.st, prod, 1); } else { if (Tools.logging) { Tools.logger("Shifter: skipping rejected stack with state ", as.st.state.stateNumber); } } } logAfterShifter(); } protected void addStack(Frame st1) { if(Tools.tracing) { TRACE("SG_AddStack() - " + st1.state.stateNumber); } activeStacks.addFirst(st1); } private void parseCharacter() { logBeforeParseCharacter(); activeStacksWorkQueue.clear(); activeStacksWorkQueue.addAll(activeStacks); forActorDelayed.clear(); forShifter.clear(); while (activeStacksWorkQueue.size() > 0 || forActor.size() > 0) { final Frame st = pickStackNodeFromActivesOrForActor(activeStacksWorkQueue); if (!st.allLinksRejected()) { actor(st); } if(activeStacksWorkQueue.size() == 0 && forActor.size() == 0) { fillForActorWithDelayedFrames(); //Fills foractor, clears foractor delayed } } } private void fillForActorWithDelayedFrames() { if(Tools.tracing) { TRACE("SG_ - both empty"); } final ArrayDeque<Frame> empty = forActor; forActor = forActorDelayed; empty.clear(); forActorDelayed = empty; } private Frame pickStackNodeFromActivesOrForActor(ArrayDeque<Frame> actives) { Frame st; if(actives.size() > 0) { if(Tools.tracing) { TRACE("SG_ - took active"); } st = actives.remove(); } else { if(Tools.tracing) { TRACE("SG_ - took foractor"); } st = forActor.remove(); } return st; } private void actor(Frame st) { final State s = st.peek(); logBeforeActor(st, s); for (final Action action : s.getActions()) { if (action.accepts(currentToken)) { for (final ActionItem ai : action.getActionItems()) { switch (ai.type) { case ActionItem.SHIFT: { final Shift sh = (Shift) ai; final ActionState actState = new ActionState(st, parseTable.getState(sh.nextState)); actState.currentToken = currentToken; addShiftPair(actState); //Adds StackNode to forshifter statsRecordParsers(); //sets some values un current parse state break; } case ActionItem.REDUCE: { final Reduce red = (Reduce) ai; doReductions(st, red.production); break; } case ActionItem.REDUCE_LOOKAHEAD: { final ReduceLookahead red = (ReduceLookahead) ai; if(checkLookahead(red)) { if(Tools.tracing) { TRACE("SG_ - ok"); } doReductions(st, red.production); } break; } case ActionItem.ACCEPT: { if (!st.allLinksRejected()) { acceptingStack = st; if (Tools.logging) { Tools.logger("Reached the accept state"); } } break; } default: throw new IllegalStateException("Unknown action type: " + ai.type); } } } } if(Tools.tracing) { TRACE("SG_ - actor done"); } } private boolean checkLookahead(ReduceLookahead red) { return doCheckLookahead(red, red.getCharRanges(), 0); } private boolean doCheckLookahead(ReduceLookahead red, RangeList[] charClass, int pos) { if(Tools.tracing) { TRACE("SG_CheckLookAhead() - "); } final int c = currentInputStream.read(); // EOF if(c == -1) { return true; } boolean permit = true; if(pos < charClass.length) { permit = charClass[pos].within(c) ? false : doCheckLookahead(red, charClass, pos + 1); } currentInputStream.unread(c); return permit; } private void addShiftPair(ActionState state) { if(Tools.tracing) { TRACE("SG_AddShiftPair() - " + state.s.stateNumber); } forShifter.add(state); } private void statsRecordParsers() { if (forShifter.size() > maxBranches) { maxBranches = forShifter.size(); maxToken = currentToken; maxColumn = columnNumber; maxLine = lineNumber; maxTokenNumber = tokensSeen; } } private void doReductions(Frame st, Production prod) { if(!recoverModeOk(st, prod)) { return; } PooledPathList paths = pathCache.create(); try { st.findAllPaths(paths, prod.arity); logBeforeDoReductions(st, prod, paths.size()); reduceAllPaths(prod, paths); logAfterDoReductions(); } finally { pathCache.endCreate(paths); } } private boolean recoverModeOk(Frame st, Production prod) { return !prod.isRecoverProduction() || fineGrainedOnRegion; } private void doLimitedReductions(Frame st, Production prod, Link l) { //Todo: Look add sharing code with doReductions if(!recoverModeOk(st, prod)) { return; } PooledPathList limitedPool = pathCache.create(); try { st.findLimitedPaths(limitedPool, prod.arity, l); //find paths containing the link logBeforeLimitedReductions(st, prod, l, limitedPool); reduceAllPaths(prod, limitedPool); } finally { pathCache.endCreate(limitedPool); } } private void reduceAllPaths(Production prod, PooledPathList paths) { for(int i = 0; i < paths.size(); i++) { final Path path = paths.get(i); final AbstractParseNode[] kids = path.getParseNodes(); final Frame st0 = path.getEnd(); final State next = parseTable.go(st0.state, prod.label); logReductionPath(prod, path, st0, next); if(!prod.isRecoverProduction()) reducer(st0, next, prod, kids, path); else reducerRecoverProduction(st0, next, prod, kids, path); } if (asyncAborted) { // Rethrown as ParseTimeoutException in SGLR.sglrParse() throw new TaskCancellationException("Long-running parse job aborted"); } } private void reducer(Frame st0, State s, Production prod, AbstractParseNode[] kids, Path path) { assert(!prod.isRecoverProduction()); logBeforeReducer(s, prod, path.getLength()); increaseReductionCount(); final int length = path.getLength(); final int numberOfRecoveries = calcRecoverCount(prod, path); final AbstractParseNode t = prod.apply(kids); final Frame st1 = findStack(activeStacks, s); if (st1 == null) { // Found no existing stack with for state s; make new stack addNewStack(st0, s, prod, length, numberOfRecoveries, t); } else { /* A stack with state s exists; check for ambiguities */ Link nl = st1.findDirectLink(st0); if (nl != null) { logAmbiguity(st0, prod, st1, nl); if (prod.isRejectProduction()) { nl.reject(); } if(numberOfRecoveries == 0 && nl.recoverCount == 0 || nl.isRejected()) { createAmbNode(t, nl); } else if (numberOfRecoveries < nl.recoverCount) { nl.label = t; nl.recoverCount = numberOfRecoveries; actorOnActiveStacksOverNewLink(nl); } else if (numberOfRecoveries == nl.recoverCount) { nl.label = t; } } else { nl = st1.addLink(st0, t, length); nl.recoverCount = numberOfRecoveries; if (prod.isRejectProduction()) { nl.reject(); increaseRejectCount(); } logAddedLink(st0, st1, nl); actorOnActiveStacksOverNewLink(nl); } } if(Tools.tracing) { TRACE_ActiveStacks(); TRACE("SG_ - reducer done"); } } private void reducerRecoverProduction(Frame st0, State s, Production prod, AbstractParseNode[] kids, Path path) { assert(prod.isRecoverProduction()); final int length = path.getLength(); final int numberOfRecoveries = calcRecoverCount(prod, path); final AbstractParseNode t = prod.apply(kids); final Frame stActive = findStack(activeStacks, s); if(stActive!=null){ Link lnActive=stActive.findDirectLink(st0); if(lnActive!=null){ return; //TODO: ambiguity } } final Frame stRecover = findStack(recoverStacks, s); if(stRecover!=null){ Link nlRecover = stRecover.findDirectLink(st0); if(nlRecover!=null){ return; //TODO: ambiguity } nlRecover = stRecover.addLink(st0, t, length); nlRecover.recoverCount = numberOfRecoveries; return; } addNewRecoverStack(st0, s, prod, length, numberOfRecoveries, t); } private void createAmbNode(AbstractParseNode t, Link nl) { nl.addAmbiguity(t, tokensSeen); ambiguityManager.increaseAmbiguityCalls(); } /** * Found no existing stack with for state s; make new stack */ private void addNewStack(Frame st0, State s, Production prod, int length, int numberOfRecoveries, AbstractParseNode t) { final Frame st1 = newStack(s); final Link nl = st1.addLink(st0, t, length); nl.recoverCount = numberOfRecoveries; addStack(st1); forActorDelayed.addFirst(st1); if(Tools.tracing) { TRACE("SG_AddStack() - " + st1.state.stateNumber); } if (prod.isRejectProduction()) { if (Tools.logging) { Tools.logger("Reject [new]"); } nl.reject(); increaseRejectCount(); } } /** * Found no existing stack with for state s; make new stack */ private void addNewRecoverStack(Frame st0, State s, Production prod, int length, int numberOfRecoveries, AbstractParseNode t) { if (!(fineGrainedOnRegion && !prod.isRejectProduction())) { return; } final Frame st1 = newStack(s); final Link nl = st1.addLink(st0, t, length); nl.recoverCount = numberOfRecoveries; recoverStacks.addFirst(st1); } private void actorOnActiveStacksOverNewLink(Link nl) { // Note: ActiveStacks can be modified inside doLimitedReductions // new elements may be inserted at the beginning final int sz = activeStacks.size(); for (int i = 0; i < sz; i++) { // for(Frame st2 : activeStacks) { if(Tools.tracing) { TRACE("SG_ activeStack - "); } final int pos = activeStacks.size() - sz + i; final Frame st2 = activeStacks.get(pos); if (st2.allLinksRejected() || inReduceStacks(forActor, st2) || inReduceStacks(forActorDelayed, st2)) { continue; //stacknode will find reduction in regular process } for (final Action action : st2.peek().getActions()) { if (action.accepts(currentToken)) { for (final ActionItem ai : action.getActionItems()) { switch(ai.type) { case ActionItem.REDUCE: final Reduce red = (Reduce) ai; doLimitedReductions(st2, red.production, nl); break; case ActionItem.REDUCE_LOOKAHEAD: final ReduceLookahead red2 = (ReduceLookahead) ai; if(checkLookahead(red2)) { doLimitedReductions(st2, red2.production, nl); } break; } } } } } } private int calcRecoverCount(Production prod, Path path) { return path.getRecoverCount() + (prod.isRecoverProduction() ? 1 : 0); } private boolean inReduceStacks(Queue<Frame> q, Frame frame) { if(Tools.tracing) { TRACE("SG_InReduceStacks() - " + frame.state.stateNumber); } return q.contains(frame); } protected Frame newStack(State s) { if(Tools.tracing) { TRACE("SG_NewStack() - " + s.stateNumber); } return new Frame(s); } private void increaseReductionCount() { reductionCount++; } protected void increaseRejectCount() { rejectCount++; } protected int getRejectCount() { return rejectCount; } Frame findStack(ArrayDeque<Frame> stacks, State s) { int desiredState = s.stateNumber; if(Tools.tracing) { TRACE("SG_FindStack() - " + desiredState); } // We need only check the top frames of the active stacks. if (Tools.debugging) { Tools.debug("findStack() - ", dumpActiveStacks()); Tools.debug(" looking for ", desiredState); } final int size = stacks.size(); for (int i = 0; i < size; i++) { Frame stack = stacks.get(i); if (stack.state.stateNumber == desiredState) { if(Tools.tracing) { TRACE("SG_ - found stack"); } return stack; } } if(Tools.tracing) { TRACE("SG_ - stack not found"); } return null; } private int getNextToken() { if(Tools.tracing) { TRACE("SG_NextToken() - "); } final int ch = currentInputStream.read(); updateLineAndColumnInfo(ch); if(ch == -1) { return SGLR.EOF; } return ch; } protected void updateLineAndColumnInfo(int ch) { tokensSeen++; if (Tools.debugging) { Tools.debug("getNextToken() - ", ch, "(", (char) ch, ")"); } switch (ch) { case '\n': lineNumber++; columnNumber = 0; break; case '\t': columnNumber = (columnNumber / TAB_SIZE + 1) * TAB_SIZE; break; case -1: break; default: columnNumber++; } } public ParseTable getParseTable() { return parseTable; } public void setTreeBuilder(ITreeBuilder treeBuilder) { this.treeBuilder = treeBuilder; parseTable.initializeTreeBuilder(treeBuilder); } public ITreeBuilder getTreeBuilder() { return treeBuilder; } AmbiguityManager getAmbiguityManager() { return ambiguityManager; } public Disambiguator getDisambiguator() { return disambiguator; } public void setDisambiguator(Disambiguator disambiguator) { this.disambiguator = disambiguator; } @Deprecated public ITermFactory getFactory() { return parseTable.getFactory(); } protected int getReductionCount() { return reductionCount; } protected int getRejectionCount() { return rejectCount; } ////////////////////////////////////////////////////// Log functions /////////////////////////////////////////////////////////////////////////////// // TODO: cleanup, this doesn't belong here! private static int traceCallCount = 0; static void TRACE(String string) { System.err.println("[" + traceCallCount + "] " + string); traceCallCount++; } private String dumpActiveStacks() { final StringBuffer sb = new StringBuffer(); boolean first = true; if (activeStacks == null) { sb.append(" GSS unitialized"); } else { sb.append("{").append(activeStacks.size()).append("} "); for (final Frame f : activeStacks) { if (!first) { sb.append(", "); } sb.append(f.dumpStack()); first = false; } } return sb.toString(); } private void logParseResult(Link s) { if (Tools.debugging) { Tools.debug("internal parse tree:\n", s.label); } if(Tools.tracing) { TRACE("SG_ - internal tree: " + s.label); } if (Tools.measuring) { final Measures m = new Measures(); //Tools.debug("Time (ms): " + (System.currentTimeMillis()-startTime)); m.setTime(System.currentTimeMillis() - startTime); //Tools.debug("Red.: " + reductionCount); m.setReductionCount(reductionCount); //Tools.debug("Nodes: " + Frame.framesCreated); m.setFramesCreated(Frame.framesCreated); //Tools.debug("Links: " + Link.linksCreated); m.setLinkedCreated(Link.linksCreated); //Tools.debug("avoids: " + s.avoidCount); m.setAvoidCount(s.recoverCount); //Tools.debug("Total Time: " + parseTime); m.setParseTime(parseTime); //Tools.debug("Total Count: " + parseCount); Measures.setParseCount(++parseCount); //Tools.debug("Average Time: " + (int)parseTime / parseCount); m.setAverageParseTime((int)parseTime / parseCount); m.setRecoverTime(-1); Tools.setMeasures(m); } } private void logBeforeParsing() { if(Tools.tracing) { TRACE("SG_Parse() - "); } if (Tools.debugging) { Tools.debug("parse() - ", dumpActiveStacks()); } } private void logAfterParsing() throws BadTokenException, TokenExpectedException { if (isLogging()) { Tools.logger("Number of lines: ", lineNumber); Tools.logger("Maximum ", maxBranches, " parse branches reached at token ", logCharify(maxToken), ", line ", maxLine, ", column ", maxColumn, " (token #", maxTokenNumber, ")"); final long elapsed = System.currentTimeMillis() - startTime; Tools.logger("Parse time: " + elapsed / 1000.0f + "s"); } if (Tools.debugging) { Tools.debug("Parsing complete: all tokens read"); } if (acceptingStack == null) { final BadTokenException bad = createBadTokenException(); if (collectedErrors.isEmpty()) { throw bad; } else { collectedErrors.add(bad); throw new MultiBadTokenException(this, collectedErrors); } } if (Tools.debugging) { Tools.debug("Accepting stack exists"); } } private void logCurrentToken() { if (isLogging()) { Tools.logger("Current token (#", tokensSeen, "): ", logCharify(currentToken)); } } private void logAfterShifter() { if(Tools.tracing) { TRACE("SG_DiscardShiftPairs() - "); TRACE_ActiveStacks(); } } private void logBeforeShifter() { if(Tools.tracing) { TRACE("SG_Shifter() - "); TRACE_ActiveStacks(); } if (Tools.logging) { Tools.logger("#", tokensSeen, ": shifting ", forShifter.size(), " parser(s) -- token ", logCharify(currentToken), ", line ", lineNumber, ", column ", columnNumber); } if (Tools.debugging) { Tools.debug("shifter() - " + dumpActiveStacks()); Tools.debug(" token : " + currentToken); Tools.debug(" parsers : " + forShifter.size()); } } private void logBeforeParseCharacter() { if(Tools.tracing) { TRACE("SG_ParseToken() - "); } if (Tools.debugging) { Tools.debug("parseCharacter() - " + dumpActiveStacks()); Tools.debug(" # active stacks : " + activeStacks.size()); } /* forActor = *///computeStackOfStacks(activeStacks); if (Tools.debugging) { Tools.debug(" # for actor : " + forActor.size()); } } private String logCharify(int currentToken) { switch (currentToken) { case 32: return "\\32"; case SGLR.EOF: return "EOF"; case '\n': return "\\n"; case 0: return "\\0"; default: return "" + (char) currentToken; } } @SuppressWarnings("deprecation") private void logBeforeActor(Frame st, State s) { List<ActionItem> actionItems = null; if (Tools.debugging || Tools.tracing) { actionItems = s.getActionItems(currentToken); } if(Tools.tracing) { TRACE("SG_Actor() - " + st.state.stateNumber); TRACE_ActiveStacks(); } if (Tools.debugging) { Tools.debug("actor() - ", dumpActiveStacks()); } if (Tools.debugging) { Tools.debug(" state : ", s.stateNumber); Tools.debug(" token : ", currentToken); } if (Tools.debugging) { Tools.debug(" actions : ", actionItems); } if(Tools.tracing) { TRACE("SG_ - actions: " + actionItems.size()); } } private void logAfterDoReductions() { if (Tools.debugging) { Tools.debug("<doReductions() - " + dumpActiveStacks()); } if(Tools.tracing) { TRACE("SG_ - doreductions done"); } } private void logReductionPath(Production prod, Path path, Frame st0, State next) { if (Tools.debugging) { Tools.debug(" path: ", path); Tools.debug(st0.state); } if (Tools.logging) { Tools.logger("Goto(", st0.peek().stateNumber, ",", prod.label + ") == ", next.stateNumber); } } private void logBeforeDoReductions(Frame st, Production prod, final int pathsCount) { if(Tools.tracing) { TRACE("SG_DoReductions() - " + st.state.stateNumber); } if (Tools.debugging) { Tools.debug("doReductions() - " + dumpActiveStacks()); logReductionInfo(st, prod); Tools.debug(" paths : " + pathsCount); } } private void logBeforeLimitedReductions(Frame st, Production prod, Link l, PooledPathList paths) { if(Tools.tracing) { TRACE("SG_ - back in reducer "); TRACE_ActiveStacks(); TRACE("SG_DoLimitedReductions() - " + st.state.stateNumber + ", " + l.parent.state.stateNumber); } if (Tools.debugging) { Tools.debug("doLimitedReductions() - ", dumpActiveStacks()); logReductionInfo(st, prod); Tools.debug(Arrays.asList(paths)); } } private void logReductionInfo(Frame st, Production prod) { Tools.debug(" state : ", st.peek().stateNumber); Tools.debug(" token : ", currentToken); Tools.debug(" label : ", prod.label); Tools.debug(" arity : ", prod.arity); Tools.debug(" stack : ", st.dumpStack()); } private void logAddedLink(Frame st0, Frame st1, Link nl) { if (Tools.debugging) { Tools.debug(" added link ", nl, " from ", st1.state.stateNumber, " to ", st0.state.stateNumber); } if(Tools.tracing) { TRACE_ActiveStacks(); } } private void logBeforeReducer(State s, Production prod, int length) { if(Tools.tracing) { TRACE("SG_Reducer() - " + s.stateNumber + ", " + length + ", " + prod.label); TRACE_ActiveStacks(); } if (Tools.logging) { Tools.logger("Reducing; state ", s.stateNumber, ", token: ", logCharify(currentToken), ", production: ", prod.label); } if (Tools.debugging) { Tools.debug("reducer() - ", dumpActiveStacks()); Tools.debug(" state : ", s.stateNumber); Tools.debug(" token : ", logCharify(currentToken) + " (" + currentToken + ")"); Tools.debug(" production : ", prod.label); } } private void TRACE_ActiveStacks() { TRACE("SG_ - active stacks: " + activeStacks.size()); TRACE("SG_ - for_actor stacks: " + forActor.size()); TRACE("SG_ - for_actor_delayed stacks: " + forActorDelayed.size()); } private void logAmbiguity(Frame st0, Production prod, Frame st1, Link nl) { if (Tools.logging) { Tools.logger("Ambiguity: direct link ", st0.state.stateNumber, " -> ", st1.state.stateNumber, " ", (prod.isRejectProduction() ? "{reject}" : "")); if (nl.label.isParseNode()) { Tools.logger("nl is ", nl.isRejected() ? "{reject}" : "", " for ", ((ParseNode) nl.label).getLabel()); } } if (Tools.debugging) { Tools.debug("createAmbiguityCluster - ", tokensSeen - nl.getLength() - 1, "/", nl.getLength()); } } }