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
C#
UTF-8
1,628
3.53125
4
[ "MIT" ]
permissive
// <copyright file="Program.cs" company="OSIsoft, LLC"> // Copyright © 2016 John L. Swartzentruber // </copyright> namespace PerfectSquaresBenchmarking { /// <summary> /// Combine different solutions in an attempt to create an optimal solution /// </summary> public class HybridSolution : IPerfectSquareSolution { /// <summary> /// Fastest general purpose solution /// </summary> private static readonly IPerfectSquareSolution Solver = new BinarySearchSolution(); /// <summary> /// Gets the name of this solution /// </summary> public string Name => "Hybrd"; /// <summary> /// Determines if the input value is a perfect square /// </summary> /// <param name="value">The value being checked</param> /// <returns>True if perfect square</returns> public bool IsPerfectSquare(long value) { if (value == 0) { return false; } int[] smallPrimes = { 2, 3, 5, 7, 11, 13, 17 }; // First do prime factor processing to reduce the value foreach (var factor in smallPrimes) { while (value % factor == 0) { value /= factor; if (value % factor != 0) { return false; } value /= factor; } } return value == 1 || Solver.IsPerfectSquare(value); } } }
JavaScript
UTF-8
5,362
2.65625
3
[]
no_license
const puppeteer = require('puppeteer'); const mongoose = require('mongoose'); const EventEmitter = require('events'); EventEmitter.defaultMaxListeners = 1000; // depends on number of items scraped const constants = require('./util/constants.js'); const Job = require('./models/job'); const jobTitle = 'Graduate Developer' const jobLocation = '' const jobTitleLink = jobTitle.toLowerCase().split(' ').join('-') const searchUrl = `https://www.seek.com.au/${jobTitleLink}-jobs/${jobLocation === '' ? '' : 'in-'+jobLocation}` async function run() { const browser = await puppeteer.launch({ headless: false }); const page = await browser.newPage(); await page.goto(constants.SEEK_URL); await page.click(constants.KEYWORDS); await page.keyboard.type(jobTitle); await page.click(constants.LOCATION); await page.keyboard.type(jobLocation); await page.click(constants.SEARCH); await page.waitFor(2000); await page.screenshot({ path: './src/screenshots/search.png' }); let numPages = await getNumPages(page); console.log('Numpages: ', numPages); for (let h = 1; h <= numPages; h++) { let pageUrl = h > 1 ? searchUrl + '?page=' + h : searchUrl; await page.goto(pageUrl); console.log(`Page ` + h) const listContainer = constants.JOB_CLASS; let jobListLength = await page.evaluate(sel => { let jobList = document.querySelectorAll(sel); return jobList.length; }, listContainer) for (let i = 2; i <= jobListLength; i++) { let titleSelector = constants.JOB_TITLE.replace('INDEX', i); let detailSelector = constants.JOB_DETAILS.replace('INDEX', i); let categorySelector = constants.JOB_CATEGORY.replace('INDEX', i); let locationSelector = constants.JOB_LOCATION.replace('INDEX', i); let jobTitle = await page.evaluate(sel => { let element = document.querySelector(sel) return element ? element.getAttribute('aria-label') : null }, titleSelector) let jobCategory = await page.evaluate(sel => { let element = document.querySelector(sel) return element ? element.innerText.replace('classification: ', '') : null }, categorySelector) let jobCompany = await page.evaluate(sel => { let element = document.querySelectorAll(sel)[2] return element ? element.innerText.replace('at ', '') : null }, detailSelector) let jobDescription = await page.evaluate(sel => { let element = document.querySelectorAll(sel)[3] return element ? element.innerText : null }, detailSelector) let jobLocation = await page.evaluate(sel => { let element = document.querySelector(sel) return element ? element.innerText : null }, locationSelector) let jobDays = await page.evaluate(sel => { let element = document.querySelectorAll(sel)[1] return element ? element.innerText : null }, detailSelector) const jobTypes = ['c#', 'c++', 'java', 'php', '.net', 'react', 'angular', 'devops', 'node', 'ruby on rails', 'wordpress', 'scala', 'front end', 'python', 'django', 'software']; let jobType = []; for (let type of jobTypes) { if (jobTitle.toLowerCase().includes(type)) { jobType.push(type); } } if (jobType.length === 0) { jobType.push('general') } console.log(jobTitle + '->' + jobLocation + '->' + jobCompany + '->' + jobDays) await insertJob({ description: jobDescription, title: jobTitle, type: jobType, company: jobCompany, category: jobCategory, location: jobLocation, period: jobDays, dateCrawled: new Date() }) } } await browser.close() } run() async function getNumPages(page) { const jobCount = constants.JOBS_NUM; let pageCount = await page.evaluate( sel => { let jobs = parseInt(document.querySelector(sel).innerText); let pages = Math.ceil(jobs / 20); return pages }, jobCount) return pageCount } async function insertJob(jobPost) { const DB_URL = 'mongodb://localhost/joblist' if (mongoose.connection.readyState === 0) { await mongoose.connect(DB_URL); } mongoose.connection.on('connected', () => { console.log('Establish connection to MongoDB') }) // if a job entry exists, update the entry, don't insert let conditions = { description: jobPost.description } let options = { upsert: true, new: true, setDefaultsOnInsert: true }; Job.findOneAndUpdate(conditions, jobPost, options, (err, result) => { if (err) throw err; // console.log(jobPost) console.count('Job posted!') }); }
Go
UTF-8
10,208
2.59375
3
[ "Apache-2.0" ]
permissive
package keeper import ( "bytes" "fmt" sdk "github.com/cosmos/cosmos-sdk/types" sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" clienttypes "github.com/cosmos/cosmos-sdk/x/ibc/02-client/types" "github.com/cosmos/cosmos-sdk/x/ibc/03-connection/types" commitmenttypes "github.com/cosmos/cosmos-sdk/x/ibc/23-commitment/types" ) // ConnOpenInit initialises a connection attempt on chain A. // // NOTE: Identifiers are checked on msg validation. func (k Keeper) ConnOpenInit( ctx sdk.Context, connectionID, // identifier clientID string, counterparty types.Counterparty, // desiredCounterpartyConnectionIdentifier, counterpartyPrefix, counterpartyClientIdentifier ) error { _, found := k.GetConnection(ctx, connectionID) if found { return types.ErrConnectionExists } // connection defines chain A's ConnectionEnd connection := types.NewConnectionEnd(types.INIT, connectionID, clientID, counterparty, types.GetCompatibleEncodedVersions()) k.SetConnection(ctx, connectionID, connection) if err := k.addConnectionToClient(ctx, clientID, connectionID); err != nil { return err } k.Logger(ctx).Info(fmt.Sprintf("connection %s state updated: NONE -> INIT", connectionID)) return nil } // ConnOpenTry relays notice of a connection attempt on chain A to chain B (this // code is executed on chain B). // // NOTE: // - Here chain A acts as the counterparty // - Identifiers are checked on msg validation func (k Keeper) ConnOpenTry( ctx sdk.Context, connectionID string, // desiredIdentifier counterparty types.Counterparty, // counterpartyConnectionIdentifier, counterpartyPrefix and counterpartyClientIdentifier clientID string, // clientID of chainA counterpartyVersions []string, // supported versions of chain A proofInit []byte, // proof that chainA stored connectionEnd in state (on ConnOpenInit) proofConsensus []byte, // proof that chainA stored chainB's consensus state at consensus height proofHeight uint64, // height at which relayer constructs proof of A storing connectionEnd in state consensusHeight uint64, // latest height of chain B which chain A has stored in its chain B client ) error { if consensusHeight >= uint64(ctx.BlockHeight()) { return sdkerrors.Wrapf( sdkerrors.ErrInvalidHeight, "consensus height is greater than or equal to the current block height (%d >= %d)", consensusHeight, uint64(ctx.BlockHeight()), ) } expectedConsensusState, found := k.clientKeeper.GetSelfConsensusState(ctx, consensusHeight) if !found { return clienttypes.ErrSelfConsensusStateNotFound } // expectedConnection defines Chain A's ConnectionEnd // NOTE: chain A's counterparty is chain B (i.e where this code is executed) prefix := k.GetCommitmentPrefix() expectedCounterparty := types.NewCounterparty(clientID, connectionID, commitmenttypes.NewMerklePrefix(prefix.Bytes())) expectedConnection := types.NewConnectionEnd(types.INIT, counterparty.ConnectionID, counterparty.ClientID, expectedCounterparty, counterpartyVersions) // chain B picks a version from Chain A's available versions that is compatible // with the supported IBC versions version, err := types.PickVersion(counterpartyVersions) if err != nil { return err } // connection defines chain B's ConnectionEnd connection := types.NewConnectionEnd(types.UNINITIALIZED, connectionID, clientID, counterparty, []string{version}) // Check that ChainA committed expectedConnectionEnd to its state if err := k.VerifyConnectionState( ctx, connection, proofHeight, proofInit, counterparty.ConnectionID, expectedConnection, ); err != nil { return err } // Check that ChainA stored the correct ConsensusState of chainB at the given consensusHeight if err := k.VerifyClientConsensusState( ctx, connection, proofHeight, consensusHeight, proofConsensus, expectedConsensusState, ); err != nil { return err } // If connection already exists for connectionID, ensure that the existing connection's counterparty // is chainA and connection is on INIT stage // Check that existing connection version is on desired version of current handshake previousConnection, found := k.GetConnection(ctx, connectionID) if found && !(previousConnection.State == types.INIT && previousConnection.Counterparty.ConnectionID == counterparty.ConnectionID && bytes.Equal(previousConnection.Counterparty.Prefix.Bytes(), counterparty.Prefix.Bytes()) && previousConnection.ClientID == clientID && previousConnection.Counterparty.ClientID == counterparty.ClientID && previousConnection.Versions[0] == version) { return sdkerrors.Wrap(types.ErrInvalidConnection, "cannot relay connection attempt") } // Set connection state to TRYOPEN and store in chainB state connection.State = types.TRYOPEN if err := k.addConnectionToClient(ctx, clientID, connectionID); err != nil { return sdkerrors.Wrapf(err, "failed to add connection with ID %s to client with ID %s", connectionID, clientID) } k.SetConnection(ctx, connectionID, connection) k.Logger(ctx).Info(fmt.Sprintf("connection %s state updated: %s -> TRYOPEN ", connectionID, previousConnection.State)) return nil } // ConnOpenAck relays acceptance of a connection open attempt from chain B back // to chain A (this code is executed on chain A). // // NOTE: Identifiers are checked on msg validation. func (k Keeper) ConnOpenAck( ctx sdk.Context, connectionID string, encodedVersion string, // version that ChainB chose in ConnOpenTry proofTry []byte, // proof that connectionEnd was added to ChainB state in ConnOpenTry proofConsensus []byte, // proof that chainB has stored ConsensusState of chainA on its client proofHeight uint64, // height that relayer constructed proofTry consensusHeight uint64, // latest height of chainA that chainB has stored on its chainA client ) error { // Check that chainB client hasn't stored invalid height if consensusHeight >= uint64(ctx.BlockHeight()) { return sdkerrors.Wrapf( sdkerrors.ErrInvalidHeight, "consensus height is greater than or equal to the current block height (%d >= %d)", consensusHeight, uint64(ctx.BlockHeight()), ) } // Retrieve connection connection, found := k.GetConnection(ctx, connectionID) if !found { return sdkerrors.Wrap(types.ErrConnectionNotFound, connectionID) } // Check connection on ChainA is on correct state: INIT or TRYOPEN if connection.State != types.INIT && connection.State != types.TRYOPEN { return sdkerrors.Wrapf( types.ErrInvalidConnectionState, "connection state is not INIT or TRYOPEN (got %s)", connection.State.String(), ) } version, err := types.DecodeVersion(encodedVersion) if err != nil { return sdkerrors.Wrap(err, "version negotiation failed") } // Check that ChainB's proposed version identifier is supported by chainA supportedVersion, found := types.FindSupportedVersion(version, types.GetCompatibleVersions()) if !found { return sdkerrors.Wrapf( types.ErrVersionNegotiationFailed, "connection version provided (%s) is not supported (%s)", version, types.GetCompatibleVersions(), ) } // Check that ChainB's proposed feature set is supported by chainA if err := supportedVersion.VerifyProposedVersion(version); err != nil { return err } // Retrieve chainA's consensus state at consensusheight expectedConsensusState, found := k.clientKeeper.GetSelfConsensusState(ctx, consensusHeight) if !found { return clienttypes.ErrSelfConsensusStateNotFound } prefix := k.GetCommitmentPrefix() expectedCounterparty := types.NewCounterparty(connection.ClientID, connectionID, commitmenttypes.NewMerklePrefix(prefix.Bytes())) expectedConnection := types.NewConnectionEnd(types.TRYOPEN, connection.Counterparty.ConnectionID, connection.Counterparty.ClientID, expectedCounterparty, []string{encodedVersion}) // Ensure that ChainB stored expected connectionEnd in its state during ConnOpenTry if err := k.VerifyConnectionState( ctx, connection, proofHeight, proofTry, connection.Counterparty.ConnectionID, expectedConnection, ); err != nil { return err } // Ensure that ChainB has stored the correct ConsensusState for chainA at the consensusHeight if err := k.VerifyClientConsensusState( ctx, connection, proofHeight, consensusHeight, proofConsensus, expectedConsensusState, ); err != nil { return err } k.Logger(ctx).Info(fmt.Sprintf("connection %s state updated: %s -> OPEN ", connectionID, connection.State)) // Update connection state to Open connection.State = types.OPEN connection.Versions = []string{encodedVersion} k.SetConnection(ctx, connectionID, connection) return nil } // ConnOpenConfirm confirms opening of a connection on chain A to chain B, after // which the connection is open on both chains (this code is executed on chain B). // // NOTE: Identifiers are checked on msg validation. func (k Keeper) ConnOpenConfirm( ctx sdk.Context, connectionID string, proofAck []byte, // proof that connection opened on ChainA during ConnOpenAck proofHeight uint64, // height that relayer constructed proofAck ) error { // Retrieve connection connection, found := k.GetConnection(ctx, connectionID) if !found { return sdkerrors.Wrap(types.ErrConnectionNotFound, connectionID) } // Check that connection state on ChainB is on state: TRYOPEN if connection.State != types.TRYOPEN { return sdkerrors.Wrapf( types.ErrInvalidConnectionState, "connection state is not TRYOPEN (got %s)", connection.State.String(), ) } prefix := k.GetCommitmentPrefix() expectedCounterparty := types.NewCounterparty(connection.ClientID, connectionID, commitmenttypes.NewMerklePrefix(prefix.Bytes())) expectedConnection := types.NewConnectionEnd(types.OPEN, connection.Counterparty.ConnectionID, connection.Counterparty.ClientID, expectedCounterparty, connection.Versions) // Check that connection on ChainA is open if err := k.VerifyConnectionState( ctx, connection, proofHeight, proofAck, connection.Counterparty.ConnectionID, expectedConnection, ); err != nil { return err } // Update ChainB's connection to Open connection.State = types.OPEN k.SetConnection(ctx, connectionID, connection) k.Logger(ctx).Info(fmt.Sprintf("connection %s state updated: TRYOPEN -> OPEN ", connectionID)) return nil }
Markdown
UTF-8
603
3.65625
4
[]
no_license
# Tic-Tac-Toe-Game A simple C++ program to play Tic-Tac-Toe. The program lets two players play the Tic-Tac-Toe game on a 3 by 3 board. You probably already know how to play Tic-Tac-Toe, but in case you don't... The player who first fills the box with 3 X's or 3 O's in a horizontal, vertical, or diagonal manner will win the game. In some cases, when none of the players succeeds in filling the boxes horizontally, vertically, or diagonally with 3 X's or 3 O's, then the game will be considered to be a draw. [Click here for additional help on the game rules](https://www.wikihow.com/Play-Tic-Tac-Toe)
JavaScript
UTF-8
205
2.5625
3
[]
no_license
const sentiment = require('sentiment') /** * param: Trump tweet * returns: 'happy' or 'sad' */ module.exports = { happyOrSad(tweet) { return sentiment(tweet).score > 0 ? 'Happy!' : 'Sad!' } }
Java
UTF-8
4,560
2.21875
2
[ "Apache-2.0" ]
permissive
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.apis.app; // Need the following import to get access to the app resources, since this // class is in a sub-package. import com.example.android.apis.R; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.os.Parcel; import android.os.RemoteException; import android.widget.Toast; /** * This is an example of implementing an application service that will run in * response to an alarm, allowing us to move long duration work out of an * intent receiver. * * @see AlarmService * @see AlarmService_Alarm */ public class AlarmService_Service extends Service { NotificationManager mNM; @Override public void onCreate() { mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); // show the icon in the status bar showNotification(); // Start up the thread running the service. Note that we create a // separate thread because the service normally runs in the process's // main thread, which we don't want to block. Thread thr = new Thread(null, mTask, "AlarmService_Service"); thr.start(); } @Override public void onDestroy() { // Cancel the notification -- we use the same ID that we had used to start it mNM.cancel(R.string.alarm_service_started); // Tell the user we stopped. Toast.makeText(this, R.string.alarm_service_finished, Toast.LENGTH_SHORT).show(); } /** * The function that runs in our worker thread */ Runnable mTask = new Runnable() { public void run() { // Normally we would do some work here... for our sample, we will // just sleep for 30 seconds. long endTime = System.currentTimeMillis() + 15*1000; while (System.currentTimeMillis() < endTime) { synchronized (mBinder) { try { mBinder.wait(endTime - System.currentTimeMillis()); } catch (Exception e) { } } } // Done with our work... stop the service! AlarmService_Service.this.stopSelf(); } }; @Override public IBinder onBind(Intent intent) { return mBinder; } /** * Show a notification while this service is running. */ private void showNotification() { // In this sample, we'll use the same text for the ticker and the expanded notification CharSequence text = getText(R.string.alarm_service_started); // Set the icon, scrolling text and timestamp Notification notification = new Notification(R.drawable.stat_sample, text, System.currentTimeMillis()); // The PendingIntent to launch our activity if the user selects this notification PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, AlarmService.class), 0); // Set the info for the views that show in the notification panel. notification.setLatestEventInfo(this, getText(R.string.alarm_service_label), text, contentIntent); // Send the notification. // We use a layout id because it is a unique number. We use it later to cancel. mNM.notify(R.string.alarm_service_started, notification); } /** * This is the object that receives interactions from clients. See RemoteService * for a more complete example. */ private final IBinder mBinder = new Binder() { @Override protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException { return super.onTransact(code, data, reply, flags); } }; }
Markdown
UTF-8
609
2.671875
3
[ "Apache-2.0" ]
permissive
## Development The Fastly CLI requires [Go 1.16 or above](https://golang.org). Clone this repo to any path and type `make` to run all of the tests and generate a development build locally. ```sh git clone git@github.com:fastly/cli cd cli make ./fastly version ``` The `make` task requires the following executables to exist in your `$PATH`: - [golint](https://github.com/golang/lint) - [gosec](https://github.com/securego/gosec) - [staticcheck](https://staticcheck.io/) If you have none of them installed, or don't mind them being upgraded automatically, you can run `make dependencies` to install them.
Markdown
UTF-8
4,091
2.828125
3
[]
no_license
[*<<返回主页*](../index.md)<br><br> **本文为作者原创,转载请注明出处**<br> ### 使用pytorch融合多模型结果 本文讲解如何使用pytorch融合多模型结果;<br><br> #### 问题背景 在工作中优化一个二分类问题,针对这个二分类问题有多个模型(每个模型的特征和模型结构有差别)输出多个结果,每个结果均是一个(0, 1)之间的浮点数;融合模型的任务是为每个基模型找一个权重,对多个基模型的结果加权平均;一开始由于基模型数量比较少(2~3个),我们直接使用遍历权重的方法,即取步长为0.01、范围为(0, 1),遍历权重的所有可能值,选取一个最优的权重组合,权重选取的标准是eer(equal error rate,等错误率)最小;如果只有两个基模型,计算复杂度是100,三个基模型时,计算复杂度是100 x 100 = 10000, 由此可见,计算复杂度随基模型的数量指数增加,当模型数量较多时,需要一天甚至几天才能找到最优值(运行时间跟数据量大小也有关系);很显然遍历权重的方法是一种暴力且比较粗糙的办法,而目前主流的深度学习框架都可以自动计算梯度和优化参数,因此可以使用深度学习框架完成各基模型权重的优化,在本任务中不用考虑部署的问题,因此选用用户更加友好的pytorch作为目标框架;<br><br> #### 解决方案 基模型权重学习本质上是一个简单的线性问题,但与线性问题不太一样的地方是需要保证权重的和为1,因此需要对参数进行归一化,假设有n个基模型,模型得分分别为(X<sub>1</sub>, X<sub>2</sub>, ..., X<sub>n</sub>),模型权重分别为(w<sub>1</sub>, w<sub>2</sub>, ..., w<sub>n</sub>),权重归一化后为w<sub>i</sub>/(w<sub>1</sub>+w<sub>2</sub>+ ... +w<sub>n</sub>)(i = 1,2, ..., n),归一化后的权重与模型得分做矩阵乘法即可得到融合模型的得分; 使用权重归一化的好处是权重可以取任意的正数,不必局限在(0, 1)之间以及和为1;<br><br> 融合模型定义完成之后就可以定义模型的loss和优化方法,在<b>问题背景</b>中提到的办法其实是将eer作为loss,按道理融合模型的loss也可以使用eer,但似乎没看到哪个机器学习模型的loss是使用eer的,而且pytorch也不支持eer loss,所以放弃使用eer作为loss,但依然可以使用eer作为验证集的metrics;由于本问题是分类问题,自然而然的想到使用负对数损失函数,当然也可以使用mse;优化方法使用最简单的sgd即可;<br><br> #### 代码细节 代码地址:[https://github.com/suvedo/model_fusion](https://github.com/suvedo/model_fusion)<br><br> 运行sh run.sh即可训练模型权重,训练相关的配置在config.py中,eval_metrics可以指定验证的metrics,支持eer或者auc,eer和auc的计算函数分别对应util.py中的cal_eer()和cal_auc();配置do_early_stop是否使用早停,min_eval_impr配置最小的metric提升量,提升量小于该值表示这一轮的训练过拟合;training_loss指定loss,目前支持负对数(nll)和均方误差(mse);<br><br> 模型的定义和训练在linear_model.py中,另外在util.py中还定义了一个训练数据和验证数据的生成器DataIter;<br><br> #### 总结 从这个任务可以看出,pytorch等深度学习框架其实不止针对深度学习,只要我们能用pytorch支持的op或运算符将我们的任务正确的表示出来(包括模型和loss),即可以使用pytorch等框架的自动求导和数值优化能力帮助我们优化我们的任务参数,从这个角度来讲,pytorch等深度学习框架可以理解成一个基于梯度的数值优化框架,与matlab等商业工具类似;但我们日常的任务并不只是训练出模型参数就终止了,还需要对模型进行部署、线上服务等,因此如何高效的部署模型和前向计算是深度学习框架需要考虑的一个重要问题;(完)<br><br>
Java
UTF-8
450
2.59375
3
[]
no_license
package com.xixi.jimeihui.definition; public enum SuperClass { Home("主页",0), Imagine("图册", 1), Video("视频",2), Mine("我的",3); private String name; private int position; private SuperClass(String name, int position) { this.name = name; this.position = position; } public String getName() { return name; } public int getPosition() { return position; } }
C++
UTF-8
1,341
2.8125
3
[]
no_license
#include "Force.h" #include "Player.h" #include "..\Util.h" using namespace BroodWar; namespace BroodWar { namespace Api { Force^ ConvertForce(BWAPI::Force force) { if(force == NULL) return nullptr; return gcnew Force(force); } Force::Force(BWAPI::Force force) { instance = force; } int Force::Id::get() { return instance->getID(); } String^ Force::Name::get() { return gcnew String(instance->getName().c_str()); } HashSet<Api::Player^>^ Force::Players::get() { return ToHashSet<BWAPI::Player, Player^>(instance->getPlayers(), &ConvertPlayer); } int Force::GetHashCode() { return instance->getID(); } bool Force::Equals(Object^ o) { Force^ other = dynamic_cast<Force^>(o); return this->Equals(other); } bool Force::Equals(Api::Force^ other) { if(ReferenceEquals(nullptr, other)) return false; if(ReferenceEquals(this, other)) return true; return this->instance->getID() == other->instance->getID(); } bool Force::operator == (Api::Force^ first, Api::Force^ second) { if(ReferenceEquals(first, second)) return true; if(ReferenceEquals(nullptr, first)) return false; return first->Equals(second); } bool Force::operator != (Api::Force^ first, Api::Force^ second) { return !(first == second); } } }
C#
UTF-8
4,787
2.96875
3
[ "MIT" ]
permissive
using UnityEngine; /* * Most functions taken from Tween.js - Licensed under the MIT license * at https://github.com/sole/tween.js * Quadratic.Bezier by @fonserbc - Licensed under WTFPL license */ namespace PenetrationTech { public delegate float EasingFunction(float k); public class Easing { public static float Linear (float k) { return k; } public class Quadratic { public static float In (float k) { return k*k; } public static float Out (float k) { return k*(2f - k); } public static float InOut (float k) { if ((k *= 2f) < 1f) return 0.5f*k*k; return -0.5f*((k -= 1f)*(k - 2f) - 1f); } /* * Quadratic.Bezier(k,0) behaves like Quadratic.In(k) * Quadratic.Bezier(k,1) behaves like Quadratic.Out(k) * * If you want to learn more check Alan Wolfe's post about it http://www.demofox.org/bezquad1d.html */ public static float Bezier (float k, float c) { return c*2*k*(1 - k) + k*k; } }; public class Cubic { public static float In (float k) { return k*k*k; } public static float Out (float k) { return 1f + ((k -= 1f)*k*k); } public static float InOut (float k) { if ((k *= 2f) < 1f) return 0.5f*k*k*k; return 0.5f*((k -= 2f)*k*k + 2f); } }; public class Quartic { public static float In (float k) { return k*k*k*k; } public static float Out (float k) { return 1f - ((k -= 1f)*k*k*k); } public static float InOut (float k) { if ((k *= 2f) < 1f) return 0.5f*k*k*k*k; return -0.5f*((k -= 2f)*k*k*k - 2f); } }; public class Quintic { public static float In (float k) { return k*k*k*k*k; } public static float Out (float k) { return 1f + ((k -= 1f)*k*k*k*k); } public static float InOut (float k) { if ((k *= 2f) < 1f) return 0.5f*k*k*k*k*k; return 0.5f*((k -= 2f)*k*k*k*k + 2f); } }; public class Sinusoidal { public static float In (float k) { return 1f - Mathf.Cos(k*Mathf.PI/2f); } public static float Out (float k) { return Mathf.Sin(k*Mathf.PI/2f); } public static float InOut (float k) { return 0.5f*(1f - Mathf.Cos(Mathf.PI*k)); } }; public class Exponential { public static float In (float k) { return k == 0f? 0f : Mathf.Pow(1024f, k - 1f); } public static float Out (float k) { return k == 1f? 1f : 1f - Mathf.Pow(2f, -10f*k); } public static float InOut (float k) { if (k == 0f) return 0f; if (k == 1f) return 1f; if ((k *= 2f) < 1f) return 0.5f*Mathf.Pow(1024f, k - 1f); return 0.5f*(-Mathf.Pow(2f, -10f*(k - 1f)) + 2f); } }; public class Circular { public static float In (float k) { return 1f - Mathf.Sqrt(1f - k*k); } public static float Out (float k) { return Mathf.Sqrt(1f - ((k -= 1f)*k)); } public static float InOut (float k) { if ((k *= 2f) < 1f) return -0.5f*(Mathf.Sqrt(1f - k*k) - 1); return 0.5f*(Mathf.Sqrt(1f - (k -= 2f)*k) + 1f); } }; public class Elastic { public static float In (float k) { if (k == 0) return 0; if (k == 1) return 1; return -Mathf.Pow( 2f, 10f*(k -= 1f))*Mathf.Sin((k - 0.1f)*(2f*Mathf.PI)/0.4f); } public static float Out (float k) { if (k == 0) return 0; if (k == 1) return 1; return Mathf.Pow(2f, -10f*k)*Mathf.Sin((k - 0.1f)*(2f*Mathf.PI)/0.4f) + 1f; } public static float InOut (float k) { if ((k *= 2f) < 1f) return -0.5f*Mathf.Pow(2f, 10f*(k -= 1f))*Mathf.Sin((k - 0.1f)*(2f*Mathf.PI)/0.4f); return Mathf.Pow(2f, -10f*(k -= 1f))*Mathf.Sin((k - 0.1f)*(2f*Mathf.PI)/0.4f)*0.5f + 1f; } }; public class Back { static float s = 1.70158f; static float s2 = 2.5949095f; public static float In (float k) { return k*k*((s + 1f)*k - s); } public static float Out (float k) { return (k -= 1f)*k*((s + 1f)*k + s) + 1f; } public static float InOut (float k) { if ((k *= 2f) < 1f) return 0.5f*(k*k*((s2 + 1f)*k - s2)); return 0.5f*((k -= 2f)*k*((s2 + 1f)*k + s2) + 2f); } }; public class Bounce { public static float In (float k) { return 1f - Out(1f - k); } public static float Out (float k) { if (k < (1f/2.75f)) { return 7.5625f*k*k; } else if (k < (2f/2.75f)) { return 7.5625f*(k -= (1.5f/2.75f))*k + 0.75f; } else if (k < (2.5f/2.75f)) { return 7.5625f *(k -= (2.25f/2.75f))*k + 0.9375f; } else { return 7.5625f*(k -= (2.625f/2.75f))*k + 0.984375f; } } public static float InOut (float k) { if (k < 0.5f) return In(k*2f)*0.5f; return Out(k*2f - 1f)*0.5f + 0.5f; } }; } }
Java
UTF-8
3,702
2.578125
3
[]
no_license
package edu.gvsu.kurmasz.zawilinski.test; import edu.gvsu.kurmasz.warszawa.io.InputHelper; import edu.gvsu.kurmasz.warszawa.io.OutputHelper; import edu.gvsu.kurmasz.warszawa.log.Log; import edu.gvsu.kurmasz.warszawa.log.SimpleLog; import edu.gvsu.kurmasz.zawilinski.*; import edu.gvsu.kurmasz.zawilinski.mw.current.MediaWikiType; import edu.gvsu.kurmasz.zawilinski.mw.current.PageType; import edu.gvsu.kurmasz.zawilinski.mw.current.RevisionType; import javax.xml.bind.JAXBException; import java.io.FileNotFoundException; import java.io.InputStream; import java.io.PrintWriter; /** * Verify that the text size pre-filter limits the size of each * revision's text. In particular, this program verifies that, when * the text size pre-filter is applied, the post-filter doesn't receive * any revisions with more text than allowed by the filter. If the post * filter detects too much text, it writes an error message and exits * with a non-zero value. * <p> * Also, for each page, the program writes out (1) the page number, (2) the * number of revisions, and (3) the page title. This output can be compared * with the output of the countRevisions ruby script to verify that the * filter does not "loose" any pages or revisions. * */ public class TextSizePrefilterTest { private static final int ERROR_RETURN = 5; private static class SizeVerifyPostFilter implements PostFilter { private int size; private int returnValue = 0; private PrintWriter output; private int pageCount = 0; private int revCount = 0; private SizeVerifyPostFilter(int size, PrintWriter output) { this.size = size; this.output = output; } public boolean keepPage(PageType page) { output.printf("%10d %4d %s\n", pageCount, revCount, page.getTitle()); pageCount++; revCount = 0; return false; } public boolean keepRevision(RevisionType revision, PageType page) { if (Util.getTextSize(revision) > size) { output.printf("ERROR! Revision %d of page %d (%s) has size %d\n", revCount, pageCount, page.getTitle(), Util.getTextSize(revision)); returnValue = ERROR_RETURN; } revCount++; return false; } public int getReturnValue() { return returnValue; } } public static void main(String[] args) throws JAXBException, FileNotFoundException { if (args.length < 2) { System.err.println("Usage: zawilinskiTest.zawilinskiTest.TextSizePrefilterTest filename size [logfile [loglevel]]"); return; } final int size = Integer.parseInt(args[1]); int returnValue = 0; SimpleLog log; if (args.length >= 3) { int level = 0; if (args.length >= 4) { level = Integer.parseInt(args[3]); } log = new Log(args[2], level); } else { log = new SimpleLog(); } InputStream input = InputHelper.openMappedAndFilteredInputStreamOrQuit(args[0]); TextSizePrefilter tspf = new TextSizePrefilter(size, log); PrintWriter output = OutputHelper.openMappedWriterOrQuit("-", "utf-8", true); SizeVerifyPostFilter svpf = new SizeVerifyPostFilter(size, output); MediaWikiType root = PostFilteredMediaWikiLoader.load(input, log, svpf, tspf).getValue(); if (svpf.getReturnValue() == ERROR_RETURN ) { output.println("There were errors"); } output.close(); System.exit(svpf.getReturnValue()); } }
C#
UTF-8
5,096
2.921875
3
[]
no_license
using System; using Xenko.Engine; namespace VL.Xenko.Layer { /// <summary> /// Establishes a parent-child relationship between a parent and a child <see cref="Entity"/>. /// </summary> public sealed class EntityLink : IDisposable { readonly Entity parent; Entity child; public EntityLink(Entity parent) { this.parent = parent; } public void Update(Entity child) { Child = child; } public void Dispose() { Child = null; } public Entity Child { get => child; set { if (value != child) { if (child != null && child.GetParent() == parent) { // Unlink child.SetParent(null); child.Scene = null; child = null; } if (value != null && value.GetParent() == null) { // Link value.SetParent(parent); child = value; } } } } } /// <summary> /// Establishes a parent-child relationship between a parent <see cref="Scene"/> and a child <see cref="Entity"/>. /// </summary> public sealed class EntitySceneLink : IDisposable { readonly Scene parent; Entity child; public EntitySceneLink(Scene parent) { this.parent = parent; } public void Update(Entity child) { Child = child; } public void Dispose() { Child = null; } public Entity Child { get => child; set { if (value != child) { if (child != null && child.GetParent() == null && child.Scene == parent) { // Unlink child.Scene = null; child = null; } if (value != null && value.GetParent() == null && value.Scene == null) { // Link value.Scene = parent; child = value; } } } } } /// <summary> /// Establishes a parent-child relationship between a parent and a child <see cref="Scene"/>. /// </summary> public sealed class SceneLink : IDisposable { readonly Scene parent; Scene child; public SceneLink(Scene parent) { this.parent = parent; } public void Update(Scene child) { Child = child; } public void Dispose() { Child = null; } public Scene Child { get => child; set { if (value != child) { if (child != null && child.Parent == parent) { // Unlink child.Parent = null; child = null; } if (value != null && value.Parent == null) { // Link value.Parent = parent; child = value; } } } } } /// <summary> /// Establishes a link between a <see cref="EntityComponent"/> and its <see cref="Entity"/>. /// </summary> public sealed class ComponentLink : IDisposable { readonly Entity entity; EntityComponent component; public ComponentLink(Entity entity) { this.entity = entity; } public void Update(EntityComponent component) { Component = component; } public void Dispose() { Component = null; } public EntityComponent Component { get => component; set { if (value != component) { if (component != null && component.Entity == entity) { // Unlink entity.Remove(component); component = null; } if (value != null && value.Entity == null) { // Link entity.Add(value); component = value; } } } } } }
TypeScript
UTF-8
498
3.859375
4
[]
no_license
/** * 爬楼梯求的是多少种方法,而不是多少步 到前 n-1 n-2后 就是最终的方法数 * dp[i] 到第i步有多少种走法 * @param n */ function climbStairs(n: number): number { if (n <= 2) return n; let dp: number[] = new Array<number>(n + 1); dp[0] = 0 dp[1] = 1; dp[2] = 2; for (let i = 3; i <= n; ++i) { dp[i] = dp[i - 1] + dp[i - 2]; } return dp[n]; } let stairsCount = 4; console.log(climbStairs(stairsCount));
Python
UTF-8
729
2.828125
3
[]
no_license
def dfs(L,s,sum_): #레벨,시작점,해당 지점까지의 합 global count if L==k: # 종료지점 if sum_%m==0: # m의 배수이면 count+=1 # 카운트 else: for i in range(s,n): # 시작 인덱스 s부터 n-1까지 res[L]=a[i] # 해당 레벨에서 간택받은 숫자 dfs(L+1,i+1,sum_+a[i]) # 레벨 증가, 시작점 증가, 합 if __name__=="__main__": n,k=map(int,input().split()) # 정수의 갯수, 뽑는 수 a=list(map(int,input().split())) # n개의 정수 m=int(input()) # m res=[0]*k # 뽑히는수들 count=0 dfs(0,0,0) print(count)
JavaScript
UTF-8
2,750
2.890625
3
[]
no_license
function Slider () {} Slider.prototype.gestures = function() { var _this = this; this.touchstartX = 0; this.touchstartY = 0; this.touchendX = 0; this.touchendY = 0; this.container.addEventListener('touchstart', function(event) { _this.touchstartX = event.changedTouches[0].screenX; _this.touchstartY = event.changedTouches[0].screenY; }, false); this.container.addEventListener('touchend', function(event) { _this.touchendX = event.changedTouches[0].screenX; _this.touchendY = event.changedTouches[0].screenY; _this.handleGesture(); }, false); this.container.addEventListener('mousedown', function(event) { event.preventDefault(); _this.touchstartX = event.screenX; _this.touchstartY = event.screenY; }, false); this.container.addEventListener('mouseup', function(event) { _this.touchendX = event.screenX; _this.touchendY = event.screenY; _this.handleGesture(); }, false); }; Slider.prototype.handleGesture = function () { if (this.touchendX > this.touchstartX) { this.prev(); } if (this.touchendX < this.touchstartX) { this.next(); } }; Slider.prototype.render = function () { var _this = this; var container = document.createElement('div'); container.className = 'slider'; function newImage () { this.image = document.createElement('img'); this.image.className = 'slider-img'; this.image.width = 500; this.image.height = 350; this.image.alt = "slider-image"; this.image.src = _this.images[0]; } var currentImage = new newImage(); currentImage.image.classList.add('current-image'); container.appendChild(currentImage.image); var prevImage = new newImage(); prevImage.image.src = this.images[this.totalImages - 1]; prevImage.image.classList.add('hidden', 'prev-image'); container.appendChild(prevImage.image); var nextImage = new newImage(); nextImage.image.src = this.images[this.currentIndex + 1]; nextImage.image.classList.add('hidden', 'next-image'); container.appendChild(nextImage.image); this.mainNode.appendChild(container); }; /*To remove slider app*/ Slider.prototype.destroy = function () { if (this.autoSliderInterval) { clearInterval(this.autoSliderInterval); } this.container.remove(); }; Slider.prototype.autoSlider = function (config) { if (config.mode === 'auto' || config.mode === 'automanual') { this.autoSliderInterval = setInterval(this.next.bind(this), config.swipeDelay); } }; Slider.prototype.isLast = function () { if (this.currentIndex === this.totalImages - 1) { return 0; } else { return this.currentIndex + 1; } }; Slider.prototype.isFirst = function () { if (this.currentIndex === 0) { return this.totalImages - 1; } else { return this.currentIndex - 1; } };
Java
UTF-8
338
2.140625
2
[]
no_license
package com.example.firstspringboot.reposity; import com.example.firstspringboot.domain.Girl; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; //其中第二个参数为Id的类型 public interface GirlRepository extends JpaRepository<Girl,Integer> { public List<Girl> findByAge(Integer age); }
Java
UTF-8
1,134
3.40625
3
[]
no_license
package org.billing.jlab.factory.pizzas; /** * Клиент фабрики. * Класс который способен определять какую пиццу он будет готовить и далее её готовить * PazzaStore сохраняет ссылку на фабрику в конструкторе, далее, orderPizza обращается к фабрике * с запросом на создание объекта, передавая тип заказа. */ public class PizzaStore { SimplePizzaFactory factory; // класс, имеющий фабричный метод public PizzaStore(SimplePizzaFactory factory) { this.factory = factory; } /** * Метод приготовления пиццы * @param type - тип приготовляемой пиццы: (cheese, pepperoni, clam, veggie) * @return экземпляр объекта Pizza, который приготовили */ public Pizza orderPizza(String type) { Pizza pizza; pizza = factory.createPizza(type); pizza.prepare(); pizza.bake(); pizza.cut(); pizza.box(); return pizza; } }
PHP
UTF-8
3,371
3.078125
3
[]
no_license
<?php /** * Created by JetBrains PhpStorm. * User: zhalnin * Date: 07.12.12 * Time: 15:20 * To change this template use File | Settings | File Templates. */ /** * Root class for inheritance */ abstract class Field { // Name of control element protected $_name; // Type of control element protected $_type; // Title of control element on left protected $_caption; // Value of control element protected $_value; // Required control element for filling protected $_is_required; // String for additional parameters protected $_parameters; // Prompt protected $_help; // Reference for prompt protected $_help_url; // CSS class public $css_class; // CSS style public $css_style; /** * Construct of class. */ public function __construct($name, $type, $caption, $is_required = false, $value = "", $parameters = "", $help = "", $help_url = "") { $this->_name = $this->_encodestring($name); $this->_type = $type; $this->_caption = $caption; $this->_is_required = $is_required; $this->_value = $value; $this->_parameters = $parameters; $this->_help = $help; $this->_help_url = $help_url; } /** * Check correct of typed info. * @return "" or error */ abstract function check(); /** * Public html form to page. * @return array */ abstract function get_html(); /** * Admittance to protected and private control elements. * (only read) * @param $key * @return $key */ public function __get($key) { $protected_property = "_".$key; if(property_exists($this,$protected_property)) { if(isset($this->$protected_property)) return $this->$protected_property; else { throw new ExceptionMember($key, "Экземпляр ".__CLASS__."::$key не существует!"); } } else { throw new Exception("Свойство ".__CLASS__."::$protected_property не найдено!"); } } /** * To translate russian text to translit * @param $st * @return $st */ protected function _mb_strtr($str, $from, $to) { return str_replace($this->_mb_str_split($from), $this->_mb_str_split($to), $str); } protected function _mb_str_split($str) { return preg_split('~~u', $str, null, PREG_SPLIT_NO_EMPTY); } protected function _encodestring($st) { // Replace single symbol. $st= $this->_mb_strtr($st,"абвгдезийклмнопрстуфхъы", "abvgdezijklmnoprstufh#y"); $st= $this->_mb_strtr($st,"АБВГДEЗИЙКЛМНОПРСТУФХЪЫ", "ABVGDEZIJKLMNOPRSTUFH#Y"); // Replace multiple symbol. $st=strtr($st, array( "ж"=>"zh","ц"=>"ts","ч"=>"ch","ш"=>"sh", "щ"=>"shch","ь"=>"'","ю"=>"yu","я"=>"ya", "Ж"=>"ZH","Ц"=>"TS","Ч"=>"CH","Ш"=>"SH", "Щ"=>"SHCH","Ь"=>"'","Ю"=>"YU","Я"=>"YA", "э"=>"je", "Э"=>"JE", "ё"=>"jo", "Ё"=>"JO" ) ); // Return result. return $st; } } ?>
Java
UTF-8
31,443
2.796875
3
[]
no_license
package java.util.stream; import java.util.*; import java.util.function.*; class SpinedBuffer<E> extends AbstractSpinedBuffer implements Consumer<E>, Iterable<E> { protected E[] curChunk; protected E[][] spine; private static final int SPLITERATOR_CHARACTERISTICS = 16464; SpinedBuffer(final int n) { super(n); this.curChunk = (E[])new Object[1 << this.initialChunkPower]; } SpinedBuffer() { this.curChunk = (E[])new Object[1 << this.initialChunkPower]; } protected long capacity() { return (this.spineIndex == 0) ? this.curChunk.length : (this.priorElementCount[this.spineIndex] + this.spine[this.spineIndex].length); } private void inflateSpine() { if (this.spine == null) { this.spine = (E[][])new Object[8][]; this.priorElementCount = new long[8]; this.spine[0] = this.curChunk; } } protected final void ensureCapacity(final long n) { long capacity = this.capacity(); if (n > capacity) { this.inflateSpine(); int chunkSize; for (int n2 = this.spineIndex + 1; n > capacity; capacity += chunkSize, ++n2) { if (n2 >= this.spine.length) { final int n3 = this.spine.length * 2; this.spine = Arrays.copyOf(this.spine, n3); this.priorElementCount = Arrays.copyOf(this.priorElementCount, n3); } chunkSize = this.chunkSize(n2); this.spine[n2] = (E[])new Object[chunkSize]; this.priorElementCount[n2] = this.priorElementCount[n2 - 1] + this.spine[n2 - 1].length; } } } protected void increaseCapacity() { this.ensureCapacity(this.capacity() + 1L); } public E get(final long n) { if (this.spineIndex == 0) { if (n < this.elementIndex) { return this.curChunk[(int)n]; } throw new IndexOutOfBoundsException(Long.toString(n)); } else { if (n >= this.count()) { throw new IndexOutOfBoundsException(Long.toString(n)); } for (int i = 0; i <= this.spineIndex; ++i) { if (n < this.priorElementCount[i] + this.spine[i].length) { return this.spine[i][(int)(n - this.priorElementCount[i])]; } } throw new IndexOutOfBoundsException(Long.toString(n)); } } public void copyInto(final E[] array, int n) { final long n2 = n + this.count(); if (n2 > array.length || n2 < n) { throw new IndexOutOfBoundsException("does not fit"); } if (this.spineIndex == 0) { System.arraycopy(this.curChunk, 0, array, n, this.elementIndex); } else { for (int i = 0; i < this.spineIndex; ++i) { System.arraycopy(this.spine[i], 0, array, n, this.spine[i].length); n += this.spine[i].length; } if (this.elementIndex > 0) { System.arraycopy(this.curChunk, 0, array, n, this.elementIndex); } } } public E[] asArray(final IntFunction<E[]> intFunction) { final long count = this.count(); if (count >= 2147483639L) { throw new IllegalArgumentException("Stream size exceeds max array size"); } final E[] array = intFunction.apply((int)count); this.copyInto(array, 0); return array; } @Override public void clear() { if (this.spine != null) { this.curChunk = this.spine[0]; for (int i = 0; i < this.curChunk.length; ++i) { this.curChunk[i] = null; } this.spine = null; this.priorElementCount = null; } else { for (int j = 0; j < this.elementIndex; ++j) { this.curChunk[j] = null; } } this.elementIndex = 0; this.spineIndex = 0; } @Override public Iterator<E> iterator() { return Spliterators.iterator(this.spliterator()); } @Override public void forEach(final Consumer<? super E> consumer) { for (int i = 0; i < this.spineIndex; ++i) { final E[] array = this.spine[i]; for (int length = array.length, j = 0; j < length; ++j) { consumer.accept(array[j]); } } for (int k = 0; k < this.elementIndex; ++k) { consumer.accept(this.curChunk[k]); } } @Override public void accept(final E e) { if (this.elementIndex == this.curChunk.length) { this.inflateSpine(); if (this.spineIndex + 1 >= this.spine.length || this.spine[this.spineIndex + 1] == null) { this.increaseCapacity(); } this.elementIndex = 0; ++this.spineIndex; this.curChunk = this.spine[this.spineIndex]; } this.curChunk[this.elementIndex++] = e; } @Override public String toString() { final ArrayList<Object> list = new ArrayList<Object>(); this.forEach(list::add); return "SpinedBuffer:" + list.toString(); } @Override public Spliterator<E> spliterator() { class Splitr implements Spliterator<E> { int splSpineIndex = 0; final int lastSpineIndex = SpinedBuffer.this.spineIndex; int splElementIndex = 0; final int lastSpineElementFence = SpinedBuffer.this.elementIndex; E[] splChunk; Splitr(final int lastSpineIndex, final int splElementIndex, final int lastSpineElementFence) { assert splSpineIndex == 0 && lastSpineIndex == 0; this.splChunk = ((SpinedBuffer.this.spine == null) ? SpinedBuffer.this.curChunk : SpinedBuffer.this.spine[splSpineIndex]); } @Override public long estimateSize() { return (this.splSpineIndex == this.lastSpineIndex) ? (this.lastSpineElementFence - (long)this.splElementIndex) : (SpinedBuffer.this.priorElementCount[this.lastSpineIndex] + this.lastSpineElementFence - SpinedBuffer.this.priorElementCount[this.splSpineIndex] - this.splElementIndex); } @Override public int characteristics() { return 16464; } @Override public boolean tryAdvance(final Consumer<? super E> consumer) { Objects.requireNonNull(consumer); if (this.splSpineIndex < this.lastSpineIndex || (this.splSpineIndex == this.lastSpineIndex && this.splElementIndex < this.lastSpineElementFence)) { consumer.accept(this.splChunk[this.splElementIndex++]); if (this.splElementIndex == this.splChunk.length) { this.splElementIndex = 0; ++this.splSpineIndex; if (SpinedBuffer.this.spine != null && this.splSpineIndex <= this.lastSpineIndex) { this.splChunk = SpinedBuffer.this.spine[this.splSpineIndex]; } } return true; } return false; } @Override public void forEachRemaining(final Consumer<? super E> consumer) { Objects.requireNonNull(consumer); if (this.splSpineIndex < this.lastSpineIndex || (this.splSpineIndex == this.lastSpineIndex && this.splElementIndex < this.lastSpineElementFence)) { int i = this.splElementIndex; for (int j = this.splSpineIndex; j < this.lastSpineIndex; ++j) { for (E[] array = SpinedBuffer.this.spine[j]; i < array.length; ++i) { consumer.accept(array[i]); } i = 0; } final E[] array2 = (this.splSpineIndex == this.lastSpineIndex) ? this.splChunk : SpinedBuffer.this.spine[this.lastSpineIndex]; while (i < this.lastSpineElementFence) { consumer.accept(array2[i]); ++i; } this.splSpineIndex = this.lastSpineIndex; this.splElementIndex = this.lastSpineElementFence; } } @Override public Spliterator<E> trySplit() { if (this.splSpineIndex < this.lastSpineIndex) { final Splitr splitr = new Splitr(this.splSpineIndex, this.lastSpineIndex - 1, this.splElementIndex, SpinedBuffer.this.spine[this.lastSpineIndex - 1].length); this.splSpineIndex = this.lastSpineIndex; this.splElementIndex = 0; this.splChunk = SpinedBuffer.this.spine[this.splSpineIndex]; return splitr; } if (this.splSpineIndex != this.lastSpineIndex) { return null; } final int n = (this.lastSpineElementFence - this.splElementIndex) / 2; if (n == 0) { return null; } final Spliterator<E> spliterator = Arrays.spliterator(this.splChunk, this.splElementIndex, this.splElementIndex + n); this.splElementIndex += n; return spliterator; } } return new Splitr(SpinedBuffer.this.spineIndex, SpinedBuffer.this.elementIndex); } static class OfDouble extends OfPrimitive<Double, double[], DoubleConsumer> implements DoubleConsumer { OfDouble() { } OfDouble(final int n) { super(n); } @Override public void forEach(final Consumer<? super Double> consumer) { if (consumer instanceof DoubleConsumer) { ((OfPrimitive<E, T_ARR, DoubleConsumer>)this).forEach((DoubleConsumer)consumer); } else { if (Tripwire.ENABLED) { Tripwire.trip(this.getClass(), "{0} calling SpinedBuffer.OfDouble.forEach(Consumer)"); } this.spliterator().forEachRemaining(consumer); } } @Override protected double[][] newArrayArray(final int n) { return new double[n][]; } @Override public double[] newArray(final int n) { return new double[n]; } @Override protected int arrayLength(final double[] array) { return array.length; } @Override protected void arrayForEach(final double[] array, final int n, final int n2, final DoubleConsumer doubleConsumer) { for (int i = n; i < n2; ++i) { doubleConsumer.accept(array[i]); } } @Override public void accept(final double n) { this.preAccept(); ((double[])(Object)this.curChunk)[this.elementIndex++] = n; } public double get(final long n) { final int chunk = this.chunkFor(n); if (this.spineIndex == 0 && chunk == 0) { return ((double[])(Object)this.curChunk)[(int)n]; } return ((double[][])(Object)this.spine)[chunk][(int)(n - this.priorElementCount[chunk])]; } @Override public PrimitiveIterator.OfDouble iterator() { return Spliterators.iterator(this.spliterator()); } @Override public Spliterator.OfDouble spliterator() { class Splitr extends BaseSpliterator<Spliterator.OfDouble> implements Spliterator.OfDouble { Splitr(final int n2, final int n3, final int n4) { super(n, n2, n3, n4); } @Override Splitr newSpliterator(final int n, final int n2, final int n3, final int n4) { return new Splitr(n, n2, n3, n4); } void arrayForOne(final double[] array, final int n, final DoubleConsumer doubleConsumer) { doubleConsumer.accept(array[n]); } Spliterator.OfDouble arraySpliterator(final double[] array, final int n, final int n2) { return Arrays.spliterator(array, n, n + n2); } } return new Splitr(0, this.spineIndex, 0, this.elementIndex); } @Override public String toString() { final double[] array = ((OfPrimitive<E, double[], T_CONS>)this).asPrimitiveArray(); if (array.length < 200) { return String.format("%s[length=%d, chunks=%d]%s", this.getClass().getSimpleName(), array.length, this.spineIndex, Arrays.toString(array)); } return String.format("%s[length=%d, chunks=%d]%s...", this.getClass().getSimpleName(), array.length, this.spineIndex, Arrays.toString(Arrays.copyOf(array, 200))); } } abstract static class OfPrimitive<E, T_ARR, T_CONS> extends AbstractSpinedBuffer implements Iterable<E> { T_ARR curChunk; T_ARR[] spine; OfPrimitive(final int n) { super(n); this.curChunk = this.newArray(1 << this.initialChunkPower); } OfPrimitive() { this.curChunk = this.newArray(1 << this.initialChunkPower); } @Override public abstract Iterator<E> iterator(); @Override public abstract void forEach(final Consumer<? super E> p0); protected abstract T_ARR[] newArrayArray(final int p0); public abstract T_ARR newArray(final int p0); protected abstract int arrayLength(final T_ARR p0); protected abstract void arrayForEach(final T_ARR p0, final int p1, final int p2, final T_CONS p3); protected long capacity() { return (this.spineIndex == 0) ? this.arrayLength(this.curChunk) : (this.priorElementCount[this.spineIndex] + this.arrayLength(this.spine[this.spineIndex])); } private void inflateSpine() { if (this.spine == null) { this.spine = this.newArrayArray(8); this.priorElementCount = new long[8]; this.spine[0] = this.curChunk; } } protected final void ensureCapacity(final long n) { long capacity = this.capacity(); if (n > capacity) { this.inflateSpine(); int chunkSize; for (int n2 = this.spineIndex + 1; n > capacity; capacity += chunkSize, ++n2) { if (n2 >= this.spine.length) { final int n3 = this.spine.length * 2; this.spine = Arrays.copyOf(this.spine, n3); this.priorElementCount = Arrays.copyOf(this.priorElementCount, n3); } chunkSize = this.chunkSize(n2); this.spine[n2] = this.newArray(chunkSize); this.priorElementCount[n2] = this.priorElementCount[n2 - 1] + this.arrayLength(this.spine[n2 - 1]); } } } protected void increaseCapacity() { this.ensureCapacity(this.capacity() + 1L); } protected int chunkFor(final long n) { if (this.spineIndex == 0) { if (n < this.elementIndex) { return 0; } throw new IndexOutOfBoundsException(Long.toString(n)); } else { if (n >= this.count()) { throw new IndexOutOfBoundsException(Long.toString(n)); } for (int i = 0; i <= this.spineIndex; ++i) { if (n < this.priorElementCount[i] + this.arrayLength(this.spine[i])) { return i; } } throw new IndexOutOfBoundsException(Long.toString(n)); } } public void copyInto(final T_ARR t_ARR, int n) { final long n2 = n + this.count(); if (n2 > this.arrayLength(t_ARR) || n2 < n) { throw new IndexOutOfBoundsException("does not fit"); } if (this.spineIndex == 0) { System.arraycopy(this.curChunk, 0, t_ARR, n, this.elementIndex); } else { for (int i = 0; i < this.spineIndex; ++i) { System.arraycopy(this.spine[i], 0, t_ARR, n, this.arrayLength(this.spine[i])); n += this.arrayLength(this.spine[i]); } if (this.elementIndex > 0) { System.arraycopy(this.curChunk, 0, t_ARR, n, this.elementIndex); } } } public T_ARR asPrimitiveArray() { final long count = this.count(); if (count >= 2147483639L) { throw new IllegalArgumentException("Stream size exceeds max array size"); } final T_ARR array = this.newArray((int)count); this.copyInto(array, 0); return array; } protected void preAccept() { if (this.elementIndex == this.arrayLength(this.curChunk)) { this.inflateSpine(); if (this.spineIndex + 1 >= this.spine.length || this.spine[this.spineIndex + 1] == null) { this.increaseCapacity(); } this.elementIndex = 0; ++this.spineIndex; this.curChunk = this.spine[this.spineIndex]; } } @Override public void clear() { if (this.spine != null) { this.curChunk = this.spine[0]; this.spine = null; this.priorElementCount = null; } this.elementIndex = 0; this.spineIndex = 0; } public void forEach(final T_CONS t_CONS) { for (int i = 0; i < this.spineIndex; ++i) { this.arrayForEach(this.spine[i], 0, this.arrayLength(this.spine[i]), t_CONS); } this.arrayForEach(this.curChunk, 0, this.elementIndex, t_CONS); } abstract class BaseSpliterator<T_SPLITR extends Spliterator.OfPrimitive<E, T_CONS, T_SPLITR>> implements Spliterator.OfPrimitive<E, T_CONS, T_SPLITR> { int splSpineIndex; final int lastSpineIndex; int splElementIndex; final int lastSpineElementFence; T_ARR splChunk; BaseSpliterator(final int splSpineIndex, final int lastSpineIndex, final int splElementIndex, final int lastSpineElementFence) { this.splSpineIndex = splSpineIndex; this.lastSpineIndex = lastSpineIndex; this.splElementIndex = splElementIndex; this.lastSpineElementFence = lastSpineElementFence; assert splSpineIndex == 0 && lastSpineIndex == 0; this.splChunk = ((SpinedBuffer.OfPrimitive.this.spine == null) ? SpinedBuffer.OfPrimitive.this.curChunk : SpinedBuffer.OfPrimitive.this.spine[splSpineIndex]); } abstract T_SPLITR newSpliterator(final int p0, final int p1, final int p2, final int p3); abstract void arrayForOne(final T_ARR p0, final int p1, final T_CONS p2); abstract T_SPLITR arraySpliterator(final T_ARR p0, final int p1, final int p2); @Override public long estimateSize() { return (this.splSpineIndex == this.lastSpineIndex) ? (this.lastSpineElementFence - (long)this.splElementIndex) : (SpinedBuffer.OfPrimitive.this.priorElementCount[this.lastSpineIndex] + this.lastSpineElementFence - SpinedBuffer.OfPrimitive.this.priorElementCount[this.splSpineIndex] - this.splElementIndex); } @Override public int characteristics() { return 16464; } @Override public boolean tryAdvance(final T_CONS t_CONS) { Objects.requireNonNull(t_CONS); if (this.splSpineIndex < this.lastSpineIndex || (this.splSpineIndex == this.lastSpineIndex && this.splElementIndex < this.lastSpineElementFence)) { this.arrayForOne(this.splChunk, this.splElementIndex++, t_CONS); if (this.splElementIndex == SpinedBuffer.OfPrimitive.this.arrayLength(this.splChunk)) { this.splElementIndex = 0; ++this.splSpineIndex; if (SpinedBuffer.OfPrimitive.this.spine != null && this.splSpineIndex <= this.lastSpineIndex) { this.splChunk = SpinedBuffer.OfPrimitive.this.spine[this.splSpineIndex]; } } return true; } return false; } @Override public void forEachRemaining(final T_CONS t_CONS) { Objects.requireNonNull(t_CONS); if (this.splSpineIndex < this.lastSpineIndex || (this.splSpineIndex == this.lastSpineIndex && this.splElementIndex < this.lastSpineElementFence)) { int splElementIndex = this.splElementIndex; for (int i = this.splSpineIndex; i < this.lastSpineIndex; ++i) { final T_ARR t_ARR = SpinedBuffer.OfPrimitive.this.spine[i]; SpinedBuffer.OfPrimitive.this.arrayForEach(t_ARR, splElementIndex, SpinedBuffer.OfPrimitive.this.arrayLength(t_ARR), t_CONS); splElementIndex = 0; } SpinedBuffer.OfPrimitive.this.arrayForEach((this.splSpineIndex == this.lastSpineIndex) ? this.splChunk : SpinedBuffer.OfPrimitive.this.spine[this.lastSpineIndex], splElementIndex, this.lastSpineElementFence, t_CONS); this.splSpineIndex = this.lastSpineIndex; this.splElementIndex = this.lastSpineElementFence; } } @Override public T_SPLITR trySplit() { if (this.splSpineIndex < this.lastSpineIndex) { final Spliterator.OfPrimitive<E, T_CONS, T_SPLITR> spliterator = (Spliterator.OfPrimitive<E, T_CONS, T_SPLITR>)this.newSpliterator(this.splSpineIndex, this.lastSpineIndex - 1, this.splElementIndex, SpinedBuffer.OfPrimitive.this.arrayLength(SpinedBuffer.OfPrimitive.this.spine[this.lastSpineIndex - 1])); this.splSpineIndex = this.lastSpineIndex; this.splElementIndex = 0; this.splChunk = SpinedBuffer.OfPrimitive.this.spine[this.splSpineIndex]; return (T_SPLITR)spliterator; } if (this.splSpineIndex != this.lastSpineIndex) { return null; } final int n = (this.lastSpineElementFence - this.splElementIndex) / 2; if (n == 0) { return null; } final Spliterator.OfPrimitive<E, T_CONS, T_SPLITR> arraySpliterator = (Spliterator.OfPrimitive<E, T_CONS, T_SPLITR>)this.arraySpliterator(this.splChunk, this.splElementIndex, n); this.splElementIndex += n; return (T_SPLITR)arraySpliterator; } } } static class OfInt extends OfPrimitive<Integer, int[], IntConsumer> implements IntConsumer { OfInt() { } OfInt(final int n) { super(n); } @Override public void forEach(final Consumer<? super Integer> consumer) { if (consumer instanceof IntConsumer) { ((OfPrimitive<E, T_ARR, IntConsumer>)this).forEach((IntConsumer)consumer); } else { if (Tripwire.ENABLED) { Tripwire.trip(this.getClass(), "{0} calling SpinedBuffer.OfInt.forEach(Consumer)"); } this.spliterator().forEachRemaining(consumer); } } @Override protected int[][] newArrayArray(final int n) { return new int[n][]; } @Override public int[] newArray(final int n) { return new int[n]; } @Override protected int arrayLength(final int[] array) { return array.length; } @Override protected void arrayForEach(final int[] array, final int n, final int n2, final IntConsumer intConsumer) { for (int i = n; i < n2; ++i) { intConsumer.accept(array[i]); } } @Override public void accept(final int n) { this.preAccept(); ((int[])(Object)this.curChunk)[this.elementIndex++] = n; } public int get(final long n) { final int chunk = this.chunkFor(n); if (this.spineIndex == 0 && chunk == 0) { return ((int[])(Object)this.curChunk)[(int)n]; } return ((int[][])(Object)this.spine)[chunk][(int)(n - this.priorElementCount[chunk])]; } @Override public PrimitiveIterator.OfInt iterator() { return Spliterators.iterator(this.spliterator()); } @Override public Spliterator.OfInt spliterator() { class Splitr extends BaseSpliterator<Spliterator.OfInt> implements Spliterator.OfInt { Splitr(final int n2, final int n3, final int n4) { super(n, n2, n3, n4); } @Override Splitr newSpliterator(final int n, final int n2, final int n3, final int n4) { return new Splitr(n, n2, n3, n4); } void arrayForOne(final int[] array, final int n, final IntConsumer intConsumer) { intConsumer.accept(array[n]); } Spliterator.OfInt arraySpliterator(final int[] array, final int n, final int n2) { return Arrays.spliterator(array, n, n + n2); } } return new Splitr(0, this.spineIndex, 0, this.elementIndex); } @Override public String toString() { final int[] array = ((OfPrimitive<E, int[], T_CONS>)this).asPrimitiveArray(); if (array.length < 200) { return String.format("%s[length=%d, chunks=%d]%s", this.getClass().getSimpleName(), array.length, this.spineIndex, Arrays.toString(array)); } return String.format("%s[length=%d, chunks=%d]%s...", this.getClass().getSimpleName(), array.length, this.spineIndex, Arrays.toString(Arrays.copyOf(array, 200))); } } static class OfLong extends OfPrimitive<Long, long[], LongConsumer> implements LongConsumer { OfLong() { } OfLong(final int n) { super(n); } @Override public void forEach(final Consumer<? super Long> consumer) { if (consumer instanceof LongConsumer) { ((OfPrimitive<E, T_ARR, LongConsumer>)this).forEach((LongConsumer)consumer); } else { if (Tripwire.ENABLED) { Tripwire.trip(this.getClass(), "{0} calling SpinedBuffer.OfLong.forEach(Consumer)"); } this.spliterator().forEachRemaining(consumer); } } @Override protected long[][] newArrayArray(final int n) { return new long[n][]; } @Override public long[] newArray(final int n) { return new long[n]; } @Override protected int arrayLength(final long[] array) { return array.length; } @Override protected void arrayForEach(final long[] array, final int n, final int n2, final LongConsumer longConsumer) { for (int i = n; i < n2; ++i) { longConsumer.accept(array[i]); } } @Override public void accept(final long n) { this.preAccept(); ((long[])(Object)this.curChunk)[this.elementIndex++] = n; } public long get(final long n) { final int chunk = this.chunkFor(n); if (this.spineIndex == 0 && chunk == 0) { return ((long[])(Object)this.curChunk)[(int)n]; } return ((long[][])(Object)this.spine)[chunk][(int)(n - this.priorElementCount[chunk])]; } @Override public PrimitiveIterator.OfLong iterator() { return Spliterators.iterator(this.spliterator()); } @Override public Spliterator.OfLong spliterator() { class Splitr extends BaseSpliterator<Spliterator.OfLong> implements Spliterator.OfLong { Splitr(final int n2, final int n3, final int n4) { super(n, n2, n3, n4); } @Override Splitr newSpliterator(final int n, final int n2, final int n3, final int n4) { return new Splitr(n, n2, n3, n4); } void arrayForOne(final long[] array, final int n, final LongConsumer longConsumer) { longConsumer.accept(array[n]); } Spliterator.OfLong arraySpliterator(final long[] array, final int n, final int n2) { return Arrays.spliterator(array, n, n + n2); } } return new Splitr(0, this.spineIndex, 0, this.elementIndex); } @Override public String toString() { final long[] array = ((OfPrimitive<E, long[], T_CONS>)this).asPrimitiveArray(); if (array.length < 200) { return String.format("%s[length=%d, chunks=%d]%s", this.getClass().getSimpleName(), array.length, this.spineIndex, Arrays.toString(array)); } return String.format("%s[length=%d, chunks=%d]%s...", this.getClass().getSimpleName(), array.length, this.spineIndex, Arrays.toString(Arrays.copyOf(array, 200))); } } }
Python
UTF-8
450
2.640625
3
[]
no_license
import cv2 import numpy as np import scipy img = cv2.imread(r'C:\Users\jclat\OneDrive\Desktop\353\sudoku.jpg') gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) edges = cv2.Canny(gray,50,150,apertureSize = 3) minLineLength = 100 maxLineGap = 10 lines = cv2.HoughLinesP(edges,1,np.pi/180,200,0,0) for x1,y1,x2,y2 in lines[0]: cv2.line(img,(x1,y1),(x2,y2),(0,255,0),2) cv2.imwrite(r'C:\Users\jclat\OneDrive\Desktop\353\output2.jpg',img)
C#
UTF-8
469
2.765625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CodeReviewByMilka { class Animal { public Animal() :this("no name", 0) { } public Animal(string name, int numberOfLegs) { Name = name; NumberOfLegs = numberOfLegs; } public string Name { get; set; } public int NumberOfLegs { get; set; } } }
C++
UTF-8
1,664
2.71875
3
[]
no_license
#pragma once #include "Handler.h" class Handlers { public: Handlers(); virtual ~Handlers(); /* Opens a decoder. * 'filename' - file to open. * Returns the decoder, or nullptr if the stream could not be opened. */ Decoder::Ptr OpenDecoder(const std::wstring& filename) const; // Reads 'tags' from 'filename', returning true if the tags were read. bool GetTags(const std::wstring& filename, Tags& tags) const; // Writes 'tags' to 'filename', returning true if the tags were written. bool SetTags(const std::wstring& fileanme, const Tags& tags) const; // Returns all the file extensions supported by the decoders, as set of lowercase strings. std::set<std::wstring> GetAllSupportedFileExtensions() const; // Returns the BASS library version. std::wstring GetBaseVersion() const; // Adds a 'handler'. void AddHandler(Handler::Ptr handler); // Returns the available encoders. Handler::List GetEncoder() const; /* Open a encoder matching the 'desciption'. * Returns the encoder, or nullptr if an encoder could not opened. */ Encoder::Ptr OpenEncoder(const std::wstring& description) const; // Called when the application 'settings' have changed. void SettingsChanged(Settings& settings) const; // Initialises the handlers with the application 'settings'. void Init(Settings& settings); private: // Returns a decoder handler supported by the 'filename' extension, or nullptr of there was no match. Handler::Ptr FindDecoderHandler(const std::wstring& filename) const; // Available Handlers. Handler::List m_Handlers; // Available decoders. Handler::List m_Decoders; // Available encoders. Handler::List m_Encoders; };
JavaScript
UTF-8
3,451
2.640625
3
[]
no_license
Page({ /** * 页面的初始数据 */ data: { bookInfo: {}, bookCommentList: [], isBuyBook: false, downloadBoolFilePercent: 0 }, /** * 生命周期函数--监听页面加载 */ onLoad: function(options) { // 初始化书籍信息 const bookInfo = JSON.parse(options.bookInfo) // 初始化书籍评论 let bookCommentList = []; const allBookCommentList = wx.getStorageSync('bookCommentList'); if (allBookCommentList) { const _bookCommentList = allBookCommentList[`book-${bookInfo.id}`]; if (_bookCommentList) { bookCommentList = _bookCommentList; } }; // 初始化书籍是否已经购买 let isBuyBook = false; const buyBookList = wx.getStorageSync('buyBookList'); if (buyBookList) { isBuyBook = buyBookList[`book-${bookInfo.id}`] ? true : false; } this.setData({ bookInfo, bookCommentList, isBuyBook }); }, /** * 生命周期函数--监听页面显示 */ onShow: function () { // 初始化书籍评论 let bookCommentList = []; const allBookCommentList = wx.getStorageSync('bookCommentList'); if (allBookCommentList) { const _bookCommentList = allBookCommentList[`book-${this.data.bookInfo.id}`]; if (_bookCommentList) { bookCommentList = _bookCommentList; } }; this.setData({ bookCommentList }); }, buyBook() { wx.showModal({ title: '提示', content: '确定用1积分购买此书?', showCancel: true, success: (res) => { if (res.confirm) { this.doBuyBook(); } else { // 取消购买 } } }) }, doBuyBook() { // 请求服务端购买 // ... wx.showToast({ title: '兑换成功', icon: 'success', duration: 1500, mask: true }); // 标识用户已购买 this.setData({ isBuyBook: true }); let buyBookList = wx.getStorageSync('buyBookList'); if (buyBookList === '') { buyBookList = {}; } buyBookList[`book-${this.data.bookInfo.id}`] = this.data.bookInfo; wx.setStorageSync('buyBookList', buyBookList); }, readBook() { const bookFileUrl = 'https://yyccyy.com/wp-content/uploads/2018/12/compressed.tracemonkey-pldi-09.pdf'; // 下载书籍 const downloadBookFile = wx.downloadFile({ url: bookFileUrl, success: (res) => { console.log('文档下载成功'); // 隐藏下载进度条 this.setData({ downloadBoolFilePercent: 0 }); // 打开本地文档 wx.openDocument({ filePath: res.tempFilePath, success: function (res) { console.log('打开本地文档成功') }, fail: function (error) { console.log('打开本地文档失败') console.log(error); } }); }, fail: function (error) { console.log('文档下载失败') console.log(error); } }); // 更新下载进度 downloadBookFile.onProgressUpdate(res => { this.setData({ downloadBoolFilePercent: res.progress }); }); }, toBookComment() { // 将书籍信息拼接到 url 后面 let bookDetailUrl = `/page/comment/comment?bookInfo=${JSON.stringify(this.data.bookInfo)}`; wx.navigateTo({ url: bookDetailUrl }); } })
PHP
UTF-8
9,628
2.546875
3
[]
no_license
//items.php (Page 1) <?php require_once 'itemsfunction.php'; // array of images $photos =array("<img src = 'kakashi.jpg' width='300' height='300'>", "<img src = 'allmight.jpg' width='300' height='300'>", "<img src = 'simondominic.jpg' width='300' height='300'>", "<img src = 'mlazi.jpg' width='300' height='300'>", "<img src = 'Pokemon.jpg' width='300' height='300'>", "<img src = 'dragon.jpg' width='300' height='300'>", "<img src = 'ich.jpg' width='300' height='300'>", "<img src = 'spider.jpg' width='300' height='300'>", "<img src = 'loco.jpg' width='300' height='300'>", "<img src = 'beads.jpg' width='300' height='300'>", ); //array of items to be sold ($is,$product_name,$price,$description) $items = [ '1' => new Item(0,'Naruto Shippuden', 4.5,'T-Shirt','Watercolor T-Shirt of Kakashi Hatake, the coolest, most kickass ninja of the Hidden-leaf village. ',$photos[0]), '2' => new Item(1,'My Hero Academia', 12.70, 'T-Shirt','Black All Might T-Shirt. A true hero is one who overcomes lifes misfortunes',$photos[1]), '3' => new Item(3,'Won & Only - EP',12.00,'Digital EP','Korean born rapper Simon Dominic has returned with an amazing EP',$photos[2]), '4' => new Item(4,'Mlazi Milano', 19.00, 'Digital Album','South African born rapper Okmalumkoolkat he is so cryptic and smart about his choice of words, bringing a balance between his style, flow and depth of his lines. Perhaps the best album of 2017.',$photos[3]), '5' => new Item(5,'Pokemon', 5.00, 'Key Chain','Size: 1 inch Diameter Design, 2.5 inch Chain and Ring',$photos[4]), '6' => new Item(6,'Dragonball Super', 5.00, 'Key Chain','Size: 1 inch Diameter Design, 2.5 inch Chain and Ring',$photos[5]), '7' => new Item(7,'Icha Icha Paradise', 20.00, 'Paperback book' ,'Best selling novel from Jiraya sensei. The novel is about a passionate love between a man and a woman',$photos[6]), '8' => new Item(8,'Spiderman: Clone Saga Epic 1', 22.00, 'Paperback Comic book','Spider-Mans clone is back and the real Spidey is beside himself Peter thought his clone was long dead, but where has Ben Reilly been for the last five years? ',$photos[7]), '9' => new Item(9,'Bleached', 19.00, 'Digital Album','“Bleached” is the 1st album recorded by South Korean rapper Loco - 로꼬',$photos[8]), '10' => new Item(10,'Kimoyo Beads', 12.70, 'Accessory Item','Wakandas precious Kimoyo beads are at your hand, allowing access to Black Panthers secret communication field with this exquisite gunmetal bracelet by RockLove. A blue prime bead holds a lifetime of knowledge and illuminates in the dark.',$photos[9]), ]; ?> //itemsfunction.php(Page 2) <?php class Item { var $id; var $name; var $price; var $category; var $description; var $photo; function __construct($id,$name,$price,$category,$description,$photo) { $this->id = $id; $this->name = $name; $this->price = $price; $this->category = $category; $this->description = $description; $this->image = $photo; } function get_id() { return $this->id; } function get_name() { return $this->name; } function get_photo() { return $this->image; } function get_price() { return $this->price; } function get_category() { return $this->category; } function get_description() { return $this->description; } function takes_currrency($number) { $number = get_price(); setlocale(LC_MONETARY,"en_US"); echo money_format($number); } function get_select($max_items) { $id = $this->get_name(); $html = <<<EOT <label for="$id">$this->description</label> <select id="$id" name="$id"> EOT; for ($count = 0; $count <= $max_items; $count++) { $html .= <<<EOT <option value="$count">$count</option> EOT; } $html .= '</select>'; return $html; } } //function get_name() {return $this->description . 'Item';} ?> // user.php (Page 3) <?php session_start(); require 'items.php'; require_once 'itemsfunction.php'; ?> <!DOCTYPE html> <html> <head> <title>Product Page</title> <link rel = "stylesheet" type = "text/css" href = "default.css"> </head> <body align = "center"> <?php //initialize cart if(!isset($_SESSION['shoppingCart'])) { $_SESSION['shoppingCart'] = array(); } echo"<a href = 'user.php?view_cart=1'>View Cart</a></br>"; //Empty cart if($_GET['empty_cart']) { $_SESSION['shoppingCart'] = array(); } //add to cart if(isset($_POST['addCart'])) { $item_id = $_POST['item_id']; //Is item valid if(!isset($items[$item_id])) { echo "Invalid Item!<br/>"; } else if(isset($_SESSION['shoppingCart'][$item_id])) { echo "Item is already in cart!<br/>"; } else { $count = count($_SESSION['shoppingCart']); $_SESSION['shoppingCart'][$count]['item_id'] = $_POST['item_id']; $_SESSION['shoppingCart'][$count]['quantity'] = $_POST['quantity']; } } //update Cart if((isset($_POST['updateCart']))) { $quanties = $_POST['quantity']; foreach($quanties as $id=>$quantity) { if(!isset($products[$id])) { echo "Invalid product!<br/>"; break; } } $_SESSION['shoppingCart'][$id]['quantity'] = $quantity; } if(isset($_GET['view_product'])) { echo "<h2 style = 'text-align:center;' >Hidden Leaf Mart</h2> <h3 style = 'text-align:center;'>You Selected:</h3>"; echo $_GET['view_product']; $item_id = $_GET['view_product']; echo "<span; align = left><a href='http://localhost/test/user.php'>Home</a> </span></br>"; $item = $items[$item_id]; echo $item->get_photo()."</br>" ; echo $item->get_name()."</br>" ; $total = sprintf($item->get_price()); echo '$'.$total."</br>" ; echo $item->get_category()."</br>" ; echo $item->get_description()."</br>" ; echo"<span> <form action = 'user.php?view_product=$item_id' method = 'post'> <select name = 'quantity'> <option value = '1'>1</option> <option value = '2'>2</option> <option value = '3'>3</option> <option value = '4'>4</option> <option value = '5'>5</option> </select> <input type = 'hidden' name = 'item_id' value = '$item_id'/> <input type = 'submit' name = 'addCart' value = 'Add to cart'/> </form>"; } else if(isset($_GET['view_cart'])) { echo "<a href = 'user.php'>Hidden-Leaf</a></br>"; echo"Your Cart: <br/>"; echo "<a href = 'user.php?empty_cart=1'>Empty Cart</a></br></br>"; if(empty($_SESSION['shoppingCart'])) { echo "You have no items in your cart. </br>"; } else { echo "<form action='user.php?view_cart=1' method='post'> <table style='width:500px;' cellspacing='0'> <tr> <th style='border-bottom:1px solid #000000;'>Name</th> <th style='border-bottom:1px solid #000000;'>Price</th> <th style='border-bottom:1px solid #000000;'>Category</th> <th style='border-bottom:1px solid #000000;'>Quantity</th> </tr>"; foreach($_SESSION['shoppingCart']as $id => $product) { $product_id = $product['item_id']; $quantity = $product['quantity']; $item = $items[$product_id]; echo "<tr> <td style='border-bottom:1px solid #000000;'><a href='./index.php?view_product=$id'>" . $item->get_name() . "</a></td> <td style='border-bottom:1px solid #000000;'>$" . $item->get_price() . "</td> <td style='border-bottom:1px solid #000000;'>" . $item->get_category(). "</td> <td style='border-bottom:1px solid #000000;'> <input type='text' name='quantity[$product_id]' value='" . $product['quantity'] . "' /></td> </tr>"; } } echo "</table> <input type='submit' name='update_cart' value='Update' /> </form> <p> <a href='user.php?checkout=1'>Checkout</a> </p>"; } else if(isset($_GET['checkout'])) { echo "<a href = 'user.php'>Hidden-Leaf</a></br>"; echo"Checkout: <br/>"; if(empty($_SESSION['shoppingCart'])) { echo "Your cart is empty.<br />"; } else { echo "<form action='user.php?checkout=1' method='post'> <table style='width:500px;' cellspacing='0'> <tr> <th style='border-bottom:1px solid #000000;'>Name</th> <th style='border-bottom:1px solid #000000;'>Item Price</th> <th style='border-bottom:1px solid #000000;'>Quantity</th> <th style='border-bottom:1px solid #000000;'>Cost</th> </tr>"; $total_price =0; foreach($_SESSION['shoppingCart'] as $id => $product) { $product_id = $product['item_id']; $item = $items[$product_id]; $total = $item->get_price(); $total_price += ($total * $product['quantity']); echo "<tr> <td style='border-bottom:1px solid #000000;'><a href='user.php?view_product=$id'>" . $item->get_name() . "</a></td> <td style='border-bottom:1px solid #000000;'>$" . $item->get_price(). "</td> <td style='border-bottom:1px solid #000000;'>" . $product['quantity'] . "</td> <td style='border-bottom:1px solid #000000;'>$" . ($total * $product['quantity']) . "</td> </tr>"; } $taxrate = 8.25; echo "</table><br/>"; echo "Tax rate: $".$taxrate."<br/>"; echo "<p>Total price: $" . ($total_price+$taxrate) . "</p>"; } } else { echo "<h2 style = 'text-align:center;' >Welcome to Hidden Leaf Mart</h2> <h3 style = 'text-align:center;'>Our Products:</h3>"; foreach ($items as $id => $item) { $item->get_id(); echo $item-> get_photo(); echo '<br />'; echo "<a href = './user.php?view_product=$id'>". $item ->get_name()."</a>"; echo '<br />'; echo '<br />'; echo '<br />'; } } ?> </body> </html>
Java
UTF-8
2,365
3.875
4
[]
no_license
import java.util.Scanner; /** *This program tells the user their discount and how much they saved based on how much they spent * @author Zachary Balean */ public class Main { /** * The method that is executed when you hit the run button. * @param args the command line arguments */ public static void main(String[] args) { // Creates new Scanner Scanner input = new Scanner(System.in); //Constants for the discount percents final double TEN_OFF = 0.10; final double TWENTY_OFF = 0.20; final double THIRTY_OFF = 0.30; final double FORTY_OFF = 0.40; //asks and allows user to input how much they spent System.out.println("Please enter the amount the customer spent"); double amountSpent = input.nextDouble(); //Calculates cost if you get 10% off if(amountSpent >= 0.01 && amountSpent <= 40.00){ System.out.println("They will receive 10% off."); //Calculates amount saved double amountSaved = (amountSpent * TEN_OFF); System.out.println("They will save $" + amountSaved + "."); //Calculates remaining total double total = (amountSpent - amountSaved); System.out.println("The new total is $" + total + "."); //Calculates cost if you get 20% off } else if(amountSpent >= 40.01 && amountSpent <= 80.00){ System.out.println("They will receive 20% off."); double amountSaved = (amountSpent * TWENTY_OFF); System.out.println("They will save $" + amountSaved + "."); double total = (amountSpent - amountSaved); System.out.println("The new total is $" + total + "."); //Calculates if you get 30% off } else if(amountSpent >= 80.01 && amountSpent <= 120.00){ System.out.println("They will receive 30% off."); double amountSaved = (amountSpent * THIRTY_OFF); System.out.println("They will save $" + amountSaved + "."); double total = (amountSpent - amountSaved); System.out.println("The new total is $" + total + "."); //Calculates if you get 40%off } else { System.out.println("They will receive 40% off."); double amountSaved = (amountSpent * FORTY_OFF); System.out.println("They will save $" + amountSaved + "."); double total = (amountSpent - amountSaved); System.out.println("The new total is $" + total + "."); } } }
Python
UTF-8
201
2.90625
3
[ "MIT" ]
permissive
import time def printPeak(soundAnalysis): for i in range(10000): print(i , ": Peack count", soundAnalysis[0]) print(i , ": Weight Feed", soundAnalysis[1]) time.sleep(0.1)
Python
UTF-8
6,870
2.71875
3
[ "Apache-2.0" ]
permissive
from exceptions import NotImplementedError, Exception import logging from threading import RLock, local as thread_local import re class EventDispatcher(object): def __init__(self): self.listeners = dict() self.listeners[None] = set() self.lock = RLock() def dispatch_event(self, name, property, param): with self.lock: ## dispatch a all registraar os None for l in self.listeners.get(None, []): l.report_event(name, property, param) for l in self.listeners.get(name, []): l.report_event(name, property, param) def add_listener(self, listener): with self.lock: if listener.events is None: self.listeners[None].add(listener) else: for event in listener.events: s = self.listeners.get(event) if s is None: s = set() self.listeners[event] = s s.add(listener) def remove_listener(self, listener): with self.lock: if listener.events is None: self.listeners[None].remove(listener) else: for event in listener.events: s = self.listeners.get(event) s.remove(listener) class CounterRegistry(object): def __init__(self, dispatcher): super(CounterRegistry, self).__init__() self.lock = RLock() self.dispatcher = dispatcher self.registry = dict() def get_values(self): values_collection = CounterValueCollection() with self.lock: for name, c in self.registry.iteritems(): values_collection[name] = c.get_value() return values_collection def add_counter(self, counter, throw=True): with self.lock: if counter.name in self.registry: if throw: raise Exception("A counter named %s is already defined" % (counter.name)) return False self.registry[counter.name] = counter self.dispatcher.add_listener(counter) return True def remove_counter(self, counter=None, name=None): with self.lock: if counter: name = counter.name if not counter: counter = self.registry[name] if not name: raise Exception("trying to remove a counter from perfomance registry but no counter or name supplied.") self.dispatcher.remove_listener(counter) self.registry.pop(name) def get_counter(self, name, throw=True): with self.lock: c = self.registry.get(name) if not c and throw: raise Exception("No counter named '%s' found " % (name, )) return c class ThreadSpecificDispatcher(thread_local): """ A dispatcher handle thread specific dispatching. Also percolates to Global event""" ## TODO: work in progress. no clean solution yet. def _get_listner_set(self): if not hasattr(self, "listeners"): self.listeners = set() # new thread return self.listeners def add_listener(self, listener): self._get_listner_set().add(listener) def remove_listener(self, listener): self._get_listner_set().remove(listener) def dispatch_event(self, name, property, param): # first event specific ls = self._get_listner_set() if ls: for l in ls: l.report_event(name, property, param) # finally dispatch it globally.. global GLOBAL_DISPATCHER GLOBAL_DISPATCHER.dispatch_event(name, property, param) GLOBAL_DISPATCHER = EventDispatcher() GLOBAL_REGISTRY = CounterRegistry(GLOBAL_DISPATCHER) THREAD_DISPATCHER = ThreadSpecificDispatcher() class BaseListener(object): def __init__(self, events=None): """ events - a list of events name to listen to. Use None for all. """ self.events = events def report_event(self, name, property, param): """ reports an event to this listener """ raise NotImplementedError("report_event is not implemented") class EventLogger(BaseListener): """Ask boaz what it is for""" def __init__(self, logger, name_filter=None, property_filter=None, logging_level=logging.DEBUG): super(EventLogger, self).__init__() self.logger = logger self.logging_level = logging_level self.name_filter = None if name_filter: if isinstance(name_filter, basestring): self.name_filter = re.compile(name_filter) else: self.name_filter = name_filter if property_filter: if isinstance(property_filter, basestring): self.property_filter = re.compile(property_filter) else: self.property_filter = property_filter def report_event(self, name, property, param): if self.name_filter and not self.name_filter.match(name): return if self.property_filter and not self.property_filter.match(property): return self.logger.log(self.logging_level, "Event: name=%s property=%s param=%s", name, property, param) ########## # Values # ########## class CounterValueBase(object): """ a base class for counter values. Deals with defining merge semantics etc. """ def __init__(self, value): self.value = value def merge_with(self, other_counter_value): """ updates this CounterValue with information of another. Used for multiprocess reporting """ raise NotImplementedError("merge_with should be implemented in class inheriting from CounterValueBase") class CounterValueCollection(dict): """ a dictionary of counter values, adding support for dictionary merges and getting a value only dict. """ @property def values(self): r = {} for k, v in self.iteritems(): r[k] = v.value if hasattr(v, "value") else v return r def merge_with(self, other_counter_value_collection): for k, v in other_counter_value_collection.iteritems(): mv = self.get(k) if mv is None: # nothing local, just set it self[k] = v elif isinstance(mv, CounterValueBase): if not isinstance(v, CounterValueBase): raise Exception("Can't merge with CounterValueCollection. Other Collection doesn't have a mergeable value for key %s" % (k, )) mv.merge_with(v) else: raise Exception("Can't merge with CounterValueCollection. Local key %s doesn't have a mergeable value." % (k, ))
Java
UTF-8
2,669
2.203125
2
[]
no_license
package com.kpetrov.loftcoin.ui.wallets; import androidx.annotation.NonNull; import androidx.lifecycle.ViewModel; import com.kpetrov.loftcoin.data.Coin; import com.kpetrov.loftcoin.data.CurrencyRepo; import com.kpetrov.loftcoin.data.Transaction; import com.kpetrov.loftcoin.data.Wallet; import com.kpetrov.loftcoin.data.WalletsRepo; import com.kpetrov.loftcoin.util.RxSchedulers; import java.util.List; import javax.inject.Inject; import io.reactivex.Completable; import io.reactivex.Observable; import io.reactivex.subjects.BehaviorSubject; import io.reactivex.subjects.Subject; class WalletsViewModel extends ViewModel { private final Subject<Integer> walletPosition = BehaviorSubject.createDefault(0); private final Observable<List<Wallet>> wallets; private final Observable<List<Transaction>> transactions; private final WalletsRepo walletsRepo; private final CurrencyRepo currencyRepo; private final RxSchedulers schedulers; @Inject WalletsViewModel(WalletsRepo walletsRepo, CurrencyRepo currencyRepo, RxSchedulers schedulers) { this.walletsRepo = walletsRepo; this.currencyRepo = currencyRepo; this.schedulers = schedulers; wallets = currencyRepo.currency() .switchMap(walletsRepo::wallets) .replay(1) .autoConnect(); transactions = wallets .filter((f) -> !f.isEmpty()) .switchMap((wallets) -> walletPosition .map((position) -> Math.min(position, wallets.size() -1)) .map(wallets::get) ) .switchMap(walletsRepo::transactions) .replay(1) .autoConnect(); } @NonNull Observable<List<Wallet>> wallets() { return wallets.observeOn(schedulers.main()); } @NonNull Observable<List<Transaction>> transactions() { return transactions.observeOn(schedulers.main()); } @NonNull Completable addWallet() { return wallets .firstOrError() .flatMap((list) -> Observable .fromIterable(list) .map(Wallet::coin) .map(Coin::id) .toList() ) .flatMapCompletable((ids) -> currencyRepo .currency() .flatMapCompletable((completable) -> walletsRepo.addWallet(completable, ids)) ) .observeOn(schedulers.main()); } void changeWallet(int position) { walletPosition.onNext(position); } }
C++
WINDOWS-1250
2,546
2.9375
3
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
/***************************************************************************\ * * * Buffer pemapovn index * * * \***************************************************************************/ class CBufIndex { // ------------------------- intern promnn a funkce ---------------------- private: // promnn int* m_Data; // ukazatel na data int m_Num; // poet poloek v bufferu int m_Max; // velikost bufferu (poloek) // ---------------------------- veejn funkce ------------------------------ public: // konstruktor a destruktor CBufIndex(); ~CBufIndex(); // statick konstruktor a destruktor void Init(); void Term(); // zruen vech poloek v bufferu void DelAll(); // poskytnut adresy dat inline int* Data() const { return m_Data; }; // poskytnut/nastaven potu poloek v bufferu // (nov poloky neinicializovan, vrac FALSE=chyba pamti) inline int Num() const { return m_Num; }; bool _fastcall Num(const int num); // nastaven potu poloek s vymaznm "-1", vrac FALSE=chyba pamti bool _fastcall NumClear(const int num); // vymazn vech poloek v bufferu zadanou hodnotou void _fastcall Clear(const int clear); // kontrola platnosti poloky (kontroluje se pouze rozsah indexu) inline BOOL IsValid(const int index) const { return ((DWORD)index < (DWORD)m_Num); }; inline BOOL IsNotValid(const int index) const { return ((DWORD)index >= (DWORD)m_Num); }; // poskytnut pstupu k poloce (bez kontroly indexu) inline int& operator[] (const int index) { ASSERT(IsValid(index)); return m_Data[index]; } inline const int& operator[] (const int index) const { ASSERT(IsValid(index)); return m_Data[index]; } inline int& At(const int index) { ASSERT(IsValid(index)); return m_Data[index]; } inline const int& At(const int index) const { ASSERT(IsValid(index)); return m_Data[index]; } // poskytnut poloky (s kontrolou platnosti indexu, pro neplatnou vrt -1) int _fastcall Get(const int index) const; // nastaven poloky (s kontrolou platnosti indexu) void _fastcall Set(const int index, const int data); // pidn poloky na konec bufferu (vrac index poloky, pi chyb pamti vrac <0) int _fastcall Add(const int data); // opertor piazen (pi chyb pamti poet poloek nesouhlas) const CBufIndex& _fastcall operator= (const CBufIndex& srcbuf); };
Markdown
UTF-8
2,699
2.90625
3
[ "Apache-2.0" ]
permissive
Puppet Dashboard's Rake API ===== This is a chapter of the [Puppet Dashboard manual](./index.markdown). #### Navigation * [Installing Dashboard](./bootstrapping.markdown) * [Upgrading Dashboard](./upgrading.markdown) * [Configuring Dashboard](./configuring.markdown) * [Maintaining Dashboard](./maintaining.markdown) * **Rake API** * * * Rake API ----- Puppet Dashboard provides rake tasks that can create nodes, group nodes, create classes, and assign classes to nodes and groups. You can use these as an API to automate workflows or bypass Dashboard's GUI when performing large tasks. **This list of tasks applies to Dashboard 1.2.4 and later.** Some of these tasks were not included in prior releases of Dashboard 1.2. All of these tasks should be run as follows, replacing `<TASK>` with the task name and any arguments it requires: $ sudo -u puppet-dashboard rake -f <FULL PATH TO DASHBOARD'S DIRECTORY>/Rakefile <TASK> ### Node Tasks `node:list [match=<REGULAR EXPRESSION>]` : List nodes. Can optionally match nodes by regex. `node:add name=<NAME> [groups=<GROUPS>] [classes=<CLASSES>]` : Add a new node. Classes and groups can be specified as comma-separated lists. `node:del name=<NAME>` : Delete a node. `node:classes name=<NAME> classes=<CLASSES>` : Replace the list of classes assigned to a node. Classes must be specified as a comma-separated list. `node:groups name=<NAME> groups=<GROUPS>` : Replace the list of groups a node belongs to. Groups must be specified as a comma-separated list. ### Class Tasks `nodeclass:list [match=<REGULAR EXPRESSION>]` : List node classes. Can optionally match classes by regex. `nodeclass:add name=<NAME>` : Add a new class. This must be a class available to the Puppet autoloader via a module. `nodeclass:del name=<NAME>` : Delete a node class. ### Group Tasks `nodegroup:list [match=<REGULAR EXPRESSION>]` : List node groups. Can optionally match groups by regex. `nodegroup:add name=<NAME> [classes=<CLASSES>]` : Create a new node group. Classes can be specified as a comma-separated list. `nodegroup:del name=<NAME>` : Delete a node group. `nodegroup:add_all_nodes name=<NAME>` : Add every known node to a group. `nodegroup:addclass name=<NAME> class=<CLASS>` : Assign a class to a group without overwriting its existing classes. `nodegroup:edit name=<NAME> classes=<CLASSES>` : Replace the classes assigned to a node group. Classes must be specified as a comma-separated list. * * * #### Navigation * [Installing Dashboard](./bootstrapping.markdown) * [Upgrading Dashboard](./upgrading.markdown) * [Configuring Dashboard](./configuring.markdown) * [Maintaining Dashboard](./maintaining.markdown) * **Rake API**
Markdown
UTF-8
31,429
3.765625
4
[]
no_license
# movie_recommendation_system A program which uses data from movies and databases, including user ratings -- and can answer questions about the data, including which items should be recommended to a user based on their ratings of several movies. To execute the program, upload the 'Final.zip' file to https://www.dukelearntoprogram.com//capstone/upload.php ## Classes <b>Movie</b> - a Plain Old Java Object (POJO) class for storing the data about one movie. It includes the following: * Eight private variables to represent information about a movie including: >* id - a String variable representing the IMDB ID of the movie >* title - a String variable for the movie’s title >* year - an integer representing the year >* genres - one String of one or more genres separated by commas >* director - one String of one or more directors of the movie separated by commas >* country - one String of one or more countries the film was made in, separated by commas >* minutes - an integer for the length of the movie >* poster - a String that is a link to an image of the movie poster if one exists, or “N/A” if no poster exists * A constructor with eight parameters to initialize the private variables * Eight getter methods to return the private information such as the method *getGenres* that returns a String of all the genres for this movie. * A *toString* method for representing movie information as a String so it can easily be printed. <b>Rating</b> - a POJO class for storing the data about one rating of an item. It includes: * Two private variables to represent information about a rating: >* item - a String description of the item being rated (for this assignment you should use the IMDB ID of the movie being rated) >* value - a double of the actual rating * A constructor with two parameters to initialize the private variables. * Two getter methods *getItem* and *getValue*. * A *toString* method to represent rating information as a String. * A *compareTo* method to compare this rating with another rating. <b>Rater</b> - an interface for classes that keep track of one rater and all their ratings. Contains the following methods: * *addRating* that has two parameters, a String named item and a double named rating. * *hasRating* with one String pararemeter for the movie ID. * *getID* with no parameters. * *getRating* that has one parameter item. * *numRatings* with no parameters. * *getItemsRated* that has no parameters. <b>PlainRater</b> - a class that uses the implements the Rater interface. This class includes: * Two private variables: >* myID - a unique String ID for this rater >* myRatings - an ArrayList of Ratings * A constructor with one parameter of the ID for the rater. * A method *addRating* that has two parameters, a String named item and a double named rating. A new Rating is created and added to myRatings. * A method *hasRating* with one String pararemeter for the movie ID. Returns true if a rating exists, false otherwise. * A method *getID* with no parameters to get the ID of the rater. * A method *getRating* that has one parameter item. This method returns the double rating of this item if it is in myRatings. Otherwise this method returns -1. * A method *numRatings* that returns the number of ratings this rater has. * A method *getItemsRated* that has no parameters. This method returns an ArrayList of Strings representing a list of all the items that have been rated. <b>EfficientRater</b> - a class that uses the implements the Rater interface. This class includes: * Two private variables: >* myID - a unique String ID for this rater >* myRatings - a HashMap<String,Rating>. The key in the HashMap is a movie ID, and its value is a rating associated with this movie. * A constructor with one parameter of the ID for the rater. * A method *addRating* that has two parameters, a String named item and a double named rating. A new Rating is created and added to myRatings, with the value associated with the movie ID String item as the key in the HashMap. * A method *hasRating* with one String pararemeter for the movie ID. Returns true if a rating exists, false otherwise. * A method *getID* with no parameters to get the ID of the rater. * A method *getRating* that has one parameter item. This method returns the double rating of this item if it is in myRatings. Otherwise this method returns -1. * A method *numRatings* that returns the number of ratings this rater has. * A method *getItemsRated* that has no parameters. This method returns an ArrayList of Strings representing a list of all the items that have been rated. <b>FirstRatings</b> - a class that processes the movie and ratings data and to answer questions about them. Contains the folling methods: * *loadMovies* - takes in 1 parameter, the filename of a csv containing movies that have been rated. Loads the movies in and returns the result in an ArrayList local variable, movieData. Also calls printMovieData to prints the number of movies, and print each movie. * *printMovieData* - takes in an ArrayList movieData, analyzes it, and prints the total # of movies, the # of comedies, the # of movies with runtime greater than 150 mins, and the driector(s) with the greatest # of movies. * *loadRaters* - takes in 1 parameter, the filename of a csv containing raters and their ratings, then processes every record and return an ArrayList of type Rater with all the rater data from the file. * *printRaterData* - takes in an ArrayList rater of type Rater, and prints the total # of raters. Then for each rater, prints their ID and the # of movies rated, and prints each movie along with the rating. * *printRatingsByID* -takes in 2 parameters, a String id which represents a rater id, and an ArrayList raterData of type Rater. Checks to see if the rater id exists in the ArrayList and, if so, prints the rater information. Otherwise prints that no rater information could be found. * *findMaxNoRatings* - takes in 1 parameter, an ArrayList raterData of type Rater. Returns and int of the highest # of ratings given by a single rater. * *findMaxRaters* - takes in 2 parameters, an ArrayList raterData of type Rater, and an int maxNoRatings representing the maximum number of ratings. Returns all raters who are greater than or equal the maxNoRatings. * *printMaxRaters* - takes in 1 parameter, an ArrayList raterData of type Rater. Calls findMaxNoRatings and findMaxRaters, then prints the maximum # of ratings and all raters who ratings that many movies. * *findNoRatingsForMovie* - takes in 2 parameters, a String movieID representing a movie, and an ArrayList raterData of type Rater. Returns an int representing the number of ratings for the given movie. * *findNoMoviesRated* - takes in 1 parameter, an ArrayList raterData of type Rater. Analyzes the ArrayList and returns the # of movies that have been rated. * *testLoadMovies* - a void method with tests loading a csv containing movies into an ArrayList of type Movie. Prints the resulting ArrayList. * *testLoadRaters* - a void method with tests loading a csv containing movies into an ArrayList of type Rater. Prints the resulting ArrayList. <b>SecondRatings</b> - a class to do calculations focusing on computing averages on movie ratings. Includes two private variables, one named myMovies of type ArrayList of type Movie, and a second one named myRaters of type ArrayList of type Rater. Contains the folling methods: * *SecondRatings* - default constructor that loads the files "ratedmoviesfull.csv", "ratings.csv" by calling them into the second constructor. * *SecondRatings* - second constructor that creates a FirstRatings object and then calls the loadMovies and loadRaters methods in FirstRatings to read in all the movie and ratings data and store them in the two private ArrayList variables of the SecondRatings class, myMovies and myRaters. * *getMovieSize* - returns the number of movies that were read in and stored in the ArrayList of type Movie. * *getRaterSize* - returns the number of raters that were read in and stored in the ArrayList of type Rater. * *getAverageByID* - has two parameters: a String named id representing a movie ID and an integer named minimalRaters. This method returns a double representing the average movie rating for this ID if there are at least minimalRaters ratings. If there are not minimalRaters ratings, then it returns 0.0. * *getAverageRatings* - has one int parameter named minimalRaters. This method finds the average rating for every movie that has been rated by at least minimalRaters raters. Stores each such rating in a Rating object in which the movie ID and the average rating are used in creating the Rating object. Returns an ArrayList of all the Rating objects for movies that have at least the minimal number of raters supplying a rating. >* For example, if minimalRaters has the value 10, then this method returns rating information (the movie ID and its average rating) for each movie that has at least 10 ratings. * *getTitle* - has one String parameter named id, representing the ID of a movie. This method returns the title of the movie with that ID. If the movie ID does not exist, then this method should return a String indicating the ID was not found. * *getID* - has one String parameter named title representing the title of a movie. This method returns the movie ID of this movie. If the title is not found, return an appropriate message such as “NO SUCH TITLE.” Note that the movie title must be spelled exactly as it appears in the movie data files. <b>MovieRunnerAverage</b> - used to test the methods created in SecondRatings by creating a SecondRatings object in MovieRunnerAverage and calling its methods. Contains the following methods: * *printAverageRatings* - has no parameters. Creates a SecondRatings object and use the CSV filenames of movie information and ratings information from the first assignment when calling the constructor. Prints the number of movies and number of raters from the two files by calling the appropriate methods in the SecondRatings class. >* For example, if run on the files ratings_short.csv and ratedmovies_short.csv, you should see 5 raters and 5 movies. * *getAverageRatingOneMovie* - this method first creates a SecondRatings object, reading in data from the movie and ratings data files. Then this method prints out the average ratings for a specific movie title, such as the movie “The Godfather”. If the moviefile is set to the file named ratedmovies_short.csv, and the ratingsfile is set to the file ratings_short.csv, then the average for the movie “The Godfather” would be 9.0. <b>MovieDatabase</b> - This class is an efficient way to get information about movies. It stores movie information in a HashMap for fast lookup of movie information given a movie ID. The class also allows filtering movies based on queries. All methods and fields in the class are static. This means we'll be able to access methods in MovieDatabase without using new to create objects, but by calling methods like MovieDatabase.getMovie("0120915"). This class has the following parts: * A HashMap named *ourMovies* that maps a movie ID String to a Movie object with all the information about that movie. * A public initialize method with one String parameter named *moviefile*. We can call this method with the name of the file used to initialize the movie database. * A private initialize method with no parameters that will load the movie file ratedmoviesfull.csv if no file has been loaded. This method is called as a safety check with any of the other public methods to make sure there is movie data in the database. * A private *loadMovies* method to build the HashMap. * A *containsID* method with one String parameter named id. This method returns true if the id is a movie in the database, and false otherwise. * Several getter methods including *getYear*, *getTitle*, *getMovie*, *getPoster*, *getMinutes*, *getCountry*, *getGenres*, and *getDirector*. Each of these takes a movie ID as a parameter and returns information about that movie. * A *size* method that returns the number of movies in the database. * A *filterBy* method that has one Filter parameter named f. This method returns an ArrayList of type String of movie IDs that match the filtering criteria: >* The interface Filter has only one signature for the method satisfies. Any filters that implement this interface must also have this method. The method satisfies has one String parameter named id representing a movie ID. This method returns true if the movie satisfies the criteria in the method and returns false otherwise. >* The class <b>TrueFilter</b> can be used to select every movie from MovieDatabase. It’s satisfies method always returns true. >* The class <b>YearsAfterFilter</b> is a filter for a specified year; it selects only those movies that were created on that year or created later than that year. If the year is 2000, then all movies created in the year 2000 and the years after (2001, 2002, 2003, etc) would be selected if used with MovieDatabase.filterBy. >* The class <b>AllFilters</b> combines several filters. This class has the following: >* - A private variable named filters that is an ArrayList of type Filter. >* - An addFilter method that has one parameter named f of type Filter. This method allows one to add a Filter to the ArrayList filters. >* - A satisfies method that has one parameter named id representing a movie ID. This method returns true if the movie satisfies the criteria of all the filters in the filters ArrayList. Otherwise this method returns false. <b>ThirdRatings</b> - This class does calculations focusing on computing averages on movie ratings. Similar to the SecondRatings class, except movies are stored in the MovieDatabase instead of in the instance variable myMovies. Includes one private variable, myRaters, of type ArrayList of type Rater. Contains the folling methods: * *ThirdRatings* - default constructor that loads the files "ratedmoviesfull.csv", "ratings.csv" by calling them into the second constructor. * *ThirdRatings* - second constructor that creates a FirstRatings object and then calls the loadMovies and loadRaters methods in FirstRatings to read in all the movie and ratings data and store them in the private ArrayList variable of the ThirdRatings class, myRaters. * *getRaterSize* - returns the number of raters that were read in and stored in the ArrayList of type Rater. * *getAverageByID* - has two parameters: a String named id representing a movie ID and an integer named minimalRaters. This method returns a double representing the average movie rating for this ID if there are at least minimalRaters ratings. If there are not minimalRaters ratings, then it returns 0.0. * *getAverageRatings* - has one int parameter named minimalRaters. This method finds the average rating for every movie that has been rated by at least minimalRaters raters. Stores each such rating in a Rating object in which the movie ID and the average rating are used in creating the Rating object. Returns an ArrayList of all the Rating objects for movies that have at least the minimal number of raters supplying a rating. >* For example, if minimalRaters has the value 10, then this method returns rating information (the movie ID and its average rating) for each movie that has at least 10 ratings. * *getAverageRatingsByFilter* - has two parameters, an int named minimalRaters for the minimum number of ratings a movie must have and a Filter named filterCriteria. This method should create and return an ArrayList of type Rating of all the movies that have at least minimalRaters ratings and satisfies the filter criteria. This method will creates the ArrayList of type String of movie IDs from the MovieDatabase using the filterBy method before calculating those averages. <b>MovieRunnerWithFilters</b> - a class used to find the average rating of movies using different filters. * *printAverageRatings* - has no parameters. Creates a ThirdRatings object and uses the CSV filenames of movie information and ratings information from the first assignment when calling the constructor. Prints the number of movies and number of raters from the two files by calling the MovieDatabase initialize method with the moviefile to set up the movie database. * *printAverageRatingsByYear* - similar to printAverageRatings, but also creates a <b>YearAfterFilter</b> and calls *getAverageRatingsByFilter* to get an ArrayList of type Rating of all the movies that have a specified number of minimal ratings and came out in a specified year or later. Print the number of movies found, and for each movie found, print its rating, its year, and its title. * *printAverageRatingsByGenre* - creates a <b>GenreFilter</b> and calls * *getAverageRatingsByFilter* to get an ArrayList of type Rating of all the movies that have a specified number of minimal ratings and include a specified genre. Prints the number of movies found, and for each movie, prints its rating and its title on one line, and its genres on the next line. * *printAverageRatingsByMinutes* - creates a <b>MinutesFilter</b> and calls * *getAverageRatingsByFilter* - gets an ArrayList of type Rating of all the movies that have a specified number of minimal ratings and their running time is at least a minimum number of minutes and no more than a maximum number of minutes. Prints the number of movies found, and for each movie prints its rating, its running time, and its title on one line. * *printAverageRatingsByDirectors* - creates a <b>DirectorsFilter</b> and calls *getAverageRatingsByFilter* to get an ArrayList of type Rating of all the movies that have a specified number of minimal ratings and include at least one of the directors specified. Print the number of movies found, and for each movie prints its rating and its title on one line, and all its directors on the next line. * *printAverageRatingsByYearAfterAndGenre* - creates an <b>AllFilters</b> object that includes criteria based on movies that came out in a specified year or later and have a specified genre as one of its genres. This method calls *getAverageRatingsByFilter* to get an ArrayList of type Rating of all the movies that have a specified number of minimal ratings and the two criteria based on year and genre. Prints the number of movies found, and for each movie, prints its rating, its year, and its title on one line, and all its genres on the next line. * *printAverageRatingsByDirectorsAndMinutes* - creates an <b>AllFilters</b> object that includes criteria based on running time (at least a specified minimum number of minutes and at most a specified maximum number of minutes), and directors (at least one of the directors in a list of specified directors—directors are separated by commas). This method calls *getAverageRatingsByFilter* to get an ArrayList of type Rating of all the movies that have a specified number of minimal ratings and the two criteria based on minutes and directors. Prints the number of movies found, and for each movie, prints its rating, its time length, and its title on one line, and all its directors on the next line. <b>GenreFilter</b> - a class that implements Filter. The constructor has one parameter named genre representing one genre, and the satisfies method returns true if a movie has this genre. Note that movies may have several genres. <b>MinutesFilter</b> - a class that implements Filter. Its satisfies method returns true if a movie’s running time is at least min minutes and no more than max minutes. <b>DirectorsFilter</b> - a class that implements Filter. The constructor has one parameter named directors representing a list of directors separated by commas (Example: "Charles Chaplin,Michael Mann,Spike Jonze", and its satisfies method should return true if a movie has at least one of these directors as one of its directors. Note that each movie may have several directors. <b>RaterDatabase</b> - an efficient way to get information about raters. This class contains: * A HashMap named ourRaters that maps a rater ID String to a Rater object that includes all the movie ratings made by this rater. * A public static initialize method with one String parameter named filename. We can call this method with the name of the file used to initialize the rater database. * A private initialize method with no parameters that initializes the HashMap ourRaters if it does not exist. * A public static void *addRatings* method that has one String parameter named filename. We could alternatively call this method to add rater ratings to the database from a file. * A public static void *addRaterRating* method that has three parameters, a String named raterID representing a rater ID, a String named movieID that represents a movie ID, and a double named rating that is the rating the rater raterID has given to the movie movieID. This function can be used to add one rater and their movie rating to the database. Notice that the method addRatings calls this method. * A method *getRater* has one String parameter named id. This method returns a Rater that has this ID. * A method *getRaters* that has no parameters. This method returns an ArrayList of Raters from the database. * A method *size* that has no parameters. This method returns the number of raters in the database. <b>FourthRatings</b> - This class does calculations focusing on computing averages on movie ratings. Similar to the ThirdRatings class, except raters are stored in the RaterDatabase class, so both movies are ratings are stored in database classes now in place of instance variables. Includes one private variable, myRaters, of type ArrayList of type Rater. Contains the folling methods: * *FourthRatings* - default constructor that loads the file, "ratings.csv" by calling them into the second constructor. * *FourthRatings* - second constructor that creates calls the <b>RaterDatabase</b> *initialize* method to read in all the movie and ratings data. * *getAverageByID* - has two parameters: a String named id representing a movie ID and an integer named minimalRaters. This method returns a double representing the average movie rating for this ID if there are at least minimalRaters ratings. If there are not minimalRaters ratings, then it returns 0.0. * *getAverageRatings* - has one int parameter named minimalRaters. This method finds the average rating for every movie that has been rated by at least minimalRaters raters. Stores each such rating in a Rating object in which the movie ID and the average rating are used in creating the Rating object. Returns an ArrayList of all the Rating objects for movies that have at least the minimal number of raters supplying a rating. >* For example, if minimalRaters has the value 10, then this method returns rating information (the movie ID and its average rating) for each movie that has at least 10 ratings. * *getAverageRatingsByFilter* - has two parameters, an int named minimalRaters for the minimum number of ratings a movie must have and a Filter named filterCriteria. This method should create and return an ArrayList of type Rating of all the movies that have at least minimalRaters ratings and satisfies the filter criteria. This method will creates the ArrayList of type String of movie IDs from the MovieDatabase using the filterBy method before calculating those averages. * *dotProduct* - has two parameters, a Rater named me and a Rater named r. This method first translates a rating from the scale 0 to 10 to the scale -5 to 5 and returns the dot product of the ratings of movies that they both rated. This is called by getSimilarities. * *getSimilarities* - has one String parameter named id—this method computes a similarity rating for each rater in the RaterDatabase (except the rater with the ID given by the parameter) to see how similar they are to the Rater whose ID is the parameter to getSimilarities. This method returns an ArrayList of type Rating sorted by ratings from highest to lowest rating with the highest rating first and only including those raters who have a positive similarity rating since those with negative values are not similar in any way. Note that in each Rating object the item field is a rater’s ID, and the value field is the dot product comparison between that rater and the rater whose ID is the parameter to getSimilarities. * *getSimilarRatings* - has three parameters: a String named id representing a rater ID, an integer named numSimilarRaters, and an integer named minimalRaters. This method returns an ArrayList of type Rating, of movies and their weighted average ratings using only the top numSimilarRaters with positive ratings and including only those movies that have at least minimalRaters ratings from those most similar raters (not just minimalRaters ratings overall). >* For example, if minimalRaters is 3 and a movie has 4 ratings but only 2 of those ratings were made by raters in the top numSimilarRaters, that movie should not be included. These Rating objects should be returned in sorted order by weighted average rating from largest to smallest ratings. This method is very much like the getAverageRatings method you have written previously. In particular this method should: >* For every rater, get their similarity rating to the given parameter rater id. Include only those raters with positive similarity ratings—those that are more similar to rater id. >* For each movie, calculate a weighted average movie rating based on: Use only the top (largest) numSimilarRaters raters. For each of these raters, multiplies their similarity rating by the rating they gave that movie. This emphasizes those raters who are closer to the rater id, since they have greater weights. The weighted average movie rating for a particular movie is the sum of these weighted average ratings (for each rater multiply their similarity rating by their rating for the movie), divided by the total number of such ratings. >* This method returns an ArrayList of Ratings for movies and their calculated weighted ratings, in sorted order. * *getSimilarRatingsByFilter* - similar to the *getSimilarRatings* method but has one additional Filter parameter named filterCriteria and uses that filter to access and rate only those movies that match the filter criteria. <b>MovieRunnerSimilarRatings</b> - a class used to find the average rating of movies using different filters. * *printAverageRatings* - has no parameters. Creates a FourthRatings object and uses the CSV filenames of movie information and ratings information from the first assignment when calling the constructor. Prints the number of movies and number of raters from the two files by calling the MovieDatabase initialize method with the moviefile to set up the movie database. * *printAverageRatingsByYearAfterAndGenre* - creates an <b>AllFilters</b> object that includes criteria based on movies that came out in a specified year or later and have a specified genre as one of its genres. This method calls *getAverageRatingsByFilter* to get an ArrayList of type Rating of all the movies that have a specified number of minimal ratings and the two criteria based on year and genre. Prints the number of movies found, and for each movie, prints its rating, its year, and its title on one line, and all its genres on the next line. * *printSimilarRatings* - has no parameters. This method creates a new FourthRatings object, reads data into the <b>MovieDatabase</b> and <b>RaterDatabase</b>, and then calls *getSimilarRatings* for a particular rater ID, a number for the top number of similar raters, and a number of minimal rateSimilarRatings, and then lists recommended movies and their similarity ratings. >* For example, using the files ratedmoviesfull.csv and ratings.csv and the rater ID 65, the number of minimal raters 5, and the number of top similar raters set to 20, the movie returned with the top rated average is “The Fault in Our Stars”. * *printSimilarRatingsByGenre* - has no parameters. This method is similar to *printSimilarRatings* but also uses a genre filter and then lists recommended movies and their similarity ratings, and for each movie prints the movie and its similarity rating on one line and its genres on a separate line below it. >* For example, using the files ratedmoviesfull.csv and ratings.csv, the genre “Action”, the rater ID 65, the number of minimal raters set to 5, and the number of top similar raters set to 20, the movie returned with the top rated average is “Rush”. * *printSimilarRatingsByDirector* - has no parameters. This method is similar to *printSimilarRatings* but also uses a director filter and then lists recommended movies and their similarity ratings, and for each movie prints the movie and its similarity rating on one line and its directors on a separate line below it. >* For example, using the files ratedmoviesfull.csv and ratings.csv, the directors “Clint Eastwood,Sydney Pollack,David Cronenberg,Oliver Stone”, the rater ID 1034, the number of minimal raters set to 3, and the number of top similar raters set to 10, the movie returned with the top rated average is “Unforgiven”. * *printSimilarRatingsByGenreAndMinutes* - has no parameters. This method is similar to *printSimilarRatings* but also uses a genre filter and a minutes filter and then lists recommended movies and their similarity ratings, and for each movie prints the movie, its minutes, and its similarity rating on one line and its genres on a separate line below it. >* For example, using the files ratedmoviesfull.csv and ratings.csv, the genre “Adventure”, minutes between 100 and 200 inclusive, the rater ID 65, the number of minimal raters set to 5, and the number of top similar raters set to 10, the movie returned with the top rated average is “Interstellar”. * *printSimilarRatingsByYearAfterAndMinutes* - has no parameters. This method is similar to *printSimilarRatings* but also uses a year-after filter and a minutes filter and then lists recommended movies and their similarity ratings, and for each movie prints the movie, its year, its minutes, and its similarity rating on one line. >* For example, using the files ratedmoviesfull.csv and ratings.csv, the year 2000, minutes between 80 and 100 inclusive, the rater ID 65, the number of minimal raters set to 5, and the number of top similar raters set to 10, the movie returned with the top rated average is “The Grand Budapest Hotel”. ## Data files In creating recommendations we'll need two data files: one of movies (ratedmoviesfull.csv), and one of ratings of these movies by different raters (ratings.csv). These files are contained in the 'data' folder. ratedmoviesfull.csv - has a header row as the first line, first followed by one line for each movie. ratings.csv - has a header first followed by one line for each rating. ## Link to exercises: * https://www.coursera.org/learn/java-programming-recommender/supplement/ILMcl/programming-exercise-step-one * https://www.coursera.org/learn/java-programming-recommender/supplement/KTrOQ/programming-exercise-step-two * https://www.coursera.org/learn/java-programming-recommender/supplement/E9Xy0/programming-exercise-step-three * https://www.coursera.org/learn/java-programming-recommender/supplement/433EU/programming-exercise-step-four * https://www.coursera.org/learn/java-programming-recommender/peer/uOSDs/step-five
Go
UTF-8
719
3.6875
4
[]
no_license
package main import ( "fmt" "time" ) func main() { queue := make(chan string, 2) //这个通道设置了缓冲,所以直接发送,数据会放在缓冲区中,等待读取, //可以尝试改变缓冲区大小来进行调试, 改成1, 第一个数据会发送到通道,第二个就deadlock queue <- "one" fmt.Println("send one") queue <- "two" fmt.Println("send two") close(queue) time.Sleep(time.Second * 3) for msg := range queue { //这个接收消息,是按照发送消息一条一条接收的,并不像tcp的字节流 // 你看,我把缓冲区设置得很大了,而且还sleep了一会儿,还是依然无法收到整条数据,他们依然是分开的 fmt.Println(msg) } }
Python
UTF-8
16,947
2.96875
3
[ "MIT" ]
permissive
""" Implementation of optimization benchmark function using Pytorch reference: https://www.sfu.ca/~ssurjano/optimization.html """ import torch from torch import Tensor import math import numpy as np from .utils import DataTransformer, standardize class BenchmarkFunction(object): def __init__(self, noise_std=None, maximize=False): self.noise_std = noise_std self.maximize = maximize self.is_grid = False self.bounds = None self.dim = 1 @property def optimal_value(self): return self._optimal_value if not self.maximize else -self._optimal_value def evaluate_true(self, x): raise NotImplementedError() def evaluate(self, x, transformer=None): if transformer is not None: # transform from some other space to the original domain x = transformer(x) batch = x.ndimension() > 1 x = x if batch else x.unsqueeze(0) f = self.evaluate_true(x) if self.noise_std is not None: f += self.noise_std * torch.randn_like(f) if self.maximize: f = -f return f if batch else f.squeeze(0) def discretize_domain(self, num_sobol_samples_scale=1000): self.is_grid = True self.num_sobol_samples = num_sobol_samples_scale * self.dim soboleng = torch.quasirandom.SobolEngine(dimension=self.dim) self.x = soboleng.draw(self.num_sobol_samples) transformer = DataTransformer(self.bounds) self.raw_x = transformer.from_normalized_to_original(self.x) self.raw_y = self.evaluate(self.raw_x) self.y = standardize(self.raw_y) class Ackley(BenchmarkFunction): def __init__( self, dim=2, noise_std=None, maximize=False, a=20.0, b=0.2, c=2 * math.pi ): super().__init__(noise_std=noise_std, maximize=maximize) self.dim = dim self.bounds = Tensor([[-32.768, 32.768] for _ in range(dim)]).t() self._optimal_value = 0.0 self.x_star = [[0.0] * dim] self.a = a self.b = b self.c = c def evaluate_true(self, x): a, b, c = self.a, self.b, self.c part1 = -a * torch.exp(-b * torch.sqrt(torch.mean(x ** 2, dim=1))) part2 = -torch.exp(torch.mean(torch.cos(c * x), dim=1)) return part1 + part2 + a + math.e class Beale(BenchmarkFunction): def __init__(self, noise_std=None, maximize=False): super().__init__(noise_std=noise_std, maximize=maximize) self.dim = 2 self.bounds = Tensor([[-4.5, 4.5], [-4.5, 4.5]]).t() self._optimal_value = 0.0 self.x_star = [[3.0, 0.5]] def evaluate_true(self, x): x1 = x[:, 0] x2 = x[:, 1] part1 = (1.5 - x1 + x1 * x2) ** 2 part2 = (2.25 - x1 + x1 * x2 ** 2) ** 2 part3 = (2.625 - x1 + x1 * x2 ** 3) ** 2 return part1 + part2 + part3 class Branin(BenchmarkFunction): def __init__(self, noise_std=None, maximize=False): super().__init__(noise_std=noise_std, maximize=maximize) self.dim = 2 self.bounds = Tensor([[-5.0, 10.0], [0.0, 15.0]]).t() self._optimal_value = 0.397887 self.x_star = [[-math.pi, 12.275], [math.pi, 2.275], [9.42478, 2.475]] def evaluate_true(self, x): t1 = ( x[:, 1] - 5.1 / (4 * math.pi ** 2) * x[:, 0] ** 2 + 5 / math.pi * x[:, 0] - 6 ) t2 = 10 * (1 - 1 / (8 * math.pi)) * torch.cos(x[:, 0]) return t1 ** 2 + t2 + 10 class Bukin(BenchmarkFunction): def __init__(self, noise_std=None, maximize=False): super().__init__(noise_std=noise_std, maximize=maximize) self.dim = 2 self.bounds = Tensor([[-15.0, -5.0], [-3.0, 3.0]]).t() self._optimal_value = 0.0 self.x_star = [[-10.0, 1.0]] def evaluate_true(self, x): part1 = 100.0 * torch.sqrt(torch.abs(x[:, 1] - 0.01 * x[:, 0] ** 2)) part2 = 0.01 * torch.abs(x[:, 0] + 10.0) return part1 + part2 class CrossInTray(BenchmarkFunction): def __init__(self, noise_std=None, maximize=False): super().__init__(noise_std=noise_std, maximize=maximize) self.dim = 2 self.bounds = Tensor([[-10.0, 10.0], [-10.0, 10.0]]).t() self._optimal_value = -2.06261 self.x_star = [ [1.3491, -1.3491], [1.3491, 1.3491], [-1.3491, 1.3491], [-1.3491, -1.3491], ] def evaluate_true(self, x): # torch.exp(100) = Inf if use single precision float x = x.type(torch.DoubleTensor) x1 = x[:, 0] x2 = x[:, 1] result = -0.0001 * ( torch.abs( torch.sin(x1) * torch.sin(x2) * torch.exp(torch.abs(100.0 - torch.sqrt(x1 ** 2 + x2 ** 2) / math.pi)) ) + 1.0 ).pow(0.1) return result.type(torch.float) class DropWave(BenchmarkFunction): def __init__(self, noise_std=None, maximize=False): super().__init__(noise_std=noise_std, maximize=maximize) self.dim = 2 self.bounds = Tensor([[-5.12, 5.12], [-5.12, 5.12]]).t() self._optimal_value = -1.0 self.x_star = [[0.0, 0.0]] def evaluate_true(self, x): sum2 = torch.sum(x ** 2, dim=1) part1 = 1.0 + torch.cos(12.0 * torch.sqrt(sum2)) part2 = 0.5 * sum2 + 2.0 return -part1 / part2 class DixonPrice(BenchmarkFunction): def __init__(self, dim=2, noise_std=None, maximize=False): super().__init__(noise_std=noise_std, maximize=maximize) self.dim = dim self.bounds = Tensor([[-10.0, 10.0] for _ in range(dim)]).t() self._optimal_value = 0.0 self.x_star = [ [math.pow(2.0, -(1.0 - 2.0 ** (-(i - 1)))) for i in range(1, dim + 1)] ] def evaluate_true(self, x): d = self.dim part1 = (x[:, 0] - 1) ** 2 i = x.new(range(2, d + 1)) part2 = torch.sum(i * (2.0 * x[:, 1:] ** 2 - x[:, :-1]) ** 2, dim=1) return part1 + part2 class EggHolder(BenchmarkFunction): def __init__(self, noise_std=None, maximize=False, a=20.0, b=0.2, c=2 * math.pi): super().__init__(noise_std=noise_std, maximize=maximize) self.dim = 2 self.bounds = Tensor([[-512.0, 512.0], [-512.0, 512.0]]).t() self._optimal_value = -959.6407 self.x_star = [[512.0, 404.2319]] def evaluate_true(self, x): x1 = x[:, 0] x2 = x[:, 1] part1 = -(x2 + 47.0) * torch.sin(torch.sqrt(torch.abs(x2 + x1 / 2.0 + 47.0))) part2 = -x1 * torch.sin(torch.sqrt(torch.abs(x1 - (x2 + 47.0)))) return part1 + part2 class Griewank(BenchmarkFunction): def __init__(self, dim=2, noise_std=None, maximize=False): super().__init__(noise_std=noise_std, maximize=maximize) self.dim = dim self.bounds = Tensor([[-600.0, 600.0] for _ in range(dim)]).t() self._optimal_value = 0.0 self.x_star = [[0.0] * dim] def evaluate_true(self, x): part1 = torch.sum(x ** 2 / 4000.0, dim=1) d = x.shape[1] part2 = -torch.prod( torch.cos(x / torch.sqrt(x.new(range(1, d + 1))).view(1, -1)) ) return part1 + part2 + 1.0 class GrLee12(BenchmarkFunction): def __init__(self, noise_std=None, maximize=False): super().__init__(noise_std=noise_std, maximize=maximize) self.dim = 1 self.bounds = Tensor([[0.5, 2.5]]).t() self._optimal_value = None self.x_star = None def evaluate_true(self, x): return (torch.sin(10.0 * math.pi * x) / (2.0 * x) + (x - 1.0) ** 4).squeeze() class Hartmann(BenchmarkFunction): def __init__(self, dim=3, noise_std=None, maximize=False): super().__init__(noise_std=noise_std, maximize=maximize) self.dim = dim self.bounds = Tensor([[0.0, 1.0] for _ in range(self.dim)]).t() self._optimal_value = None self.x_star = None self.ALPHA = [1.0, 1.2, 3.0, 3.2] if dim == 3: self.A = [[3.0, 10, 30], [0.1, 10, 35], [3.0, 10, 30], [0.1, 10, 35]] self.P = [ [3689, 1170, 2673], [4699, 4387, 7470], [1091, 8732, 5547], [381, 5743, 8828], ] self._optimal_value = -3.86278 self.x_star = [[0.114614, 0.555649, 0.852547]] elif dim == 4: self.A = [ [10, 3, 17, 3.5], [0.05, 10, 17, 0.1], [3, 3.5, 1.7, 10], [17, 8, 0.05, 10], ] self.P = [ [1312, 1696, 5569, 124], [2329, 4135, 8307, 3736], [2348, 1451, 3522, 2883], [4047, 8828, 8732, 5743], ] elif dim == 6: self.A = [ [10, 3, 17, 3.5, 1.7, 8], [0.05, 10, 17, 0.1, 8, 14], [3, 3.5, 1.7, 10, 17, 8], [17, 8, 0.05, 10, 0.1, 14], ] self.P = [ [1312, 1696, 5569, 124, 8283, 5886], [2329, 4135, 8307, 3736, 1004, 9991], [2348, 1451, 3522, 2883, 3047, 6650], [4047, 8828, 8732, 5743, 1091, 381], ] self._optimal_value = -3.32237 self.x_star = [[0.20169, 0.150011, 0.476874, 0.275332, 0.311652, 0.6573]] else: raise ValueError("Hartmann with dim %d not defined" % dim) def evaluate_true(self, x): inner_sum = torch.sum( x.new(self.A) * (x.unsqueeze(1) - 0.0001 * x.new(self.P)) ** 2, dim=2 ) H = -torch.sum(x.new(self.ALPHA) * torch.exp(-inner_sum), dim=1) if self.dim == 4: H = (1.1 + H) / 0.839 return H class HolderTable(BenchmarkFunction): def __init__(self, noise_std=None, maximize=False): super().__init__(noise_std=noise_std, maximize=maximize) self.dim = 2 self.bounds = Tensor([[-10.0, 10.0] for _ in range(self.dim)]).t() self._optimal_value = -19.2085 self.x_star = [ [8.05502, 9.66459], [-8.05502, -9.66459], [-8.05502, 9.66459], [8.05502, -9.66459], ] def evaluate_true(self, x): term = torch.abs(1 - torch.norm(x, dim=1) / math.pi) return -torch.abs(torch.sin(x[:, 0]) * torch.cos(x[:, 1]) * torch.exp(term)) class Levy(BenchmarkFunction): def __init__(self, dim=2, noise_std=None, maximize=False): super().__init__(noise_std=noise_std, maximize=maximize) self.dim = dim self.bounds = Tensor([[-10.0, 10.0] for _ in range(dim)]).t() self._optimal_value = 0.0 self.x_star = [[1.0] * dim] def evaluate_true(self, x): w = 1.0 + (x - 1.0) / 4.0 part1 = torch.sin(math.pi * w[:, 0]) ** 2 part2 = torch.sum( (w[:, :-1] - 1.0) ** 2 * (1.0 + 10.0 * torch.sin(math.pi * w[:, :-1] + 1.0) ** 2), dim=1, ) part3 = (w[:, -1] - 1.0) ** 2 * (1.0 + torch.sin(2.0 * math.pi * w[:, -1]) ** 2) return part1 + part2 + part3 class Michalewicz(BenchmarkFunction): def __init__(self, dim=2, noise_std=None, maximize=False): super().__init__(noise_std=noise_std, maximize=maximize) self.dim = dim self.bounds = Tensor([[0.0, math.pi] for _ in range(dim)]).t() self.x_star = None if dim == 2: self._optimal_value = -1.8013 self.x_star = [[2.20, 1.57]] elif dim == 5: self._optimal_value = -4.687658 elif dim == 10: self._optimal_value = -9.66015 def evaluate_true(self, x): i = x.new(range(1, self.dim + 1)) m = 10 return -torch.sum( torch.sin(x) * torch.sin(i * x ** 2 / math.pi) ** (2 * m), dim=1 ) class Powell(BenchmarkFunction): def __init__(self, dim=4, noise_std=None, maximize=False): super().__init__(noise_std=noise_std, maximize=maximize) assert dim % 4 == 0, "Powell dim must mutiple of 4" self.dim = dim self.bounds = Tensor([[-4.0, 5.0] for _ in range(dim)]).t() self._optimal_value = 0.0 self.x_star = [[0.0] * dim] def evaluate_true(self, x): result = torch.zeros_like(x[:, 0]) for i in range(self.dim // 4): i_ = i + 1 part1 = (x[:, 4 * i_ - 4] + 10.0 * x[:, 4 * i_ - 3]) ** 2 part2 = 5.0 * (x[:, 4 * i_ - 2] - x[:, 4 * i_ - 1]) ** 2 part3 = (x[:, 4 * i_ - 3] - 2.0 * x[:, 4 * i_ - 2]) ** 4 part4 = 10.0 * (x[:, 4 * i_ - 4] - x[:, 4 * i_ - 1]) ** 4 result += part1 + part2 + part3 + part4 return result class Rastrigin(BenchmarkFunction): def __init__(self, dim=2, noise_std=None, maximize=False): super().__init__(noise_std=noise_std, maximize=maximize) self.dim = dim self.bounds = Tensor([[-5.12, 5.12] for _ in range(dim)]).t() self._optimal_value = 0.0 self.x_star = [[0.0] * dim] def evaluate_true(self, x): d = x.shape[1] return 10.0 * d + torch.sum(x ** 2 - 10.0 * torch.cos(2.0 * math.pi * x), dim=1) class Rosenbrock(BenchmarkFunction): def __init__(self, dim=2, noise_std=None, maximize=False): super().__init__(noise_std=noise_std, maximize=maximize) self.dim = dim self.bounds = Tensor([[-2.048, 2.048] for _ in range(dim)]).t() self._optimal_value = 0.0 self.x_star = [[1.0] * dim] def evaluate_true(self, x): return torch.sum( 100.0 * (x[:, 1:] - x[:, :-1] ** 2) ** 2 + (x[:, :-1] - 1) ** 2, dim=1 ) class Shubert(BenchmarkFunction): def __init__(self, noise_std=None, maximize=False): super().__init__(noise_std=noise_std, maximize=maximize) self.dim = 2 self.bounds = Tensor([[-5.12, 5.12], [-5.12, 5.12]]).t() self._optimal_value = -186.7309 self.x_star = None def evaluate_true(self, x): n = x.shape[0] i = x.new(range(1, 6)).repeat(n, 1) i_plus_1 = x.new(range(2, 7)).repeat(n, 1) part1 = torch.sum(i * torch.cos(i_plus_1 * x[:, 0].view(-1, 1) + i), dim=1) part2 = torch.sum(i * torch.cos(i_plus_1 * x[:, 1].view(-1, 1) + i), dim=1) return part1 * part2 class Shekel(BenchmarkFunction): def __init__(self, m=10, noise_std=None, maximize=False): super().__init__(noise_std=noise_std, maximize=maximize) self.dim = 4 self.m = m self.bounds = Tensor([[0.0, 10.0] for _ in range(self.dim)]).t() if m == 5: self._optimal_value = -10.1532 elif m == 7: self._optimal_value = -10.4029 elif m == 10: self._optimal_value = -10.5364 self.beta = [1, 2, 2, 4, 4, 6, 3, 7, 5, 5] self.C = [ [4, 1, 8, 6, 3, 2, 5, 8, 6, 7], [4, 1, 8, 6, 7, 9, 3, 1, 2, 3.6], [4, 1, 8, 6, 3, 2, 5, 8, 6, 7], [4, 1, 8, 6, 7, 9, 3, 1, 2, 3.6], ] self.x_star = [[4, 4, 4, 4]] def evaluate_true(self, x): C = x.new(self.C).t() beta = x.new(self.beta) / 10.0 result = 0.0 for i in range(self.m): result += 1.0 / (torch.sum((x - C[i]) ** 2, dim=1) + beta[i]) return -result class SixHumpCamel(BenchmarkFunction): def __init__(self, noise_std=None, maximize=False): super().__init__(noise_std=noise_std, maximize=maximize) self.dim = 2 self.bounds = Tensor([[-3.0, 3.0], [-2.0, 2.0]]).t() self._optimal_value = -1.0316 self.x_star = [[0.0898, -0.7126], [-0.0898, 0.7126]] def evaluate_true(self, x): x1 = x[:, 0] x2 = x[:, 1] return ( (4 - 2.1 * x1 ** 2 + x1 ** 4 / 3) * x1 ** 2 + x1 * x2 + (4 * x2 ** 2 - 4) * x2 ** 2 ) class StybTang(BenchmarkFunction): def __init__(self, dim=2, noise_std=None, maximize=False): super().__init__(noise_std=noise_std, maximize=maximize) self.dim = dim self.bounds = Tensor([[-5.0, 5.0] for _ in range(self.dim)]).t() self._optimal_value = -39.166166 * dim self.x_star = [[-2.903534] * dim] def evaluate_true(self, x): return 0.5 * (x ** 4 - 16 * x ** 2 + 5 * x).sum(dim=1) class ThreeHumpCamel(BenchmarkFunction): def __init__(self, noise_std=None, maximize=False): super().__init__(noise_std=noise_std, maximize=maximize) self.dim = 2 self.bounds = Tensor([[-5.0, 5.0], [-5.0, 5.0]]).t() self._optimal_value = 0.0 self.x_star = [[0.0, 0.0]] def evaluate_true(self, x): x1 = x[:, 0] x2 = x[:, 1] return 2.0 * x1 ** 2 - 1.05 * x1 ** 4 + x1 ** 6 / 6.0 + x1 * x2 + x2 ** 2
Markdown
UTF-8
5,448
3.15625
3
[ "MIT" ]
permissive
--- date: 2021-07-19 09:02:48 permalink: /leetcode236/ categories: - leetcode - 学习笔记 - 算法 tags: - leetcode --- # [236. 二叉树的最近公共祖先](https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree) [English Version](https://github.com/doocs/leetcode/blob/main/solution/0200-0299/0236.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Tree/README_EN.md) ## 题目描述 <!-- 这里写题目描述 --> <p>给定一个二叉树, 找到该树中两个指定节点的最近公共祖先。</p> <p><a href="https://baike.baidu.com/item/%E6%9C%80%E8%BF%91%E5%85%AC%E5%85%B1%E7%A5%96%E5%85%88/8918834?fr=aladdin" target="_blank">百度百科</a>中最近公共祖先的定义为:“对于有根树 T 的两个节点 p、q,最近公共祖先表示为一个节点 x,满足 x 是 p、q 的祖先且 x 的深度尽可能大(<strong>一个节点也可以是它自己的祖先</strong>)。”</p> <p> </p> <p><strong>示例 1:</strong></p> <img alt="" src="https://cdn.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0236.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Tree/images/binarytree.png" style="width: 200px; height: 190px;" /> <pre> <strong>输入:</strong>root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 1 <strong>输出:</strong>3 <strong>解释:</strong>节点 <code>5 </code>和节点 <code>1 </code>的最近公共祖先是节点 <code>3 。</code> </pre> <p><strong>示例 2:</strong></p> <img alt="" src="https://cdn.jsdelivr.net/gh/doocs/leetcode@main/solution/0200-0299/0236.Lowest%20Common%20Ancestor%20of%20a%20Binary%20Tree/images/binarytree.png" style="width: 200px; height: 190px;" /> <pre> <strong>输入:</strong>root = [3,5,1,6,2,0,8,null,null,7,4], p = 5, q = 4 <strong>输出:</strong>5 <strong>解释:</strong>节点 <code>5 </code>和节点 <code>4 </code>的最近公共祖先是节点 <code>5 。</code>因为根据定义最近公共祖先节点可以为节点本身。 </pre> <p><strong>示例 3:</strong></p> <pre> <strong>输入:</strong>root = [1,2], p = 1, q = 2 <strong>输出:</strong>1 </pre> <p> </p> <p><strong>提示:</strong></p> <ul> <li>树中节点数目在范围 <code>[2, 10<sup>5</sup>]</code> 内。</li> <li><code>-10<sup>9</sup> <= Node.val <= 10<sup>9</sup></code></li> <li>所有 <code>Node.val</code> <code>互不相同</code> 。</li> <li><code>p != q</code></li> <li><code>p</code> 和 <code>q</code> 均存在于给定的二叉树中。</li> </ul> ## 解法 <!-- 这里可写通用的实现逻辑 --> 根据“**最近公共祖先**”的定义,若 root 是 p, q 的最近公共祖先 ,则只可能为以下情况之一: - 如果 p 和 q 分别是 root 的左右节点,那么 root 就是我们要找的最近公共祖先; - 如果 p 和 q 都是 root 的左节点,那么返回 `lowestCommonAncestor(root.left, p, q)`; - 如果 p 和 q 都是 root 的右节点,那么返回 `lowestCommonAncestor(root.right, p, q)`。 **边界条件讨论**: - 如果 root 为 null,则说明我们已经找到最底了,返回 null 表示没找到; - 如果 root 与 p 相等或者与 q 相等,则返回 root; - 如果左子树没找到,递归函数返回 null,证明 p 和 q 同在 root 的右侧,那么最终的公共祖先就是右子树找到的结点; - 如果右子树没找到,递归函数返回 null,证明 p 和 q 同在 root 的左侧,那么最终的公共祖先就是左子树找到的结点。 <!-- tabs:start --> ### **Python3** <!-- 这里可写当前语言的特殊实现逻辑 --> ```python # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': if root is None or root == p or root == q: return root left = self.lowestCommonAncestor(root.left, p, q) right = self.lowestCommonAncestor(root.right, p, q) if left is None: return right if right is None: return left return root ``` ### **Java** <!-- 这里可写当前语言的特殊实现逻辑 --> ```java /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) { if (root == null || root == p || root == q) return root; TreeNode left = lowestCommonAncestor(root.left, p, q); TreeNode right = lowestCommonAncestor(root.right, p, q); if (left == null) return right; if (right == null) return left; return root; } } ``` ### **JavaScript** ```js /** * Definition for a binary tree node. * function TreeNode(val) { * this.val = val; * this.left = this.right = null; * } */ /** * @param {TreeNode} root * @param {TreeNode} p * @param {TreeNode} q * @return {TreeNode} */ var lowestCommonAncestor = function (root, p, q) { if (!root || root == p || root == q) return root; const left = lowestCommonAncestor(root.left, p, q); const right = lowestCommonAncestor(root.right, p, q); if (!left) return right; if (!right) return left; return root; }; ``` ### **...** ``` ``` <!-- tabs:end -->
Python
UTF-8
13,556
2.890625
3
[]
no_license
import sqlite3 as sql from random import randint from myConfig import * def checkDatabaseVersion(dbFile): conn = sql.connect(dbFile) cur = conn.cursor() #Set the default version. The SQL below should override this dbVersion = 0 try: cur.execute('SELECT version FROM BotDbVersion') row = cur.fetchone() dbVersion = row[0] print 'The database is at version {}'.format(dbVersion) except sql.Error, e: # If we don't have a Version table, then we need will recreate the entire schema # Set the dbVersion back to the beginning dbVersion = 0 finally: upgradeDatabase(conn,dbVersion) return conn def upgradeDatabase(con,ver): # This function should walk through the different versions, and if it is done properly, # Upgrade the database from and given point to the most recent. # This will consist of a series of # if ver == x: # ver += 1 # do stuff # if ver == y: # ver += 1 # do stuff # if ver == z: # ver += 1 # pass #Initial state if ver == 0: print 'Upgrading database to version {}'.format(ver) with con: try: cur = con.cursor() cur.executescript(""" DROP TABLE IF EXISTS BotDbVersion; DROP TABLE IF EXISTS SongHistory; DROP TABLE IF EXISTS UserHistory; DROP TABLE IF EXISTS VotingHistory; DROP TABLE IF EXISTS SnagHistory; DROP TABLE IF EXISTS BotOperators; DROP TABLE IF EXISTS DjQueue; CREATE TABLE BotDbVersion (versionId INTEGER PRIMARY KEY, version INTEGER); CREATE TABLE SongHistory (songHistoryId INTEGER PRIMARY KEY, songID TEXT, songPlayDateTime TEXT, userID TEXT, songLength INT, songArtist TEXT, songName TEXT, songAlbum TEXT); CREATE TABLE UserHistory (UserHistoryId INTEGER PRIMARY KEY, userID TEXT, seenDateTime TEXT, userName TEXT, action TEXT); CREATE TABLE VotingHistory (VotingHistoryId INTEGER PRIMARY KEY, voteType TEXT, userID TEXT, songID TEXT, voteDateTime TEXT, djID TEXT); CREATE TABLE SnagHistory (SnagHistoryID INTEGER PRIMARY KEY, userID TEXT, songID TEXT, snagDateTime TEXT); CREATE TABLE ThemeHistory (ThemeHistoryID INTEGER PRIMARY KEY, themeText TEXT, userID TEXT, themeSetDateTime TEXT); CREATE TABLE BotOperators (BotOperatorID INTEGER PRIMARY KEY, userID TEXT); CREATE TABLE DjQueue (DjQueueID INTEGER PRIMARY KEY, userID TEXT); INSERT INTO BotDbVersion (version) VALUES (0); """) con.commit() except sql.Error, e: print 'Caught a SQLite Exception: {}'.format(e) ver += 1 if ver == 1: print 'Upgrading database to version {}'.format(ver) with con: cur = con.cursor() cur.executescript(""" CREATE TABLE StuffToSayWhenTheBotLikesASong (SayingID INTEGER PRIMARY KEY, Saying TEXT); CREATE TABLE StuffToSayWhenSomeoneEntersTheRoom (SayingID INTEGER PRIMARY KEY, Saying TEXT); """) cur.executemany("INSERT INTO StuffToSayWhenTheBotLikesASong (Saying) VALUES (?)", [('This song is aweomse',),('This song rocks',),(':yellow_heart:',),('Oh yeah!',),(':fire:',),(':clap:',)]) cur.executemany("INSERT INTO StuffToSayWhenSomeoneEntersTheRoom (Saying) VALUES(?)", [('Welcome @{}! I\'m the Wal-Mart greeter for this room.',),('Hey there @{}, I\'m your friendly neighborhood bot.',),('@{}, I am your father.',),('@{}!!!!!!!!!!!!!!!!',)]) cur.execute("UPDATE BotDBVersion SET version = ? WHERE version = ?",(ver+1,ver)) ver += 1 if ver == 2: print "Upgrading database to version {}".format(ver) with con: try: cur = con.cursor() cur.executescript(""" ALTER TABLE SongHistory ADD songRoomID TEXT; ALTER TABLE UserHistory ADD userRoomID TEXT; ALTER TABLE VotingHistory ADD voteRoomID TEXT; ALTER TABLE SnagHistory ADD SnagRoomID TEXT; ALTER TABLE ThemeHistory ADD ThemeRoomID TEXT; ALTER TABLE BotOperators ADD BotOpRoomID TEXT; ALTER TABLE DjQueue ADD DjQueueRoomID TEXT; """) print 'Updated all of the table structures.' cur.execute("UPDATE SongHistory SET songRoomID = ? WHERE songRoomID IS NULL",(defaultRoom,)) cur.execute("UPDATE UserHistory SET userRoomID = ? WHERE userRoomID IS NULL",(defaultRoom,)) cur.execute("UPDATE VotingHistory SET voteRoomID = ? WHERE VotingHistoryId IS NULL",(defaultRoom,)) cur.execute("UPDATE SnagHistory SET SnagRoomID = ? WHERE SnagRoomID is NULL",(defaultRoom,)) cur.execute("UPDATE ThemeHistory SET ThemeRoomID = ? WHERE ThemeRoomID IS NULL",(defaultRoom,)) cur.execute("UPDATE BotOperators SET BotOpRoomID = ? WHERE BotOpRoomID IS NULL",(defaultRoom,)) cur.execute("UPDATE DjQueue SET DjQueueRoomID = ? WHERE DjQueueRoomID IS NULL",(defaultRoom,)) print "Updated all of the data" cur.execute("UPDATE BotDBVersion SET version = ? WHERE version = ?",(ver+1,ver)) print "Updated the version to {}".format(ver+1) except sql.Error, e: print "Caught a SQLite Exception: {}".format(e) # This is the most recent version, nothing to do here, for now print 'Database is up to date.' ver +=1 def addSongHistory(con, sid, uid, length, artist, name, album): print "Adding song history: sid = {}, uid = {}, length = {}, artist = {}, name = {}, album = {}, songRoomID = {}".format(sid, uid, length, artist, name, album,defaultRoom) with con: cur = con.cursor() cur.execute("INSERT INTO SongHistory (songID, songPlayDateTime, userID, songLength, songArtist, songName, songAlbum, songRoomID) VALUES (?,datetime(\'now\',\'localtime\'),?,?,?,?,?,?)", (sid,uid,length, artist, name, album, defaultRoom)) con.commit() def addUserHistory(con, uid, uname, action): with con: cur = con.cursor() cur.execute("INSERT INTO UserHistory (userID, seenDateTime, userName, action, userRoomID) VALUES (?,datetime(\'now\',\'localtime\'),?,?,?)", (uid,uname,action,defaultRoom)) con.commit() def addVotingHistory(con, vtype, uid, sid, djID): with con: cur = con.cursor() print "INSERT INTO VotingHistory (voteType, userID, songID, djID, voteDateTime, voteRoomID) VALUES ({},{},{},{},datetime(\'now\',\'localtime\'),{})".format(vtype,uid,sid,djID,defaultRoom) cur.execute("INSERT INTO VotingHistory (voteType, userID, songID, djID, voteDateTime, voteRoomID) VALUES (?,?,?,?,datetime(\'now\',\'localtime\'),?)", (vtype,uid,sid,djID,defaultRoom)) con.commit() def addSnagHistory(con, uid, sid): with con: cur = con.cursor() cur.execute("INSERT INTO SnagHistory (userID, songID, snagDateTime, SnagRoomID) VALUES (?,?,datetime(\'now\',\'localtime\'),?)", (uid,sid,defaultRoom)) con.commit() def addThemeHistory(con, uid, theme): with con: cur = con.cursor() cur.execute("INSERT INTO ThemeHistory (userID, themeText, themeSetDateTime, ThemeRoomID) VALUES (?,?,date(\'now\',\'localtime\'),?)", (uid,theme,defaultRoom)) con.commit() # This theme proposal system needs more thought #def addThemeProposal(con, theme, uid): # with con: # cur = con.cursor() # cur.execute("INSERT INTO ThemeProposals (ThemeText, ProposedBy, ProposedDate) VALUES (?, ?, date(\'now\',\'localtime\'))", (theme, uid)) # con.commit() #def addThemeVote(con, theme, uid): # with con: # cur = con.cursor() # cur.execute("SELECT ThemeProposalID FROM ThemeProposals WHERE ThemeText = ? AND ProposedDate" #def checkThemeVoteOK(cur, uid): # with con: # cur = con.cursor() # cur.execute("SELECT ThemeVoteUser FROM ThemeVoting WHERE ThemeVoteUser = ? AND ThemeVoteDate = date(\'now\',\'localtime\')", (uid)) # row = cur.fetchone() # return row #def checkThemeProposalExists(con, theme): # with con: # cur = con.cursor() # cur.execute("SELECT ProposedBy, ProposedDate from ThemeProposals WHERE Theme=? ORDER BY ThemeProposalID DESC LIMIT 1",(theme)) # row = cur.fetchone() # return row def saveBotOperators(con, BotOps): with con: cur = con.cursor() cur.execute("DELETE FROM BotOperators") cur.executemany("INSERT INTO BotOperators (userID) VALUES (?)",(BotOps)) cur.commit() def saveDjQueue(con, djQueue): with con: cur = con.cursor() cur.execute("DELETE FROM DjQueue") cur.executemany("INSERT INTO DjQueue (userID) VALUES (?)",(djQueue)) cur.commit() def getMostSongData(con, cnt, songItem, ignoreID): with con: cur = con.cursor() qText="SELECT COUNT(1), {} FROM SongHistory WHERE userID != ? AND songRoomID = ? GROUP BY {} ORDER BY 1 DESC LIMIT {}".format(songItem,songItem,str(cnt)) #print qText cur.execute(qText,(ignoreID,defaultRoom)) rows = cur.fetchall() return rows def getMostVoteData(con, cnt, voteItem, voteType=None): with con: cur = con.cursor() qText="SELECT COUNT(1), {} FROM VotingHistory WHERE voteRoomID = ? ".format(voteItem) if voteType: qText += "AND voteType = ? " qText += "GROUP BY {} ORDER BY 1 DESC LIMIT ?".format(voteItem) print qText cur.execute(qText,(defaultRoom,voteType,str(cnt))) #cur.execute("SELECT COUNT(*), userID FROM VotingHistory WHERE voteType = ? GROUP BY userID ORDER BY 1 DESC LIMIT ?", (voteType,str(cnt))) rows = cur.fetchall() print "SQL Returned:".format(rows) return rows def getTopVoter(con, voteType, ignoreID): print 'Finding the top awesomer' with con: cur = con.cursor() cur.execute("SELECT COUNT(1), userID FROM VotingHistory WHERE VoteType = ? AND userID != ? AND voteRoomID = ? GROUP BY userID ORDER BY 1 DESC LIMIT 1",(voteType,ignoreID,defaultRoom)) rows = cur.fetchall() print rows return rows def getTopDJVoted(con, voteType, ignoreID): with con: cur = con.cursor() cur.execute("SELECT COUNT(1), DjID FROM VotingHistory WHERE VoteType = ? AND DjID != ? AND voteRoomID = ? GROUP BY DjID ORDER BY 1 DESC LIMIT 1",(voteType,ignoreID,defaultRoom)) rows = cur.fetchall() return rows def getUserNameByID(con, uid): with con: cur = con.cursor() cur.execute("SELECT userName FROM UserHistory WHERE userID = ? AND userRoomID = ? ORDER BY UserHistoryId DESC LIMIT 1",(str(uid),defaultRoom)) row = cur.fetchone() print row print 'Found {} for ID {}'.format(row[0],uid) return row[0] def getUserIDByName(con, uname): print 'Looking up {}'.format(uname) with con: cur = con.cursor() try: cur.execute("SELECT userID FROM UserHistory WHERE userName = ? AND userRoomID = ? ORDER BY UserHistoryId DESC LIMIT 1",(uname,defaultRoom)) except: print 'SQL Exception', sys.exc_info()[0] finally: row = cur.fetchone() print row return row[0] def getLastUserHistoryByID(con, uid): with con: cur = con.cursor() cur.execute("SELECT action, seenDateTime, userName FROM UserHistory WHERE userID = ? AND userRoomID = ? ORDER BY UserHistoryId DESC LIMIT 1",(str(uid),defaultRoom)) row = cur.fetchone() return row def getLikeSongSaying(con): with con: cur = con.cursor() cur.execute("SELECT count(1) FROM StuffToSayWhenTheBotLikesASong") cnt = cur.fetchone() cur.execute("SELECT Saying FROM StuffToSayWhenTheBotLikesASong WHERE SayingID = ?",(randint(1,cnt[0]),)) row = cur.fetchone() #rows is now a list of tuples [()] # So the next line will shuffle the tuples, and return the data from one of them return row[0] def getEntersRoomSaying(con): with con: cur = con.cursor() cur.execute("SELECT count(1) FROM StuffToSayWhenSomeoneEntersTheRoom") cnt = cur.fetchone() cur.execute("SELECT Saying FROM StuffToSayWhenSomeoneEntersTheRoom WHERE SayingID = ?",(randint(1,cnt[0]),)) row = cur.fetchone() return row[0] def getSongSeedData(con, songID): with con: print "Looking up song {}".format(songID) result = {} cur = con.cursor() cur.execute("SELECT songPlayDateTime, userID FROM SongHistory WHERE songID = ? AND songRoomID = ? ORDER BY songHistoryId ASC LIMIT 1",(songID,defaultRoom)) #row should be DateTime & userID row = cur.fetchone() #print "Seed result query 1:",row if row: result['firstPlayDate'] = row[0] result['userID'] = row[1] #Convert UserID to Name cur.execute("SELECT userName FROM UserHistory WHERE userID = ? AND userRoomID = ? ORDER BY userHistoryID DESC LIMIT 1",(result["userID"],defaultRoom)) row = cur.fetchone() if row: print "Got row: ",row result['userName'] = row[0] else: print "Lost it at Convert UserID to Name" result['userName'] = 'Unknown' #Get total plays cur.execute("SELECT COUNT(1) FROM SongHistory WHERE songID = ? AND songRoomID = ?",(songID,defaultRoom)) row = cur.fetchone() if row: print "Got row: ",row result['totalPlays'] = row[0] else: print "Lost it at Get total plays" result['totalPlays'] = 0 #Get total likes cur.execute("SELECT COUNT(1) FROM VotingHistory WHERE songID = ? AND voteType = ? AND voteRoomID = ?",(songID,'up',defaultRoom)) row = cur.fetchone() if row: print "Got row: ",row result['totalLikes'] = row[0] else: print "Lost it at Get total likes" result['totalLikes'] = 0 #Get total snags cur.execute("SELECT COUNT(1) FROM SnagHistory WHERE songID = ? AND snagRoomID = ?",(songID,defaultRoom)) row = cur.fetchone() if row: print "Got row: ",row result['totalSnags'] = row[0] else: print "Lost it at Get total songs" result['totalSnags'] = 0 else: result = None print result return result
Markdown
UTF-8
585
2.53125
3
[]
no_license
#e-shop ecommerce project E-shop is an ecommerce project built with spring framework, java, mySql and maven as a build tool. #Features Add products to database Find products by id Find all products Delete product Spring MVC with thymeleaf template engine for viewing product details #installation Step 1: Clone repository Step 2: Install dependencies: cd into the root folder and run the following command: `mvn install` Step 3: Setup database: run sql script in the db folder `src/main/resources/db/setup-db.sql` Step 4: Run the project `mvn spring-boot-run` "# e-shop"
Java
UTF-8
1,731
2.5
2
[ "Apache-2.0" ]
permissive
package l10; import l10.hibernate.DbServiceHibernateImpl; import l10.hibernate.HibernateConfigurator; import l10.model.AddressDataSet; import l10.model.UserDataSet; import org.hibernate.cfg.Configuration; import org.junit.After; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; public class dbServiceMyOrmImplTest { private DbServiceHibernateImpl dbServiceHibernate; @Before public void setUp() { String url = "jdbc:postgresql://localhost:5432/l09?user=anton&password=12345&ssl=false"; Configuration hibernateConfiguration = (new HibernateConfigurator()).getTestConfiguration(url); dbServiceHibernate = new DbServiceHibernateImpl(hibernateConfiguration); } @Test public void saveNewUserHibernate() { UserDataSet user = new UserDataSet(); user.setName("Ваня"); user.setAge(15); dbServiceHibernate.save(user); UserDataSet result = dbServiceHibernate.read(1); assertEquals(15, result.getAge()); assertEquals("Ваня", result.getName()); } @Test public void saveNewUserWithAddressHibernate() { UserDataSet user = new UserDataSet(); user.setName("Петя"); user.setAge(20); user.setAddress(new AddressDataSet("Будапештская, 61")); dbServiceHibernate.save(user); UserDataSet result = dbServiceHibernate.read(1); assertEquals(20, result.getAge()); assertEquals("Петя", result.getName()); assertEquals("Будапештская, 61", result.getAddress().getStreet()); } @After public void tearDown() { dbServiceHibernate.shutdown(); } }
Java
UTF-8
418
1.9375
2
[]
no_license
package catproducts.catdb.api; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.Query; import org.springframework.stereotype.Repository; import catproducts.catdb.api.entities.Product; @Repository public interface IProductRespository extends MongoRepository<Product, String> { @Query(value="{'id':?0}") Product findByRepoId(String id); }
C#
UTF-8
878
2.671875
3
[]
no_license
using System; using uLearn.CSharp; namespace uLearn.Courses.BasicProgramming.Slides.U00_Basics { [Slide("Первый шаг", "{90BCB61E-57F0-4BAA-8BC9-10C9CFD27F58}")] public class S011_FirstStep : SlideTestBase { /* Любая, даже самая сложная дорога, начинается с первого шага. Выведите на консоль фразу `The first step!` Допишите код функции `Main`, а затем запустите и проверьте ваше решение с помощью кнопки RUN. */ [Exercise] [ExpectedOutput("The first step!")] [Hint("Вывод на консоль производится методом ```Console.WriteLine```")] static public void Main() { Console.WriteLine("The first step!"); /*uncomment // пишите код тут */ } } }
C++
UHC
1,826
3.5625
4
[]
no_license
// 5_Ϲȭ α׷ // : Ϲ α׷ְ STL // C++ ̺귯(STL) Ϸ ݵ Ϲȭ ؾ մϴ. // C++ : ü + Լ + Ϲ(Generic) #include <iostream> using namespace std; // C ڿ ˻ char* xstrchr(char *s, char c) { while (*s != '\0' && *s != c) ++s; return *s == c ? s : 0; } // 1. ˻ Ϲȭ : κ ڿ ˻ ϰ . // ˻ - ݰ [first, last) char* xstrchr(char* first, char* last, char value) { while (first != last && *first != value) ++first; return first == last ? 0 : first; } // 2. ˻ Ÿ Ϲȭ : Template ! // template <typename T> // -> Ÿ԰ ã Ÿ Ǿ ִ. // double 迭 int ã . // template <typename T1, typename T2> // T1* xfind(T1* first, T1* last, T2 value) // -> T* ϸ ¥ ͸ ִ. // Ʈ ͸ . template <typename T1, typename T2> T1 xfind(T1 first, T1 last, T2 value) { while (first != last && *first != value) ++first; return first; } // http://d.pr/n/1ggM5 #include <vector> #include <list> int main() { list<int> v; v.push_back(10); v.push_back(20); v.push_back(30); cout << *xfind(v.begin(), v.end(), 20) << endl; } #if 0 int main() { double x[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; double *p = xfind(x, x + 10, 3); if (p != x + 10) cout << *p << endl; } #endif #if 0 int main() { char s[] = "abcdefg"; // char* p = xstrchr(s, 'c'); char* p = xstrchr(s + 1, s + 4, 'c'); if (p) cout << *p << endl; } #endif
C++
UTF-8
2,008
3.078125
3
[]
no_license
/* Author: coderqiuan@163.com Created on: 2016-12-21 22:09 */ #pragma once #include "util.h" namespace qiuan { template<uint32_t streamsize = 1024> class Stream { private: Stream(const Stream& r); const Stream& operator=(const Stream& r); bool less(int inlen) { return inlen > 0 && inlen < m_data + streamsize - m_current; } public: explicit Stream() : m_current(m_data) { *m_current = '\0'; } const char* c_str() { return m_data; } uint32_t size() { return m_current - m_data; } std::string to_string() { return std::string(c_str(), size()); } public: bool append(const std::string in) { return append(in.c_str(), in.size()); } bool append(const char* inbuf, int inlen) { if(less(inlen)) { memcpy(m_current, inbuf, inlen); m_current += inlen; return true; } return false; } template<typename Type> Stream& operator<<(Type value) { append(qiuan::to_string<Type>(value)); return *this; } Stream& operator<<(Stream& value) { if(this != &value) { append(value.c_str(), value.size()); } return *this; } Stream& operator<<(const std::string& value) { append(value.c_str(), value.size()); return *this; } private: char* m_current; char m_data[streamsize]; }; typedef Stream<1024> CStream; typedef Stream<2 * 1024> CLogStream; typedef Stream<4 * 1024> CBigStream; }
C#
UTF-8
4,105
2.875
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using Horizon; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Falsy.Tests { static class Timings { public static void Main() { const double interval = 200d; const double threshold = 0.025d; var currentProcess = Process.GetCurrentProcess(); currentProcess.PriorityBoostEnabled = true; currentProcess.PriorityClass = ProcessPriorityClass.AboveNormal; RunTimings<FalsyTests>(interval, threshold); } private static IEnumerable<char> AddSpaces(this string value) { yield return value[0]; foreach (var character in value.Skip(1)) { if (char.IsUpper(character)) yield return ' '; yield return character; } } private static string Readable(this string value) { return string.Join("", value.AddSpaces()); } private static void RunTimings<T>(double interval, double threshold) where T : new() { var total = 0d; var test = new T(); var type = typeof (T); var methods = type.GetMethods() .Where(x => x.GetCustomAttribute<TestMethodAttribute>() != null && x.GetCustomAttribute<ExpectedExceptionAttribute>() == null) .Select(x => new { Name = x.Name.Readable(), Method = x.BuildLazy() }) .ToList(); var longestName = methods.Max(x => x.Name.Length); var alignment = " | {0,-" + longestName + "}"; Console.WriteLine(); Console.WriteLine(" Timings: {0}", type.FullName); Console.WriteLine(" \t- Interval : {0}", interval); Console.WriteLine(" \t- Threshold : {0}", threshold); var line = " ♦" + new string('-', longestName + 23) + "♦"; Console.WriteLine(line); foreach (var item in methods) { dynamic @delegate = item.Method.Value; //Warmup @delegate(test); // Clean up GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); //Testing var watch = Stopwatch.StartNew(); for (var i = 0; i < interval; i++) @delegate(test); watch.Stop(); Console.Write(alignment, item.Name); Console.Write(" : "); var totalMilliseconds = watch.Elapsed.TotalMilliseconds; total += totalMilliseconds; var average = totalMilliseconds/interval; Console.ForegroundColor = average > threshold ? ConsoleColor.Red : ConsoleColor.Green; Console.Write("{0,-11:00.000000000}", average); Console.ResetColor(); Console.WriteLine(" ms |"); } Console.WriteLine(line); Console.Write(alignment, "Total Execution Time"); Console.Write(" : "); Console.ForegroundColor = ConsoleColor.DarkGray; Console.Write("{0,-11:00.000000000}", total); Console.ResetColor(); Console.WriteLine(" ms |"); var totalAverage = total / methods.Count / interval; Console.Write(alignment, "Average Per Call"); Console.Write(" : "); Console.ForegroundColor = totalAverage > threshold ? ConsoleColor.Red : ConsoleColor.Green; Console.Write("{0,-11:00.000000000}", totalAverage); Console.ResetColor(); Console.WriteLine(" ms |"); Console.WriteLine(line); Console.ReadLine(); } } }
Shell
UTF-8
576
3.28125
3
[ "MIT" ]
permissive
#!/bin/bash set -o errexit set -o pipefail set -o nounset if [ -n "$(podman ps -q --filter name=simple_dir_server)" ]; then echo "Stopping existing directory server..." podman stop $(podman ps -q --filter name=simple_dir_server) &>/dev/null fi if [ "${1:-}" = "-q" ]; then # If the argument is to just quit, the above handle would take care of it exit 0 fi echo "Serving $(pwd)..." podman run -d --rm --security-opt label=disable -p 4250:80 \ --name simple_dir_server -v $(pwd):/usr/share/nginx/html:ro docker.io/library/nginx:alpine #xdg-open http://127.0.0.1:8080
C
UTF-8
3,252
3.640625
4
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "myio.h" /**************************ReadInteger***************************************** int ReadInteger(); Purpose: Calls ReadLine() function to read string and convert to an Integer with atoi() Returns: char *iInput the converted int from the string input Notes: This frees the input string passed in. ******************************************************************************/ int ReadInteger(void){ int iInput; // int to convert a string to int i; // iterator char *input = ReadLine(); // calls ReadLine() to get user input //checking if a char is alpha in string for (i = 0; i < strlen(input); i++){ if(isalpha(input[i])){ free(input); return(0); } } iInput = atoi(input); // converts input to int free(input); // frees input array return (iInput); } /**************************ReadDouble***************************************** int ReadDouble(); Purpose: Calls ReadLine() function to read string and convert to a Double with atof() Returns: char *iInput the converted double from the string input Notes: This frees the input string passed in. ******************************************************************************/ double ReadDouble(void){ double dInput; // int to convert a string to int i; // iterator char *input = ReadLine(); // calls ReadLine() to get user input //checking if a char is alpha in string for (i = 0; i < strlen(input); i++){ if(isalpha(input[i])){ free(input); return(0); } } dInput = atof(input); // converts input to double free(input); // frees input array return(dInput); } /**************************ReadLine******************************************* int ReadLine(); Purpose: Calls ReadLineFile() to return string from stdin Returns: char *input String that was returned from ReturnLineFile(stdin) Notes: N/A ******************************************************************************/ char *ReadLine(void){ return (ReadLineFile(stdin)); } /**************************ReadLineFile**************************************** int ReadDouble(FILE *infile); Purpose: Reads from stdin a line and converts to a dynamically allocated and resized buffer of a string. Parameters: FILE *infile file pointer that was passed in by user in this case it's stdin. Returns: char *cString the converted double from the string input Notes: N/A ******************************************************************************/ char *ReadLineFile( FILE *infile){ char *cString; // dynamically allocated string depeding on input int i = 0; // iterator char *input; // line ptr read from stdin size_t len = 0; // buffer to be updated by chars in string ssize_t read; input = (char *) malloc (sizeof(char)); if ((read = getline(&input, &len, infile) == -1)){ fprintf(stderr,"Memory allocation error"); exit(1); } return (input); }
C#
UTF-8
3,551
2.6875
3
[]
no_license
using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using Week_1; namespace Formele_methoden_tests { [TestClass] public class TestHopcroftAlgorithm { [TestMethod] public void HopcroftTest1() { char[] alphabet = {'a', 'b'}; Automaat<string> dfaToHopcroft = new Automaat<string>(alphabet); dfaToHopcroft.AddTransition(new Transition<string>("1", 'a', "2")); dfaToHopcroft.AddTransition(new Transition<string>("1", 'b', "3")); dfaToHopcroft.AddTransition(new Transition<string>("2", 'a', "4")); dfaToHopcroft.AddTransition(new Transition<string>("2", 'b', "5")); dfaToHopcroft.AddTransition(new Transition<string>("3", 'a', "6")); dfaToHopcroft.AddTransition(new Transition<string>("3", 'b', "7")); dfaToHopcroft.AddTransition(new Transition<string>("4", 'a', "4")); dfaToHopcroft.AddTransition(new Transition<string>("4", 'b', "4")); dfaToHopcroft.AddTransition(new Transition<string>("5", 'a', "2")); dfaToHopcroft.AddTransition(new Transition<string>("5", 'b', "8")); dfaToHopcroft.AddTransition(new Transition<string>("6", 'a', "4")); dfaToHopcroft.AddTransition(new Transition<string>("6", 'b', "5")); dfaToHopcroft.AddTransition(new Transition<string>("7", 'a', "6")); dfaToHopcroft.AddTransition(new Transition<string>("7", 'b', "7")); dfaToHopcroft.AddTransition(new Transition<string>("8", 'a', "6")); dfaToHopcroft.AddTransition(new Transition<string>("8", 'b', "9")); dfaToHopcroft.AddTransition(new Transition<string>("9", 'a', "6")); dfaToHopcroft.AddTransition(new Transition<string>("9", 'b', "10")); dfaToHopcroft.AddTransition(new Transition<string>("10", 'a', "6")); dfaToHopcroft.AddTransition(new Transition<string>("10", 'b', "10")); dfaToHopcroft.DefineAsStartState("1"); dfaToHopcroft.DefineAsFinalState("3"); dfaToHopcroft.DefineAsFinalState("5"); dfaToHopcroft.DefineAsFinalState("7"); dfaToHopcroft.DefineAsFinalState("9"); dfaToHopcroft.DefineAsFinalState("10"); Automaat<string> hopcroftedDfa = HopcroftAlgorithm.MinimizeDfa(dfaToHopcroft); Assert.AreEqual("(A, a)-->B", hopcroftedDfa.Transitions.ToList()[0].ToString()); Assert.AreEqual("(A, b)-->D", hopcroftedDfa.Transitions.ToList()[1].ToString()); Assert.AreEqual("(B, a)-->C", hopcroftedDfa.Transitions.ToList()[2].ToString()); Assert.AreEqual("(B, b)-->E", hopcroftedDfa.Transitions.ToList()[3].ToString()); Assert.AreEqual("(C, a)-->C", hopcroftedDfa.Transitions.ToList()[4].ToString()); Assert.AreEqual("(C, b)-->C", hopcroftedDfa.Transitions.ToList()[5].ToString()); Assert.AreEqual("(D, a)-->B", hopcroftedDfa.Transitions.ToList()[6].ToString()); Assert.AreEqual("(D, b)-->D", hopcroftedDfa.Transitions.ToList()[7].ToString()); Assert.AreEqual("(E, a)-->B", hopcroftedDfa.Transitions.ToList()[8].ToString()); Assert.AreEqual("(E, b)-->A", hopcroftedDfa.Transitions.ToList()[9].ToString()); Assert.AreEqual("D",hopcroftedDfa.FinalStates.ToList()[0]); Assert.AreEqual("E",hopcroftedDfa.FinalStates.ToList()[1]); Assert.AreEqual("A",hopcroftedDfa.StartStates.ToList()[0]); } } }
Markdown
UTF-8
11,918
2.859375
3
[]
no_license
# C9 settings 1. python 설치 ```bash git clone https://github.com/pyenv/pyenv.git ~/.pyenv echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n eval "$(pyenv init -)"\nfi' >> ~/.bashrc source ~/.bashrc pyenv install 3.6.7 pyenv global 3.6.7 python -V pip install --upgrade pip pip install flask pip install requests ``` 2. ```bash git clone https://github.com/pyenv/pyenv-virtualenv.git $(pyenv root)/plugins/pyenv-virtualenv echo 'eval "$(pyenv virtualenv-init -)"' >> ~/.bashrc exec "$SHELL" ``` 3. django 깔기 ```bash git config --global user.name yoonwoo git config --global user.email lkkjasd@naver.com pyenv virtualenv django-venv # (가상환경 만듬) pyenv local django-venv # (장고 열어줌) pip install django # (장고 설치) ``` 4. 장고 폴더 만들기 ```bash django-admin startproject django_intro cd django_intro ls # ls 시 manage.py* 가 있어야함 # 서버를 열기 전에 settings.py에 들어가서 ALLOWED_HOST 를 '*' 로 바꾸고 저장해줘야한다. python manage.py runserver 0.0.0.0:8080 ``` # Django (02/11) ## 1. 시작하기 1. 프로젝트 시작하기 ```bash $ django-admin startproject 프로젝트이름 ``` 아래와 같이 프로젝트 구조가 만들어진다. ```blank ├── db.sqlite3 ├── django_intro │   ├── __init__.py │   ├── __pycache__ │   │   ├── __init__.cpython-36.pyc │   │   ├── settings.cpython-36.pyc │   │   ├── urls.cpython-36.pyc │   │   └── wsgi.cpython-36.pyc │   ├── settings.py │   ├── urls.py │   └── wsgi.py └── manage.py ``` 지금부터 pwd 는`~/workspace/django_intro` 이다. 2. 서버 실행하기 * `settings.py` ```python ALLOWED_HOST = ['*'] # c9에서는 host - 0.0.0.0, port - 8080만 활용할 수 있기 때문에 위와 같이 설정한다. ``` ```bash python manage.py runserver 0.0.0.0:8080 ``` 앞으로 모든 장고 명령어는 프로젝트를 만들 때를 제외하고 `python manage.py`를 활용한다. 따라서, 반드시 `pwd` 와 `ls` 를 통해 현재 bash(터미널) 위치를 확인하자!! 3. 이그노어 www.gitignore.io 에 들어가 django 검색 후 나오는 코드 전체 복사후 `vi .gitignore` 에 들어가 복붙 후 esc , :wq! 로 나와준다. 그 후 커밋한다. ( git add . , git commit -m '~~') @app.route('home') def index(): ​ return 'hello' ## 2. Hello, django >Django 프로젝트는 여러가지 app의 집합이다. > >각각의 app은 MTV 패턴으로 구성되어 있다. > >M (Model) : 어플리케이션의 핵심 로직의 동작을 수행한다. > >T (Template) : 사용자에게 결과물을 보여준다. > >V (View) : 모델의 템플릿의 동작을 제어한다. (모델의 상태를 변경하거나 값을 가져오고, 템플릿에 값을 전달하기 등) > >**일반적으로 MVC 패턴으로 더 많이 사용된다.** (Mode, View, Controller) ### 1. 기본 로직 앞으로 우리는 1. 요청 url 설정(`urls.py`) 2. 처리 할 view 설정(`view.py`) 3. 결과 보여줄 template 설정 (`templates/`) 으로 작성할 것이다. 1. url 설정 ```python # django_intro/urls.py from django.contrib import admin from django.urls import path # home 폴더 내에 있는 views.py를 불러온다. from home import views urlpatterns = [ path('admin/', admin.site.urls), # 요청이 home/으로 오면, views의 index 함수를 실행시킨다. path('home/', views.index), ] ``` ```bash python manage.py startapp 쓰고싶은폴더이름 하면 migrations 가 만들어진다. ``` 2. view 설정 ```python # home/views.py from django.shortcuts import render, HttpResponse # Create your views here. def index(request): return HttpResponse('hello, django!') ``` * 주의할 점은 선언된 함수에서 `request` 를 인자로 받아야 한다. * request는 사용자(클라이언트)의 요청 정보와 서버에 대한 정보가 담겨 있다. * Django 내부에서 해당 함수를 호출하면서 정보를 넘겨주기 때문에 반드시 명시해줘야한다. ### 3. Template (MTV - T) > Django에서 활용되는 Template은 DTL(Django Template Language) 이다. > > jinja2와 문법이 유사하다. 1. 요청 url 설정 ```python path('home/dinner/', views.dinner) ``` 2. view 설정 ```python def dinner(request): box = ['치킨', '밥', '피자'] dinner = random.choice(box) return render(request, 'dinner.html', {'dinner': dinner}) ``` * Template을 리턴하려면, `render`를 사용해야 한다. * `request` (필수) * `template` 파일 이름 (필수) * `template 변수 (선택) ` : `dictionary` 타입으로 구성해야 한다 ![제목 없음](image/제목 없음-1549863604327.png) 3. Template 설정 ```bash $ mkdir home/templates $ touch home/templates/dinner/ ``` ```html <!-- home/templates/dinner.html--!> <h1> {{dinner}} </h1> ``` ### 4. Variable Routing 1. url 설정 ```python path('home/you/<name>', views.you), path('home/cube/<int:num>', views.cube), ``` 2. view 파일 설정 ```python def you(request, name): return render(request, 'you.html', {'name': name}) ``` 3. 템플릿 파일 설정 ```django <h1>{{ name }}, 안녕!!! </h1> ``` ### 5. From data 1. `ping` 1. 요청 url 설정 ```python path('home/ping/', views.ping) ``` 2. view 설정 ```python def ping(request): return render(request, 'ping.html') ``` 3. template 설정 ```django <form action='/home/pong/'> <!-- action은 무조건 양쪽끝을 '/' 로 닫아줘야함 --> <input name="message" type = "text"> <input type="submit"> </form> ``` 2. `pong` 1. 요청 url 설정 ```python path('home/pong/', views.pong) ``` 2. view 설정 ```python def pong(request): message = request.GET.get('message') return render(request, 'pong.html', {'message': message}) ``` 3. template 설정 ```django <h1> {{ message }} </h1> ``` 3. POST 요청 처리 1. 요청 FORM 수정 ```django <form action="/home/pong/" method="POST"> {% csrf_token %} </form> ``` 2. view 수정 ```python def pong(request): message = request.POST.get('message') ``` * `csrf_token` 은 보안을 위해 django에서 기본적으로 설정되어 있는 것이다. * CSRF 공격 : Cross Sites Request Forgery * form을 통해 POST 요청을 보낸다는 것은 데이터베이스에 반영되는 경우가 대부분인데, 해당 요청을 우리가 만든 정해진 form에서 보내는지 검증하는 것. * 실제로 input type hidden으로 특정한 hash 값이 담겨 있는 것을 볼 수 있다. * `settings.py` 에 `MIDDLEWARE` 설정에 보면 csrf 관련된 내용이 설정된 것을 볼 수 있다. # template_example (02/12) ## 1. 반복문 ```html {% for menu in my_list %} {{ forloop.counter }} <!-- forloop.counter는 %가 아닌 {} 를 쓴다 --> {% if forloop.first %} <p>짜장면+고추가루</p> {% else %} <p>{{ menu }}</p> {% endif %} {% endfor %} {% for user in empty_list %} <p>{{ user }}</p> {% empty %} <p>지금 가입된 유저가 없습니다.</p> {% endfor} ``` ## 2. 조건문 ```html {% if '짜장면' in my_list %} <p>짜장면은 고추가루 없이 못 먹지!</p> {% endif %} ``` ## 3. length 필터 활용 ```html {% for message in messages %} {% if message|length > 5 %} <p>글씨가 너무 길어요</p> {% else %} <p>{{ message }}, {{message|length }}</p> {% endif %} {% endfor %} ``` ## 4. lorem ipsum ```html {% lorem %} <hr> {% lorem 3 w %} <hr> {% lorem 4 w random %} <hr> {% lorem 4 p %} ``` ## 5. 글자 수 제한하기(truncate) ```html <p>{{ my_sentence|truncatewords:3 }}</p> <p>{{ my_sentence|truncatechars:10 }}</p> ``` ## 6. 글자 관련 필터 ```html <p>{{ 'abc'|length }}</p> <p>{{ 'ABC'|lower }}</p> <h3>{{ my_sentence|title }}</h3> <p>{{ 'abc def'|capfirst }}</p> <p>{{ my_list|random }}</p> ``` ## 7. 연산-django-mathfilters 쓰면 추가적 기능 사용가능 ```html <p>{{ 4|add:6 }}</p>0 ``` ## 8. 날짜표현 ```html {{ now }}<br> {% now "SHORT_DATETIME_FORMAT" %}<br> {% now "DATETIME_FORMAT" %}<br> {% now "SHORT_DATE_FORMAT" %}<br> {% now "DATE_FORMAT" %}<br> {% now "Y년 m월 d일 (l) h:i" %}<br> ``` ## 6. static file 관리 == 정적파일 네임 스페이싱 (02/12) > 정적 파일(images, css, js)을 서버 저장이 되어 있을 때, 이를 각각의 템플릿에 불러오는 방법 ### 디렉토리 구조 디렉토리 구조는 `home/static/home/` 으로 구성된다. 이 디렉토리 설정은 `settings.py` 의 가장 하단에 `STATIC_URL` 에 맞춰서 해야한다. (기본 `/static/`) 1. 파일 생성 `home/static/home/images/wallpaper.jpeg` `home/static/home/stylesheets/style.css` 2. 템플릿 활용 ```django {% extends 'base.html' %} {% load static %} {% block css %} <link rel="stylesheets" type="text/css" href="{% static 'home/stylesheets/style.css' %}"> {% endblock %} {% block body %} <img src="{% static 'home/images/wallpaper.jpeg' %}"> {% endblock %} ``` ## 7. URL 설정 분리 > 위와 같이 코드를 짜는 경우에, `django_intro/urls.py` 에 모든 url 정보가 담기게 된다. > > 일반적으로 Django 어플리케이션에서 url을 설정하는 방법은 app 별로 `urls.py` 을 구성하는 것이다. 1. `django_intro/urls.py` ```python from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('home/', include('home.urls')) ] ``` * `include` 를 통해 `app/urls.py` 에 설정된 url을 포함한다. 2. `home/url.py` ```python from django.urls import path # views는 home/views.py from . import views urlpatterns = [ path('', views.index), ] ``` * `home/views.py` 파일에서 `index` 를 호출하는 url은 `http://<host>/` 이 아니라, `https://<host>/home/`이다. ## 8. Template 폴더 설정 ### 디렉토리 구조 디렉토리 구조는 `home/templates/home/` 으로 구성된다. 디렉토리 설정은 `settings.py` 의 `TEMPLATES` 에 다음과 같이 되어 있다. ```python TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'django_intro', 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] ``` * `DIRS` : templates를 커스텀하여 경로를 설정할 수 있다. * 경로 설정 ```python os.path.join(BASE_DIR, 'django_intro', 'templates') #=> PROJECT1/django_intro/templates/ ``` * `APP_DIRS` : `INSTALLED_APPS` 에 설정된 app의 디렉토리에 있는 `templates` 를 템플릿으로 활용한다. (TRUE) 1. 활용 예시 ```python # home/views.py def index(request): return render(request, 'home/index.html') ``` ``` home ├── __init__.py ├── admin.py ├── apps.py ├── migrations ├── models.py ├── templates │   └── home │   └── index.html ├── tests.py ├── urls.py └── views.py ```
JavaScript
UTF-8
2,471
2.578125
3
[]
no_license
'use strict'; const request = require('request-promise'); const querystring = require('querystring'); const MAP_URL = 'https://www.realtor.ca/Residential/Map.aspx'; const API_URL = 'https://api2.realtor.ca'; const clientSettingsDefaults = { CultureId: 1, ApplicationId: 37 } const priceTiers = [0, 25000, 50000, 75000, 100000, 125000, 150000, 175000, 200000, 225000, 250000, 275000, 300000, 325000, 350000, 375000, 400000, 425000, 450000, 475000, 500000, 550000, 600000, 650000, 700000, 750000, 800000, 850000, 900000, 950000, 1000000, 1100000, 1200000, 1300000, 1400000, 1500000, 1600000, 1700000, 1800000, 1900000, 2000000, 2500000, 3000000, 4000000, 5000000, 7500000, 10000000]; class Realtor { static post(options) { let optionDefaults = { ...clientSettingsDefaults, PropertySearchTypeId: 1 }; let form; if (typeof options === 'object') form = Object.assign(optionDefaults, options); return request({ method: 'POST', uri: API_URL + "/Listing.svc/PropertySearch_Post", form: form, json: true }); } static getPropertyDetails(options={}) { let optionDefaults = { ...clientSettingsDefaults, HashCode: 0 }; let params = {}; let url = ""; params = Object.assign(optionDefaults, options); url = API_URL + "/Listing.svc/PropertyDetails?" + querystring.encode(params); return request({ uri: url, json: true }); } static buildUrl(options) { if (options.PriceMin) { options = findNextPriceTier(options, true); } if (options.PriceMax) { options = findNextPriceTier(options, false); } let qs = '#'; for (let prop in options) { qs += prop + '=' + options[prop] + '&'; } return MAP_URL + qs.slice(0, -1); //To remove trailing ampersand or pound } /** * Given a URL from realtor.ca, attemtps to parse the query string parameters into a usable filter option set. * @param {string} url The realtor.ca URL string that represents the filters */ static optionsFromUrl(url) { return querystring.parse(url); } } function findNextPriceTier(options, minFlag) { let opt = (minFlag ? "PriceMin" : "PriceMax"); let cost = options[opt]; if (priceTiers.indexOf(cost) !== -1) return options; if (cost > priceTiers[priceTiers.length-1]) { delete options[opt]; return options; } for (let i = 0; i < priceTiers.length; i++) { if (priceTiers[i] > options[opt]) { options[opt] = priceTiers[i]; break; } } return options; } module.exports = Realtor;
Java
UTF-8
1,809
2.734375
3
[]
no_license
package server.handlers; import server.Handler; import server.data.Header; import server.data.Method; import server.data.Request; import server.data.Response; import server.data.Status; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class Authoriser implements Handler { private final Handler handler; private final Map<String, Map<String, List<Method>>> accessControlList; private final List<Method> defaultAccess; public Authoriser(Handler handler, Map<String, Map<String, List<Method>>> accessControlList, List<Method> defaultAccess) { this.handler = handler; this.accessControlList = accessControlList; this.defaultAccess = defaultAccess; } @Override public Response handle(Request request) { if (accessControlList.containsKey(request.user)) return authorise(request); else return new Response(Status.METHOD_NOT_ALLOWED, Collections.singletonMap(Header.ALLOW, ""), ""); } private Response authorise(Request request) { Map<String, List<Method>> accessControl = accessControlList.get(request.user); List<Method> allowedMethods = accessControl.getOrDefault(request.path, defaultAccess); if (allowedMethods.contains(request.method)) return handler.handle(request); else { return new Response(Status.METHOD_NOT_ALLOWED, Collections.singletonMap(Header.ALLOW, commaDelimited(allowedMethods)), ""); } } private String commaDelimited(List<Method> methods) { return methods.stream() .map(Enum::name) .collect(Collectors.joining(", ")); } }
C#
UTF-8
904
2.6875
3
[]
no_license
using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.ModelConfiguration; namespace CommonDataService.Models.Mapping { public class ProgramMap : EntityTypeConfiguration<Program> { public ProgramMap() { // Primary Key this.HasKey(t => t.ProgramID); // Properties // Table & Column Mappings this.ToTable("Programs"); this.Property(t => t.ProgramID).HasColumnName("ProgramID"); this.Property(t => t.ProgramName).HasColumnName("ProgramName"); this.Property(t => t.AccountProgram_AccountProgramID).HasColumnName("AccountProgram_AccountProgramID"); // Relationships this.HasOptional(t => t.AccountProgram) .WithMany(t => t.Programs) .HasForeignKey(d => d.AccountProgram_AccountProgramID); } } }
Markdown
UTF-8
5,235
3.703125
4
[ "MIT" ]
permissive
# ICE CREAM PARLOR #### A website for an ice cream parlor, hosted on [GitHub Pages](https://kristarutz.github.io/Ice-Cream-Parlor/), where a user can choose one or more individual toppings (sprinkles, whipped cream, hot fudge, etc) and a size to order an ice cream and see the final cost. ### _By **Krista Rutz** Last updated January 31 2020_ ## Description This web application allows the user to choose between 7 types of ice cream treats, select from a menu of ten flavors, and add up to 7 toppings. It then calculates the cost of the order. ## Installation / Set-up This app is ready to run at this url: https://kristarutz.github.io/Ice-Cream-Parlor/ You can also download the ZIP file to run this program without internet. * Select "Clone or Download" on the [GitHub Repository](https://github.com/KristaRutz/Ice-Cream-Parlor.git) site > Download ZIP * Open the ZIP download and extract files. * The new folder will be created as "ice-cream-parlor" unless you change this setting. In this folder, select the index.html document. * Choose "Open With" > Google Chrome or another browser of your choice. * The website is now ready to use! ## Technologies Used * JavaScript and jQuery * Custom CSS and responsive design using Bootstrap framework * HTML ## Specifications <details> <summary>Expand specs for this project</summary> | Spec | Example Input | Expected Output | | :------------- | :------------- | :------------- | | User begins with an empty cart | "Example" | "Example" | | When user clicks on cart, the contents of the cart are displayed | click <kbd>View cart</kbd>| "nothing in the cart" message, <kbd>new</kbd> button | | Create input form for a new ice cream creation | User selects "new" ice cream creation | click <kbd>new</kbd> | new creation form appears | | User selects "Kid's Scoop" option | Size: <kbd>Kid's</kbd> | Price updates to $2.50 but user cannot add to cart | | User selects chocolate flavor | Flavor: <kbd>Chocolate</kbd> | Price remains $2.50 and user can add to cart | | User does not select any toppings | Toppings: <kbd>None</kbd> | Price remains $2.50 and user can add to cart | | User selects 1 topping | Toppings: <kbd>Sprinkles</kbd> | Price updates to $2.80 and user can add to cart | | User adds to cart | click <kbd>Add to cart</kbd> | Cart size increases to 1, form is reset, and <kbd>Add another creation</kbd> button appears | | When user clicks on cart, the contents of the cart are displayed | click <kbd>View cart</kbd>| "1 kid's scoop" message, price, total price, <kbd>checkout</kbd> button, <kbd>new</kbd> button | |||| | User selects "Triple Scoop" option | Size: <kbd>Triple</kbd> | Price updates to $5 but user cannot add to cart | | User selects chocolate flavor | Flavor: <kbd>Chocolate</kbd> | Price remains $5 and user cannot add to cart - must select three flavors | | User selects chocolate, strawberry, vanilla flavor | Flavor: <kbd>Chocolate</kbd> <kbd>Strawberry</kbd> <kbd>Vanilla</kbd> | Price remains $5 and user can add to cart | | User does not select any toppings | Toppings: <kbd>None</kbd> | Price remains $5 and user can add to cart | | User selects 1 topping | Toppings: <kbd>Sprinkles</kbd> | Price updates to $5.30 and user can add to cart | | User adds a second item to cart | click <kbd>Add to cart</kbd> | Cart size increases to 2, form is reset, and <kbd>Add another creation</kbd> button appears | | When user clicks on cart, the contents of the cart are displayed | click <kbd>View cart</kbd>| "1 kid's scoop" message, price, "1 triple scoop" message, price, total price, <kbd>checkout</kbd> button, <kbd>new</kbd> button | </details> ## Known Bugs If treat type is changed while toppings are selected, the order may contain double toppings or toppings associated with the previous treat type. ## Support and contact details Please contact me if you run into any issues or have questions, ideas or concerns. I can be contacted at <krista.rutz@pomona.edu>. Feel free to create a pull request for updates - _contributions to the code are encouraged!_ ## Usage and Licensing *This software is licensed under the MIT license* Copyright (c) 2020 **_Krista Rutz_** <details> <summary>View license details</summary> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. </details>
Shell
UTF-8
1,348
2.9375
3
[ "MIT" ]
permissive
#!/bin/bash main_dir="./" bindings_dir="src/bindings-pkcs11" rpc_dir="src/rpc-pkcs11" server_dir="src/pkcs11proxyd" client_dir="src/client-lib" filter_dir="src/filter" filter_filter_dir="src/filter/filter" filter_backend_dir="src/filter/backend" filter_frontend_dir="src/filter/frontend" tests_dir="src/tests" ocaml_tests_dir="src/tests/ocaml" c_tests_dir="src/tests/c-based" scripts_dir="scripts" clean_dirs=($main_dir $bindings_dir $rpc_dir $server_dir $client_dir $filter_dir $filter_filter_dir $filter_backend_dir $filter_frontend_dir $tests_dir $ocaml_tests_dir $c_tests_dir) echo "Cleaning the project ..." make clean &> /dev/null echo "Cleaning AUTOCONF files ..." rm -rf aclocal.m4 autom4te.cache config.log config.status configure summary echo "Cleaning Makefiles ..." for (( i = 0 ; i < ${#clean_dirs[*]} ; i++ )) do rm -f ${clean_dirs[i]}/Makefile done rm -f ${bindings_dir}/Makefile.standalone #Cleaning Makefile.in which will be cp depending on platform rm -f ${main_dir}/Makefile.in echo "Cleaning initrc file ..." rm -rf ${scripts_dir}/pkcs11proxyd echo "Cleaning the SSL related files ..." rm -f create_ssl_files.c create_ssl_files src/client-lib/cert_file.h src/client-lib/ca_file.h src/client-lib/private_key_file.h src/rpc-pkcs11/ca_file.inc src/rpc-pkcs11/cert_file.inc src/rpc-pkcs11/private_key_file.inc server_certs.crt
JavaScript
UTF-8
207
3.0625
3
[]
no_license
const partialApply = (fn, arg1) => arg2 => fn(arg2, arg1); const pow = (a, b) => a ** b; const f1 = partialApply(pow, 2); console.log(f1(1)); // 1 console.log(f1(10)); // 100 export default partialApply;
Java
UTF-8
419
2.75
3
[]
no_license
package com.weather.core.bean; public enum DeviceName { IPHONE("iphone"), ANDROID("android"); private String name; private DeviceName(String name) { this.name = name; } public String getName() { return name; } public static DeviceName getDeviceName(String name) { for (DeviceName deviceName : values()) { if (deviceName.getName().equals(name)) { return deviceName; } } return null; } }
Python
UTF-8
2,987
2.625
3
[]
no_license
# vi:syntax=python __doc__ = """ # Pipeline This module provides methods useful for crafting the basic Dispatch pipeline resources in Starlark. Import URL: `github.com/mesosphere/dispatch-catalog/starlark/stable/pipeline` """ def push(**kwargs): """ A sugar function for creating a new push condition. Example usage: `action(tasks = ["test"], on = push(branches = ["master"]))` """ return p.Condition(push=p.PushCondition(**kwargs)) def tag(**kwargs): """ A sugar function for creating a new tag condition. Example usage: `action(tasks = ["test"], on = tag())` """ return p.Condition(tag=p.TagCondition(**kwargs)) def pullRequest(**kwargs): """ A sugar function for creating a new pull request condition. Example usage: `action(tasks = ["test"], on = pullRequest(chatops=["build"]))` """ return p.Condition(pull_request=p.PullRequestCondition(**kwargs)) def gitResource(name, url="$(context.git.url)", revision="$(context.git.commit)", pipeline=None): """ Define a new git resource in a pipeline. Example usage: `gitResource("git", url="$(context.git.url)", revision="$(context.git.commit)")` """ resource(name, type = "git", params = { "url": url, "revision": revision, }, pipeline=pipeline) return name def imageResource(name, url, digest, pipeline=None): """ Define a new image resource in a pipeline. Example usage: `imageResource("my-image", url="mesosphere/dispatch:latest")` """ return resource(name, type = "image", params = { "url": url, "digest": digest }, pipeline=pipeline) def volume(name, **kwargs): """ Create a new volume given a volume source. """ return k8s.corev1.Volume(name=name, volumeSource=k8s.corev1.VolumeSource(**kwargs)) def resourceVar(name, key): """ Shorthand for a resource variable, returns a string "$(inputs.resources.<name>.<key>)" """ return "$(inputs.resources.{}.{})".format(name, key) def secretVar(name, key): """ Convenience function for adding an environment variable from a Kubernetes secret. Example usage: `k8s.corev1.EnvVar(name="GITHUB_TOKEN", valueFrom=secretVar("scmtoken", "password"))` """ return k8s.corev1.EnvVarSource(secretKeyRef=k8s.corev1.SecretKeySelector(localObjectReference=k8s.corev1.LocalObjectReference(name=name), key=key)) def storageResource(name): """ Create a new S3 resource using the Dispatch default s3 configuration file. """ resource(name, type = "storage", params = { "type": "gcs", "location": "s3://artifacts", }, secrets = { "BOTO_CONFIG": k8s.corev1.SecretKeySelector(key = "boto", localObjectReference = k8s.corev1.LocalObjectReference(name = "s3-config")) }) return name def clean(name): """ Sanitize a name for passing in to Kubernetes / Dispatch. """ return name.replace("/", "-").replace(":", "-").replace(".", "-")
Java
UTF-8
745
1.976563
2
[]
no_license
package net.younguard.bighorn.broadcast.dao; import net.younguard.bighorn.broadcast.domain.Page; import net.younguard.bighorn.domain.PlayerDetailInfo; import net.younguard.bighorn.domain.PlayerMasterInfo; public interface PlayerDao { public void add(String accountId); public void updateInviteNum(String accountId, short num); public void updatePlayingNum(String accountId, short num); public void updateCompletedNum(String accountId, short num); public short selectInviteNum(String accountId); public short selectPlayingNum(String accountId); public short selectCompletedNum(String accountId); public Page<PlayerMasterInfo> selectPagination(short pageNum, short pageSize); public PlayerDetailInfo select(String accountId); }
Java
UTF-8
1,376
2.75
3
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
package ca.uhn.fhir.example.ex2; import java.util.HashMap; import java.util.Map; import ca.uhn.fhir.model.api.IResource; import ca.uhn.fhir.model.dstu.resource.Patient; import ca.uhn.fhir.model.primitive.IdDt; import ca.uhn.fhir.rest.annotation.IdParam; import ca.uhn.fhir.rest.annotation.Read; import ca.uhn.fhir.rest.server.IResourceProvider; import ca.uhn.fhir.rest.server.exceptions.ResourceNotFoundException; /** * This is the most basic resource provider, showing only a single * read method on a resource provider */ public class Example02_PatientResourceProvider implements IResourceProvider { private Map<Long, Patient> myPatients = new HashMap<Long, Patient>(); /** Constructor */ public Example02_PatientResourceProvider() { Patient pat1 = new Patient(); pat1.addIdentifier().setSystem("http://acme.com/MRNs").setValue("7000135"); pat1.addName().addFamily("Simpson").addGiven("Homer").addGiven("J"); myPatients.put(1L, pat1); } /** All Resource Providers must implement this method */ @Override public Class<? extends IResource> getResourceType() { return Patient.class; } /** Simple implementation of the "read" method */ @Read() public Patient read(@IdParam IdDt theId) { Patient retVal = myPatients.get(theId.getIdPartAsLong()); if (retVal == null) { throw new ResourceNotFoundException(theId); } return retVal; } }
C#
UTF-8
30,219
3.09375
3
[ "Unlicense" ]
permissive
using System; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace NDex.Tests { /// <summary> /// Tests the StableSortCopy methods. /// </summary> [TestClass] public class StableSortCopyTester { #region Real World Example /// <summary> /// StableSort is mostly useful when a fast sort is needed and equivalent values need to stay in the same order. /// </summary> [TestMethod] public void TestStableSortCopy_SortRandomList_KeepEquivalentItemsOrdered() { Random random = new Random(); // build a list var list = new List<Tuple<int, int>>(100); Sublist.Generate(100, i => Tuple.Create(random.Next(100), i)).AddTo(list.ToSublist()); // sort the list var destination = new Tuple<int, int>[100]; list.ToSublist().StableSort().CopyTo(destination.ToSublist()); // first make sure the list is sorted by the first value bool isFirstSorted = destination.ToSublist().IsSorted((t1, t2) => Comparer<int>.Default.Compare(t1.Item1, t2.Item1)); Assert.IsTrue(isFirstSorted, "The items were not sorted according to the first item."); // then make sure the list is sorted by the second value // tuples compare by first comparing the first items, then, if necessary, the second items bool isSorted = destination.ToSublist().IsSorted(); Assert.IsTrue(isSorted, "The equivalent items did not remain in the same order."); } /// <summary> /// StableSort is mostly useful when a fast sort is needed and equivalent values need to stay in the same order. /// If we restrict the size of the buffer to three, the merge sort will be very slow. /// </summary> [TestMethod] public void TestStableSortCopy_SortRandomList_TinyBuffer_KeepEquivalentItemsOrdered() { Random random = new Random(); // build a list var list = new List<Tuple<int, int>>(100); Sublist.Generate(100, i => Tuple.Create(random.Next(100), i)).AddTo(list.ToSublist()); // sort the list Tuple<int, int>[] buffer = new Tuple<int, int>[3]; // no space to merge - bad for performance! var destination = new Tuple<int, int>[100]; list.ToSublist().StableSort(buffer.ToSublist()).CopyTo(destination.ToSublist()); // first make sure the list is sorted by the first value bool isFirstSorted = destination.ToSublist().IsSorted((t1, t2) => Comparer<int>.Default.Compare(t1.Item1, t2.Item1)); Assert.IsTrue(isFirstSorted, "The items were not sorted according to the first item."); // then make sure the list is sorted by the second value // tuples compare by first comparing the first items, then, if necessary, the second items bool isSorted = destination.ToSublist().IsSorted(); Assert.IsTrue(isSorted, "The equivalent items did not remain in the same order."); } #endregion #region Argument Checking /// <summary> /// An exception should be thrown if the list is null. /// </summary> [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void TestStableSortCopy_NullList_Throws() { IReadOnlySublist<List<int>, int> list = null; list.StableSort(); } /// <summary> /// An exception should be thrown if the list is null. /// </summary> [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void TestStableSortCopy_WithBuffer_NullList_Throws() { IReadOnlySublist<List<int>, int> list = null; IExpandableSublist<List<int>, int> buffer = new List<int>().ToSublist(); list.StableSort(buffer); } /// <summary> /// An exception should be thrown if the list is null. /// </summary> [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void TestStableSortCopy_WithComparer_NullList_Throws() { IReadOnlySublist<List<int>, int> list = null; IComparer<int> comparer = Comparer<int>.Default; list.StableSort(comparer); } /// <summary> /// An exception should be thrown if the list is null. /// </summary> [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void TestStableSortCopy_WithBuffer_WithComparer_NullList_Throws() { IReadOnlySublist<List<int>, int> list = null; IExpandableSublist<List<int>, int> buffer = new List<int>().ToSublist(); IComparer<int> comparer = Comparer<int>.Default; list.StableSort(buffer, comparer); } /// <summary> /// An exception should be thrown if the list is null. /// </summary> [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void TestStableSortCopy_WithComparison_NullList_Throws() { IReadOnlySublist<List<int>, int> list = null; Func<int, int, int> comparison = Comparer<int>.Default.Compare; list.StableSort(comparison); } /// <summary> /// An exception should be thrown if the list is null. /// </summary> [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void TestStableSortCopy_WithBuffer_WithComparison_NullList_Throws() { IReadOnlySublist<List<int>, int> list = null; IExpandableSublist<List<int>, int> buffer = new List<int>().ToSublist(); Func<int, int, int> comparison = Comparer<int>.Default.Compare; list.StableSort(buffer, comparison); } /// <summary> /// An exception should be thrown if the buffer is null. /// </summary> [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void TestStableSortCopy_NullBuffer_Throws() { IReadOnlySublist<List<int>, int> list = new List<int>().ToSublist(); IExpandableSublist<List<int>, int> buffer = null; list.StableSort(buffer); } /// <summary> /// An exception should be thrown if the buffer is null. /// </summary> [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void TestStableSortCopy_WithComparer_NullBuffer_Throws() { IReadOnlySublist<List<int>, int> list = new List<int>().ToSublist(); IExpandableSublist<List<int>, int> buffer = null; IComparer<int> comparer = Comparer<int>.Default; list.StableSort(buffer, comparer); } /// <summary> /// An exception should be thrown if the buffer is null. /// </summary> [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void TestStableSortCopy_WithComparison_NullBuffer_Throws() { IReadOnlySublist<List<int>, int> list = new List<int>().ToSublist(); IExpandableSublist<List<int>, int> buffer = null; Func<int, int, int> comparison = Comparer<int>.Default.Compare; list.StableSort(buffer, comparison); } /// <summary> /// An exception should be thrown if the comparison is null. /// </summary> [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void TestStableSortCopy_NullComparer_Throws() { var list = new List<int>().ToSublist(); IComparer<int> comparer = null; list.StableSort(comparer); } /// <summary> /// An exception should be thrown if the comparison is null. /// </summary> [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void TestStableSortCopy_WithBuffer_NullComparer_Throws() { IReadOnlySublist<List<int>, int> list = new List<int>().ToSublist(); IExpandableSublist<List<int>, int> buffer = new List<int>().ToSublist(); IComparer<int> comparer = null; list.StableSort(buffer, comparer); } /// <summary> /// An exception should be thrown if the comparison is null. /// </summary> [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void TestStableSortCopy_NullComparison_Throws() { IReadOnlySublist<List<int>, int> list = new List<int>().ToSublist(); Func<int, int, int> comparison = null; list.StableSort(comparison); } /// <summary> /// An exception should be thrown if the comparison is null. /// </summary> [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void TestStableSortCopy_WithBuffer_NullComparison_Throws() { IReadOnlySublist<List<int>, int> list = new List<int>().ToSublist(); IExpandableSublist<List<int>, int> buffer = new List<int>().ToSublist(); Func<int, int, int> comparison = null; list.StableSort(buffer, comparison); } /// <summary> /// An exception should be thrown if the destination is null. /// </summary> [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public void TestStableSortCopy_DestinationNull_Throws() { IReadOnlySublist<List<int>, int> list = new List<int>().ToSublist(); IExpandableSublist<List<int>, int> destination = null; list.StableSort().CopyTo(destination); } #endregion /// <summary> /// Sorting an empty list should do nothing. /// </summary> [TestMethod] public void TestStableSortCopy_EmptyList() { var list = TestHelper.WrapReadOnly(new List<int>()); var destination = TestHelper.Wrap(new List<int>()); var result = list.StableSort().CopyTo(destination); Assert.AreEqual(list.Count, result.SourceOffset, "The source offset was wrong."); Assert.AreEqual(destination.Count, result.DestinationOffset, "The destination offset was wrong."); TestHelper.CheckHeaderAndFooter(list); TestHelper.CheckHeaderAndFooter(destination); } /// <summary> /// If someone tries to call StableSort with an empty buffer, InsertionSort is called, /// which is a stable sort, although much slower. /// </summary> [TestMethod] public void TestStableSortCopy_EmptyBuffer_CallsInsertionSort() { var list = TestHelper.WrapReadOnly(new List<int>()); var buffer = TestHelper.Wrap(new List<int>()); var destination = TestHelper.Wrap(new List<int>()); var result = list.StableSort(buffer).CopyTo(destination); Assert.AreEqual(list.Count, result.SourceOffset, "The source offset was wrong."); Assert.AreEqual(destination.Count, result.DestinationOffset, "The destination offset was wrong."); TestHelper.CheckHeaderAndFooter(list); TestHelper.CheckHeaderAndFooter(buffer); TestHelper.CheckHeaderAndFooter(destination); } /// <summary> /// StableSort should work against a reversed list. /// </summary> [TestMethod] public void TestStableSortCopy_Reversed() { var list = TestHelper.WrapReadOnly(new List<int>()); var destination = TestHelper.Wrap(new List<int>()); list = Sublist.Generate(200, i => 199 - i).AddTo(TestHelper.Populate(list)); destination = Sublist.Generate(200, 0).AddTo(destination); var result = list.StableSort(Comparer<int>.Default).CopyTo(destination); Assert.AreEqual(list.Count, result.SourceOffset, "The source offset was wrong."); Assert.AreEqual(destination.Count, result.DestinationOffset, "The destination offset was wrong."); bool isSorted = destination.IsSorted(Comparer<int>.Default); Assert.IsTrue(isSorted, "The list was not sorted."); TestHelper.CheckHeaderAndFooter(list); TestHelper.CheckHeaderAndFooter(destination); } /// <summary> /// StableSort should work against a reversed list, even if the buffer is quarter the list's size. /// </summary> [TestMethod] public void TestStableSortCopy_Reversed_QuarterBuffer() { var list = TestHelper.WrapReadOnly(new List<int>()); var buffer = TestHelper.Wrap(new List<int>()); var destination = TestHelper.Wrap(new List<int>()); list = Sublist.Generate(100, i => 99 - i).AddTo(TestHelper.Populate(list)); buffer = Sublist.Generate(25, 0).AddTo(buffer); destination = Sublist.Generate(100, 0).AddTo(destination); var result = list.StableSort(buffer, Comparer<int>.Default).CopyTo(destination); Assert.AreEqual(list.Count, result.SourceOffset, "The source offset was wrong."); Assert.AreEqual(destination.Count, result.DestinationOffset, "The destination offset was wrong."); bool isSorted = destination.IsSorted(Comparer<int>.Default); Assert.IsTrue(isSorted, "The list was not sorted."); TestHelper.CheckHeaderAndFooter(list); TestHelper.CheckHeaderAndFooter(buffer); TestHelper.CheckHeaderAndFooter(destination); } /// <summary> /// StableSort should work against a reversed list, even if the buffer is tiny. /// </summary> [TestMethod] public void TestStableSortCopy_Reversed_TinyBuffer() { var list = TestHelper.WrapReadOnly(new List<int>()); var buffer = TestHelper.Wrap(new List<int>()); var destination = TestHelper.Wrap(new List<int>()); list = Sublist.Generate(101, i => 101 - i).AddTo(TestHelper.Populate(list)); buffer = Sublist.Generate(3, 0).AddTo(buffer); destination = Sublist.Generate(101, 0).AddTo(destination); var result = list.StableSort(buffer, Comparer<int>.Default).CopyTo(destination); Assert.AreEqual(list.Count, result.SourceOffset, "The source offset was wrong."); Assert.AreEqual(destination.Count, result.DestinationOffset, "The destination offset was wrong."); bool isSorted = destination.IsSorted(Comparer<int>.Default); Assert.IsTrue(isSorted, "The list was not sorted."); TestHelper.CheckHeaderAndFooter(list); TestHelper.CheckHeaderAndFooter(buffer); TestHelper.CheckHeaderAndFooter(destination); } /// <summary> /// StableSort should work against a list whose values ascend and then descend. /// </summary> [TestMethod] public void TestStableSortCopy_PipeOrganed() { var list = TestHelper.WrapReadOnly(new List<int>()); var destination = TestHelper.Wrap(new List<int>()); list = Sublist.Generate(100, i => i * 2).AddTo(TestHelper.Populate(list)); list = Sublist.Generate(200, i => 199 - (i - 100) * 2).AddTo(TestHelper.Populate(list)); destination = Sublist.Generate(300, 0).AddTo(destination); var result = list.StableSort(Comparer<int>.Default.Compare).CopyTo(destination); Assert.AreEqual(list.Count, result.SourceOffset, "The source offset was wrong."); Assert.AreEqual(destination.Count, result.DestinationOffset, "The destination offset was wrong."); bool isSorted = destination.IsSorted(Comparer<int>.Default.Compare); Assert.IsTrue(isSorted, "The list was not sorted."); TestHelper.CheckHeaderAndFooter(list); TestHelper.CheckHeaderAndFooter(destination); } /// <summary> /// StableSort should work against a list whose values ascend and then descend, even if the buffer is quarter the list's size. /// </summary> [TestMethod] public void TestStableSortCopy_PipeOrganed_QuarterBuffer() { var list = TestHelper.WrapReadOnly(new List<int>()); var buffer = TestHelper.Wrap(new List<int>()); var destination = TestHelper.Wrap(new List<int>()); list = Sublist.Generate(50, i => i * 2).AddTo(TestHelper.Populate(list)); list = Sublist.Generate(100, i => 99 - (i - 50) * 2).AddTo(TestHelper.Populate(list)); buffer = Sublist.Generate(25, 0).AddTo(buffer); destination = Sublist.Generate(150, 0).AddTo(destination); var result = list.StableSort(buffer, Comparer<int>.Default.Compare).CopyTo(destination); Assert.AreEqual(list.Count, result.SourceOffset, "The source offset was wrong."); Assert.AreEqual(destination.Count, result.DestinationOffset, "The destination offset was wrong."); bool isSorted = destination.IsSorted(Comparer<int>.Default.Compare); Assert.IsTrue(isSorted, "The list was not sorted."); TestHelper.CheckHeaderAndFooter(list); TestHelper.CheckHeaderAndFooter(buffer); TestHelper.CheckHeaderAndFooter(destination); } /// <summary> /// StableSort should work against a list whose values ascend and then descend, even if the buffer is tiny. /// </summary> [TestMethod] public void TestStableSortCopy_PipeOrganed_TinyBuffer() { var list = TestHelper.WrapReadOnly(new List<int>()); var buffer = TestHelper.Wrap(new List<int>()); var destination = TestHelper.Wrap(new List<int>()); list = Sublist.Generate(50, i => i * 2).AddTo(TestHelper.Populate(list)); list = Sublist.Generate(101, i => 101 - (i - 50) * 2).AddTo(TestHelper.Populate(list)); buffer = Sublist.Generate(3, 0).AddTo(buffer); destination = Sublist.Generate(151, 0).AddTo(destination); var result = list.StableSort(buffer, Comparer<int>.Default.Compare).CopyTo(destination); Assert.AreEqual(list.Count, result.SourceOffset, "The source offset was wrong."); Assert.AreEqual(destination.Count, result.DestinationOffset, "The destination offset was wrong."); bool isSorted = destination.IsSorted(Comparer<int>.Default.Compare); Assert.IsTrue(isSorted, "The list was not sorted."); TestHelper.CheckHeaderAndFooter(list); TestHelper.CheckHeaderAndFooter(buffer); TestHelper.CheckHeaderAndFooter(destination); } /// <summary> /// StableSort should work against a list whose values jump between small and large. /// </summary> [TestMethod] public void TestStableSortCopy_Interweaved() { var list = TestHelper.WrapReadOnly(new List<int>()); var destination = TestHelper.Wrap(new List<int>()); list = Sublist.Generate(200, i => i % 2 == 0 ? i : 199 - (i - 1)).AddTo(TestHelper.Populate(list)); destination = Sublist.Generate(200, 0).AddTo(destination); var result = list.StableSort().CopyTo(destination); Assert.AreEqual(list.Count, result.SourceOffset, "The source offset was wrong."); Assert.AreEqual(destination.Count, result.DestinationOffset, "The destination offset was wrong."); bool isSorted = destination.IsSorted(); Assert.IsTrue(isSorted, "The list was not sorted."); TestHelper.CheckHeaderAndFooter(list); TestHelper.CheckHeaderAndFooter(destination); } /// <summary> /// StableSort should work against a list whose values jump between small and large, even if the buffer is quarter the list's size. /// </summary> [TestMethod] public void TestStableSortCopy_Interweaved_QuarterBuffer() { var list = TestHelper.WrapReadOnly(new List<int>()); var buffer = TestHelper.Wrap(new List<int>()); var destination = TestHelper.Wrap(new List<int>()); list = Sublist.Generate(100, i => i % 2 == 0 ? i : 99 - (i - 1)).AddTo(TestHelper.Populate(list)); buffer = Sublist.Generate(25, 0).AddTo(buffer); destination = Sublist.Generate(100, 0).AddTo(destination); var result = list.StableSort(buffer).CopyTo(destination); Assert.AreEqual(list.Count, result.SourceOffset, "The source offset was wrong."); Assert.AreEqual(destination.Count, result.DestinationOffset, "The destination offset was wrong."); bool isSorted = destination.IsSorted(); Assert.IsTrue(isSorted, "The list was not sorted."); TestHelper.CheckHeaderAndFooter(list); TestHelper.CheckHeaderAndFooter(buffer); TestHelper.CheckHeaderAndFooter(destination); } /// <summary> /// StableSort should work against a list whose values jump between small and large, even if the buffer is tiny. /// </summary> [TestMethod] public void TestStableSortCopy_Interweaved_TinyBuffer() { var list = TestHelper.WrapReadOnly(new List<int>()); var buffer = TestHelper.Wrap(new List<int>()); var destination = TestHelper.Wrap(new List<int>()); list = Sublist.Generate(101, i => i % 2 == 0 ? i : 101 - (i - 1)).AddTo(TestHelper.Populate(list)); buffer = Sublist.Generate(3, 0).AddTo(buffer); destination = Sublist.Generate(101, 0).AddTo(destination); var result = list.StableSort(buffer).CopyTo(destination); Assert.AreEqual(list.Count, result.SourceOffset, "The source offset was wrong."); Assert.AreEqual(destination.Count, result.DestinationOffset, "The destination offset was wrong."); bool isSorted = destination.IsSorted(); Assert.IsTrue(isSorted, "The list was not sorted."); TestHelper.CheckHeaderAndFooter(list); TestHelper.CheckHeaderAndFooter(buffer); TestHelper.CheckHeaderAndFooter(destination); } /// <summary> /// StableSort should work against a list whose values are sorted except the last value. /// </summary> [TestMethod] public void TestStableSortCopy_LastMisplaced() { var list = TestHelper.WrapReadOnly(new List<int>()); var destination = TestHelper.Wrap(new List<int>()); list = Sublist.Generate(200, i => i + 1).AddTo(TestHelper.Populate(list)); list = new int[] { 0 }.AddTo(TestHelper.Populate(list)); destination = Sublist.Generate(201, 0).AddTo(destination); var result = list.StableSort().CopyTo(destination); Assert.AreEqual(list.Count, result.SourceOffset, "The source offset was wrong."); Assert.AreEqual(destination.Count, result.DestinationOffset, "The destination offset was wrong."); bool isSorted = destination.IsSorted(); Assert.IsTrue(isSorted, "The list was not sorted."); TestHelper.CheckHeaderAndFooter(list); TestHelper.CheckHeaderAndFooter(destination); } /// <summary> /// StableSort should work against a list whose values are sorted except the last value, even if the buffer is quarter the list's size. /// </summary> [TestMethod] public void TestStableSortCopy_LastMisplaced_QuarterBuffer() { var list = TestHelper.WrapReadOnly(new List<int>()); var buffer = TestHelper.Wrap(new List<int>()); var destination = TestHelper.Wrap(new List<int>()); list = Sublist.Generate(100, i => i).AddTo(TestHelper.Populate(list)); list = new int[] { -1 }.AddTo(TestHelper.Populate(list)); buffer = Sublist.Generate(25, 0).AddTo(buffer); destination = Sublist.Generate(101, 0).AddTo(destination); var result = list.StableSort(buffer).CopyTo(destination); Assert.AreEqual(list.Count, result.SourceOffset, "The source offset was wrong."); Assert.AreEqual(destination.Count, result.DestinationOffset, "The destination offset was wrong."); bool isSorted = destination.IsSorted(); Assert.IsTrue(isSorted, "The list was not sorted."); TestHelper.CheckHeaderAndFooter(list); TestHelper.CheckHeaderAndFooter(buffer); TestHelper.CheckHeaderAndFooter(destination); } /// <summary> /// StableSort should work against a list whose values are sorted except the last value, even if the buffer is tiny. /// </summary> [TestMethod] public void TestStableSortCopy_LastMisplaced_TinyBuffer() { var list = TestHelper.WrapReadOnly(new List<int>()); var buffer = TestHelper.Wrap(new List<int>()); var destination = TestHelper.Wrap(new List<int>()); list = Sublist.Generate(101, i => i).AddTo(TestHelper.Populate(list)); list = new int[] { -1 }.AddTo(TestHelper.Populate(list)); buffer = Sublist.Generate(3, 0).AddTo(buffer); destination = Sublist.Generate(102, 0).AddTo(destination); var result = list.StableSort(buffer).CopyTo(destination); Assert.AreEqual(list.Count, result.SourceOffset, "The source offset was wrong."); Assert.AreEqual(destination.Count, result.DestinationOffset, "The destination offset was wrong."); bool isSorted = destination.IsSorted(); Assert.IsTrue(isSorted, "The list was not sorted."); TestHelper.CheckHeaderAndFooter(list); TestHelper.CheckHeaderAndFooter(buffer); TestHelper.CheckHeaderAndFooter(destination); } /// <summary> /// StableSort should work against a list whose values are sorted except the first value. /// </summary> [TestMethod] public void TestStableSortCopy_FirstMisplaced() { var list = TestHelper.WrapReadOnly(new List<int>()); var destination = TestHelper.Wrap(new List<int>()); list = new int[] { 200 }.AddTo(TestHelper.Populate(list)); list = Sublist.Generate(201, i => i - 1).AddTo(TestHelper.Populate(list)); destination = Sublist.Generate(202, 0).AddTo(destination); var result = list.StableSort().CopyTo(destination); Assert.AreEqual(list.Count, result.SourceOffset, "The source offset was wrong."); Assert.AreEqual(destination.Count, result.DestinationOffset, "The destination offset was wrong."); bool isSorted = destination.IsSorted(); Assert.IsTrue(isSorted, "The list was not sorted."); TestHelper.CheckHeaderAndFooter(list); TestHelper.CheckHeaderAndFooter(destination); } /// <summary> /// StableSort should work against a list whose values are sorted except the first value, even if the buffer is quarter the list's size. /// </summary> [TestMethod] public void TestStableSortCopy_FirstMisplaced_QuarterBuffer() { var list = TestHelper.WrapReadOnly(new List<int>()); var buffer = TestHelper.Wrap(new List<int>()); var destination = TestHelper.Wrap(new List<int>()); list = new int[] { 100 }.AddTo(TestHelper.Populate(list)); list = Sublist.Generate(101, i => i - 1).AddTo(TestHelper.Populate(list)); buffer = Sublist.Generate(25, 0).AddTo(buffer); destination = Sublist.Generate(102, 0).AddTo(destination); var result = list.StableSort(buffer).CopyTo(destination); Assert.AreEqual(list.Count, result.SourceOffset, "The source offset was wrong."); Assert.AreEqual(destination.Count, result.DestinationOffset, "The destination offset was wrong."); bool isSorted = destination.IsSorted(); Assert.IsTrue(isSorted, "The list was not sorted."); TestHelper.CheckHeaderAndFooter(list); TestHelper.CheckHeaderAndFooter(buffer); TestHelper.CheckHeaderAndFooter(destination); } /// <summary> /// StableSort should work against a list whose values are sorted except the first value, even if the buffer is tiny. /// </summary> [TestMethod] public void TestStableSortCopy_FirstMisplaced_TinyBuffer() { var list = TestHelper.WrapReadOnly(new List<int>()); var buffer = TestHelper.Wrap(new List<int>()); var destination = TestHelper.Wrap(new List<int>()); list = new int[] { 100 }.AddTo(TestHelper.Populate(list)); list = Sublist.Generate(101, i => i - 1).AddTo(TestHelper.Populate(list)); buffer = Sublist.Generate(3, 0).AddTo(buffer); destination = Sublist.Generate(102, 0).AddTo(destination); var result = list.StableSort(buffer).CopyTo(destination); Assert.AreEqual(list.Count, result.SourceOffset, "The source offset was wrong."); Assert.AreEqual(destination.Count, result.DestinationOffset, "The destination offset was wrong."); bool isSorted = destination.IsSorted(); Assert.IsTrue(isSorted, "The list was not sorted."); TestHelper.CheckHeaderAndFooter(list); TestHelper.CheckHeaderAndFooter(buffer); TestHelper.CheckHeaderAndFooter(destination); } } }
Markdown
UTF-8
4,409
2.828125
3
[ "MIT" ]
permissive
# inject-some inject-some is Javascript helper library to assist in injecting scripts, styles and html from userscripts. Tested with the Greasemonkey extension on Firefox and with the TamperMonkey extension on Google Chrome and Microsoft Edge. ## Examples These examples show how to inject additional javascript, html and/or css from the user.js file itself or from resource files, when creating userscripts for Tampermonkey or Greasemonkey. ### script injects itself. The 'jira-issue-clone' user script for JIRA is an example of how a user script can inject itself into a page: https://github.com/BartJolling/jira-issue-clone/blob/master/jira-issue-clone.user.js The `scriptToInject( )` function is serialized to a string and then embedded in a `<script>` tag. Note that in the example below, `window.AJS.$` is the jQuery namespace in JIRA which is the target application for jira-issue-clone. ```javascript // ==UserScript== // @require https://raw.githubusercontent.com/BartJolling/inject-some/master/inject-some.js // @grant none // @run-at document-end // ==/UserScript== /** * Script to be injected directly into the page */ var scriptToInject = function ($) { //... snipped ... }; /** *Main function to inject the code of the jira-issue-clone extension into the JIRA website */ (function (callback) { 'use strict'; try { var scripts = "(" + callback.toString() + ")(window.AJS.$);"; injectsome.content.script(scripts); } catch (err) { console.log('[jira-issue-clone] ' + err.message); } })(scriptToInject); ``` ### inject scripts from other files. The 'delegarity' user script for the Clarity web application has examples on inserting additional content, taken from resource files included in the 'delegarity' script, into the target page: https://github.com/BartJolling/delegarity/blob/master/delegarity.user.js Note that the example below uses the `GM_getResourceText` extension method to load 'content' that's included with the extension. You could just as well load literal HTML, CSS or javascript or use the 'links' API to insert references to external files. ```javascript // ==UserScript== // @require https://raw.githubusercontent.com/BartJolling/inject-some/master/inject-some.js // @resource delegaritycss delegarity.css // @resource delegaritycorejs delegarity.core.js // @resource timesheetsjs timeadmin.timesheet.js // @resource timesheetshtml timeadmin.timesheet.html // @run-at document-idle // @grant GM_getResourceText // ==/UserScript== (function() { 'use strict'; //... snipped ... //inject css and html templates injectsome.content.css(GM_getResourceText("delegaritycss", "delegaritycss")); injectsome.content.html(GM_getResourceText("timesheetshtml")); //inject delegarity scripts injectsome.content.script(GM_getResourceText("delegaritycorejs"), "delegaritycorejs"); injectsome.content.script(GM_getResourceText("timesheetsjs"), "timesheetsjs"); //... snipped ... })(); ``` ## content API The `injectsome.content` API allows injecting the full literal content into a target page. ### injectsome.content.script (jsContent, scriptId) Injects a block of javascript into a new script tag in the HEAD of a document. - {string} jsContent - javascript code to inject. - {string} scriptId - Id of the script tag that will be injected. Used for duplicate check. ### injectsome.content.html (htmlContent) Appends a block of HTML to the body tag. - {string} htmlContent - HTML to inject. ### injectsome.content.css (cssContent, cssId) Appends a block of css to the head tag. - {string} cssContent - CSS to inject. - {string} cssId - Id of the style tag that will be injected. Used for duplicate check. ## links API The `injectsome.links` API allows injecting links to script or css files into a target page. ### injectsome.links.script (url, mimetype) Injects a link to a javascript file in the HEAD of a document. - {string} url - location of the javascript file to inject. - {string} mimetype - sets the value of the 'type' attribute of the script tag. ### injectsome.links.stylesheet (url, mimetype) Injects a link to a stylesheet in the HEAD of a document. - {string} url - location of the stylesheet file to inject. - {string} mimetype - sets the value of the 'type' attribute of the script tag.
Java
UTF-8
1,321
2.9375
3
[ "MIT" ]
permissive
package bean; /** * A Student class wrapping fields to be used as samples in validation by Criteria. */ public class Student { private String name; private String lastName; private String address; private int age; private String phoneNumber; private float mark; private Matters matters; public Matters getMatters() { return matters; } public void setMatters(Matters matters) { this.matters = matters; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public void setAge(int age) { this.age = age; } public int getAge() { return age; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public float getMark() { return mark; } public void setMark(float mark) { this.mark = mark; } }
C++
UTF-8
690
3.1875
3
[]
no_license
/***************************************************************************** * * Author: Christopher Chu * * Date: 02/19/2018 * * Description: This file includes a class called MyInteger. *****************************************************************************/ #ifndef MYINTEGER_HPP #define MYINTEGER_HPP #include <iostream> using namespace std; //MyInteger class declaration class MyInteger { private: int *pInteger; public: MyInteger &operator = (MyInteger &right); //overloaded MyInteger (const MyInteger &obj); //copy const. MyInteger (int value); //constructor ~MyInteger(); //destructor void setMyInt(int value); int getMyInt(); }; #endif
C++
UTF-8
933
2.8125
3
[]
no_license
#ifndef TILE_LAYER_H #define TILE_LAYER_H #include "PositionalLayer.h" class TileLayerCell; class TileLayer : public PositionalLayer { public: static TileLayer* Create(int width, int height, int tileWidth, int tileHeight); ~TileLayer(); int GetWidth() const { return m_width; } int GetHeight() const { return m_height; } int GetTileWidth() const { return m_tileWidth; } int GetTileHeight() const { return m_tileHeight; } void Tick(float deltaTime) override; void Paint() override; TileLayerCell* GetCellAt(int x, int y); void SetCellAt(int x, int y, TileLayerCell* cell); private: int m_width; int m_height; int m_tileWidth; int m_tileHeight; TileLayerCell** m_cells; protected: TileLayer(); bool Init(int width, int height, int tileWidth, int tileHeight); }; #endif // TILED_MAP_H
C#
UTF-8
739
2.65625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace Calculator { static class Program { /// <summary> /// Główny punkt wejścia dla aplikacji. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Calculator calculator = new Calculator(); Presenter presenter = new Presenter(calculator); Form1 view = new Form1(); view.Presenter = presenter; presenter.CalculatorView = view; Application.Run(view); } } }
JavaScript
UTF-8
753
4.46875
4
[]
no_license
const number = [1,2,3,4] console.log("orginal array is = " + number) //starting //for shift first element will be removed and returned let snum = number.shift() console.log("shifted number is = " +snum) console.log("After shifting array is " + number) // unshift is used for adding element at the first number.unshift('addMe') console.log("after unshifting : ") console.log(number) //end of array // pop(), last element will be removed and returned let poped = number.pop() console.log("poped element is = " + poped) console.log("after poping : ") console.log(number) // push(), will be used for addding element at the last number.push("Teja") console.log(number) //middle of the array number.splice(2, 3, 'something') console.log(number)
Ruby
UTF-8
162
2.765625
3
[]
no_license
arr = [1,4,8,9,12,14,27] puts arr i = 0 while i < arr.size/2 temp = arr[-1*(i+1)] arr[-1*(i+1)] = arr[i] arr[i] = temp i += 1 end puts arr # adding a comment
JavaScript
UTF-8
438
3.875
4
[]
no_license
// conditionals are used to perform different actions based on different conditions // let hungry = true // let food // if(hungry) { // console.log('I am so hungry') // } // let age = 19 // if(age >=21) { // console.log('You can drink!') // } else if(age >= 18) { // console.log('You can drive!') // } let cold = true let sandals = cold ? 'It is too cold for sandals' : 'Break out the flip flops.' console.log(sandals)
C++
UTF-8
485
3.03125
3
[]
no_license
/* 1 -> 100 (incl) 3 => Fizz 5 => Buzz 7 => 7 15 => FizzBuzz */ #include <iostream> using namespace std; int main() { for (int num = 1; num < 101; num += 1){ if (num % 15 == 0){ cout << "FizzBuzz"; } else if (num % 3 == 0){ cout << "Fizz"; } else if (num % 5 == 0){ cout << "Buzz"; } else { cout << num; } cout << "\n"; } return 0; }
Java
UTF-8
1,454
2.640625
3
[ "Apache-2.0" ]
permissive
package com.backbase.test.parcelable; import android.os.Parcel; import android.os.Parcelable; import java.util.Objects; /** * A basic {@link Parcelable} implementation for use by {@link TestParcelable}. */ public final class TestMemberParcelable implements Parcelable { public static final Creator<TestMemberParcelable> CREATOR = new Creator<TestMemberParcelable>() { @Override public TestMemberParcelable createFromParcel(Parcel source) { return new TestMemberParcelable(source); } @Override public TestMemberParcelable[] newArray(int size) { return new TestMemberParcelable[size]; } }; private final int value; TestMemberParcelable(int value) { this.value = value; } private TestMemberParcelable(Parcel in) { this.value = in.readInt(); } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeInt(value); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof TestMemberParcelable)) return false; final TestMemberParcelable that = (TestMemberParcelable) o; return this.value == that.value; } @Override public int hashCode() { return Objects.hash(value); } int getValue() { return value; } }
Markdown
UTF-8
6,413
2.875
3
[]
no_license
6/15/2018 知與不知 士師記2:6-3:6 士師記第一章紀錄的是約書亞死後以色列人各支派在應許之地攻城掠地得產業的情況。神吩咐說,他所應許的地的城市,“凡有氣息的,一個不可存留”(申命記20:16-17),但是以色列每個支派都沒有按照神的吩咐去行。即使是日後他們強盛了,他們還是選擇將迦南人留在自己的地業成為服苦役的人。 他們所做所為並不僅僅是沒有將迦南人全部逐出,還容忍迦南人的偶像崇拜在應許之地繼續進行。士師記2:1-5,神的使者責備上一代的這些見過他的大作為並在應許之地爭戰的以色列民,說他們還與迦南人立約,並且沒有拆毀假神的祭壇。因此神“必不將他們從你們面前趕出;他們必作你們肋下的荊棘。他們的神必作你們的網羅”。 士師記2:6-3:6,是對於士師記後面的內容的概括引言——以色列人上一代沒有遵從神的吩咐,如今在下一代結出罪的果子!下一代的人“不知道耶和華,也不知道耶和華為以色列人所行的事”,他們去事奉別神,跟隨他們殘忍、邪惡、淫穢的獻祭。他們本應該是屬耶和華的聖潔的子民,卻跟從淫邪,效法那些神要除去的迦南人的行為。他們能得以進入應許之地,並非是因為他們的義,而是因為迦南人的惡,並因為神的愛和信實,(申命記9:4-5)如今他們卻效法這迦南人的所有的邪惡!他們不僅住在迦南人中間,還“娶他們的女兒為妻,將自己的女兒嫁給他們的兒子,並事奉他們的神”(士師記3:6)。上一代看起來只是稍稍的讓步,些微的懈怠,就在下一代造成如此嚴重的後果,他們“速速”偏離他們列祖所行的道,雖然在出埃及的路上的老以色列人常常抱怨,被神斥責為“硬著頸項的民”,這新一代的以色列民居然還“不如他們列祖順從耶和華的命令”!(士師記2:17)。他們如同肌肉萎縮的身體,每一個士師來到,都試圖把他們往神身上扶一扶靠一靠,但是士師一走,他們立即摔回偶像崇拜的泥潭裡。 士師記2:6-3:6進一步回答了一個在讀約書亞記的時候一直縈繞心頭的問題,就是為什麼約書亞沒有能夠將迦南人都趕出神應許的地界,“耶和華留下各族,不將他們速速趕出,也沒有交付約書亞的手。”(士師記2:23) 誠然,首先在申命記裡神就有說過,他不會把迦南人一下子趕出,在以色列這個移植到迦南地的香柏樹根還沒有紮穩、新建的社會和經濟結構還沒有成型的時候,神要使用那地的迦南人來供應他的子民的需要。但是,以色列民族在腳跟站穩,勝過迦南人的時候,卻選擇留下迦南人。 今天的士師記給出另外的三個原因,神實在是早早就知道以色列人在應許之地的光景!他知道以色列人的屬靈肌肉萎縮軟弱,屬靈根基是豆腐渣工程!神沒有趕出各族的迦南人,原因之一是對以色列人的悖逆的懲戒(士師記2:20)。另外的原因是神要“藉此試驗以色列人,看他們肯照他們列祖謹守遵行我的道不肯”(士師記2:22,3:1),並且要讓這些沒有經歷爭戰的“以色列的後代又知道又學習未曾曉得的戰事”(士師記3:2)。每個士師來把肌肉萎縮的以色列民族往神身上扶一扶靠一靠,雖然過後以色列人又摔得七仰八叉,但是他們的筋骨卻在這一次次“physical therapy”中漸漸強壯;他們一次次在偶像崇拜的腐臭爛泥裡受苦以後,越來越渴慕神的聖潔。 所以神沒有將迦南人全部交付約書亞的手,趕出應許之地,是因著神的愛和恩典,是因著對悖逆的懲罰,是因著對信心的試驗,是因著屬靈的教導和操練!反省自身,是不是也仍有諸多罪的綑綁?!也許這罪是出於我們的懈怠和悖逆而不能趕出,誠然這罪也有苦澀的後果要承擔,甚至也有神的管教的杖落下,但是這肋下的荊棘卻可以成為神更新生命的大作為的出口,試驗煉淨我們的信心,操練敬虔屬靈的肌肉。當撒旦藉著罪的後果控告我們的時候,不要被這謊言之父欺騙,因“耶和華說:我知道我向你們所懷的意念是賜平安的意念,不是降災禍的意念,要叫你們末後有指望。”(耶利米書29:11)。不管罪的光景讓我們多麼痛苦和羞愧,神卻並非是要藉此驅逐我們,而是要藉此挽回我們、與他更親近。 士師記2:6-3:6提到了一個屬靈的光景,就是這新一代的以色列人“不知道”神,也“不知道”神為以色列人所行的事。但是這新一代的以色列人並非真的“不知道”神!事實上,在士師記裡,每次他們在仇敵下被壓迫的時候,他們都“呼求耶和華”!(3:9;3:15;4:3;6:6;10:10...)。這真是讓人毛骨悚然!若是按照我們理解的“知道”,那麼我們可以推測、怪責上一代以色列人沒有向孩子們講述耶和華神。我們也大可以為將孩子送到教會,參加主日學,“知道”耶和華,“知道”耶穌,“知道”聖經,對於他們就已經足夠了!但是神所講述的“知道”,不是我們認為的“知道”,神在申命記6:4-9吩咐的“殷勤教訓你的兒女”,遠遠超過去教會、上主日學,甚至遠遠超過送私立教會學校、每天讀經、每天靈修。神所要的,是在這申命記6章第六節的“殷勤教訓你的兒女”之前,在第五節對父母要求的“要盡心盡性盡力愛耶和華——你的神”,從這生命傾倒出來的愛、敬虔、教訓、督責,才能幫助下一代真正“知道”耶和華;從這生命流淌出來的見證,才能讓下一代真正“知道”耶和華在我們生命中的作為!如今從小去教會的孩子們,長大以後80%流失,這並非是這一個世代特有的挑戰,而是一直以來的挑戰,早在以色列民身上就曾有的教訓!願神幫助我們,操練敬虔的生命,專心依靠主,殷勤教訓兒女,願神使用我們的生命,讓兒女們真正“知道”神。
Markdown
UTF-8
2,265
2.671875
3
[]
no_license
# uampMusicPlayerProject This is a uamp android music player project HOW TO RUN THE FRAMEWORK - RUN USING JENKINS prerequisite 1. Ensure you have started appium from command propmt - to start appium: open cmd and type "appium" to start appium server 2. Ensure you have started your emulator using command prompt or android studio - to start emulator: open cmd and type the below commands 1. cd C:\Users\MBEMPX\AppData\Local\Android\Sdk\emulator (Change username from this path to your username) 2. emulator -avd (Specify your emulator name without brackets) 3. Open the TestNG.xml file under TestSuit folder from the project repository - Find file on this repository (https://github.com/MBEMPX/uampMusicPlayerProject.git) - Change deviceName parameter value to your emulator name - Change URL parameter value to have your own URL 4. From Jenkins do the following: - Create a new Item/Project by clicking on New item - Enter the item name - Select "Freestyle project" - Click OK button at the bottom - On the next window go to Source Code Management and select Git - Paste this URL repository (https://github.com/MBEMPX/uampMusicPlayerProject.git) - Under Build menu, type pom.xml on the Root POM - On Goals and options text field, type mvn clean install. 5. Click Apply and Save button at the bottom 6. Click Build now from your left hand menu - RUN USING THE COMMAND PROMPT FROM YOUR LOCAL MACHINE 1. Download the project to your local machine using the following steps - Open your browser and past this URL: https://github.com/MBEMPX/uampMusicPlayerProject.git - Click on Clone or download button from git hub - Download as Zip folder and extract it from your local machine 2. Open the TestNG.xml file under TestSuit folder from the project repository - Locate the TestNG.XML file in this directory(\\uampProject\TestSuit) - Open with notepad - Change deviceName parameter value to your emulator name - Change URL parameter value to have your own URL and save it 3. Execute tests from command line - locate run.bat file from this directory(\\uampProject) - Double click on it and the tests should start execution
PHP
UTF-8
1,237
2.6875
3
[]
no_license
<?php session_start();?> <?php if(!isset($_SESSION["username"])){ echo '<script>alert("请登录再进入");location.href="login.php";</script>'; exit(); } ?> <!doctype html> <html> <head> <meta charset="utf-8"> <title>无标题文档</title> </head> <body> <?php $username=$_POST["username"];//接收用户名 $password=$_POST["password"];//接收密码 $level=$_POST["level"];//接收级别 if($username=="" || $password==""){ echo '<script>alert("请填写管理员名称或密码");history.back();</script>'; //提示请填写 }else{ include_once("../conn.php");//连库 $sql=mysqli_query($con,"select * from school.user where username='".$username."'");//查询库的用户 if(mysqli_num_rows($sql)){ echo '<script>alert("已有该用户名称,请重新创建新的用户名称");history.back();</script>'; //提示已存在 mysqli_close($con);//关库 }else{ mysqli_query($con,"INSERT INTO `school`.`user` (`username` ,`password` ,`adminlevel`)VALUES ('".$username."', '".$password."', '".$level."')");//添加管理员。执行mysqli语句 echo '<script>alert("添加管理员成功");location.href="adminguanli.php";</script>';//提示添加成功 mysqli_close($con);//关库 } } ?> </body> </html>
Java
UTF-8
928
2.421875
2
[ "Apache-2.0" ]
permissive
package com.savvasdalkitsis.android.aspect.example.loading; import android.app.LoaderManager; import android.content.Context; import android.content.Loader; import android.os.Bundle; public class DataFetcher<T> extends LoaderBackedFetcher<T> { private final DataRetriever<T> retriever; public DataFetcher(LoaderManager loaderManager, int loaderId, Context context, DataRetriever<T> retriever) { super(context, loaderManager, loaderId); this.retriever = retriever; } @Override public DataLoader<T> onCreateLoader(int id, Bundle bundle) { return new DataLoader<>(context, retriever); } @Override public void onLoadFinished(Loader<T> loader, T data) { if (data == null) { listener.onDataFailedToLoad(); } else { listener.onDataFetched(data); } } }
PHP
UTF-8
2,108
2.78125
3
[]
no_license
<?php /** * mithra62 - Backup Pro Server * * @author Eric Lamb <eric@mithra62.com> * @copyright Copyright (c) 2014, mithra62, Eric Lamb. * @link http://backup-pro.com/ * @version 2.0 * @filesource ./module/Application/View/Helper/Pagination.php */ namespace Application\View\Helper; use Base\View\Helper\BaseViewHelper; /** * Application - Pagination View Helper * * @package ViewHelpers\Pagination * @author Eric Lamb <eric@mithra62.com> * @filesource ./module/Application/View/Helper/Pagination.php */ class Pagination extends BaseViewHelper { /** * Creates the HTML pagination string * @param string $route_key The route key name to use for the links (MUST be in the config) * @param number $total_pages The total number of pages we're paginating through * @param number $current_page The page we're currently on * @return string */ public function __invoke($route_key, $total_pages = 1, $current_page = 1) { $return = ''; if( $total_pages > $current_page ) { $return = '<ul class="pagination pull-right">'; for($i=1;$i<=$total_pages;$i++) { if($i === 1){ $prev_page = $current_page-1; if($total_pages > $prev_page && $prev_page !== 0) { $return .= '<li><a href="'.$this->view->url($route_key).'?limit=10&page='.$prev_page.'">&laquo;</a></li>'; } } $return .= '<li class="'.($i == $current_page ? 'active' : '').'"><a href="'.$this->view->url($route_key).'?limit=10&page='.$i.'">'.$i.'</a></li>'; if($i == $total_pages) { $next_page = $current_page+1; if( $next_page <= $total_pages ) { $return .= '<li><a href="'.$this->view->url($route_key).'?limit=10&page='.$next_page.'">&raquo;</a></li>'; } } } $return .= '</ul>'; } return $return; } }
Java
GB18030
14,521
2.15625
2
[]
no_license
package com.sinosoft.claim.ui.control.viewHelper; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import javax.servlet.http.HttpServletRequest; import com.sinosoft.claim.dto.custom.StatStatusDto; import com.sinosoft.claim.dto.custom.UserDto; import com.sinosoft.claim.dto.domain.SwfLogDto; import com.sinosoft.claim.ui.control.action.UICodeAction; import com.sinosoft.claim.ui.control.action.UIPowerInterface; import com.sinosoft.claim.ui.control.action.UIWorkFlowAction; import com.sinosoft.claim.util.BusinessRuleUtil; import com.sinosoft.sysframework.common.datatype.DateTime; /** * <p>Title: WorkFlwoStatViewHelper</p>c * <p>Description:һЩͳƵ࣬ڸҳݵ</p> * <p>Copyright: Copyright пƼɷ޹˾(c) 2004</p> * @author Ŀ lixiang * @version 1.0 * <br> */ public class WorkFlowStatViewHelper { /** * ĬϹ췽 */ public WorkFlowStatViewHelper() {//COM.IIDIDispatch } /*========================岿֣ͳƲ========================*/ /** * ͳ--ڵ״̬ͳƹڵ״̬Ĺ * @param httpServletRequest HttpServletRequest * @param strStartDate String * @param strEndDate String * @throws Exception * @return StatStatusDto */ public StatStatusDto getNodeStatusStat(HttpServletRequest httpServletRequest,String strStartDate,String strEndDate) throws Exception { //ڼ String endDateLast = new DateTime(strEndDate).addDay(1).toString() ; String conditions =" handleTime>='"+strStartDate+"' and handleTime<'"+endDateLast+"' "; StatStatusDto statStatusDto = new StatStatusDto(); UIWorkFlowAction uiWorkFlowAction = new UIWorkFlowAction (); Collection statStatusDtoList = new ArrayList(); statStatusDtoList = uiWorkFlowAction.getNodeStatusStat(conditions); statStatusDto.setStatStatusList(statStatusDtoList); statStatusDto.setStartDate(strStartDate); statStatusDto.setEndDate(strEndDate); //ѯĽ뵽 httpServletRequest.setAttribute("statStatusDto",statStatusDto) ; //״̬ݲѯ UICodeAction uiCodeAction = new UICodeAction(); Collection claimStatusList = (ArrayList)uiCodeAction.getCodeType("ClaimStatus", BusinessRuleUtil.getOuterCode(httpServletRequest,"RISKCODE_DAA")); httpServletRequest.setAttribute("claimStatusList", claimStatusList); return statStatusDto; } /** * ͳ--ûڵ״̬ͳƹڵû״̬Ĺ * @param httpServletRequest HttpServletRequest * @param strStartDate String * @param strEndDate String * @throws Exception * @return StatStatusDto */ public StatStatusDto getNodeUserStatusStat(HttpServletRequest httpServletRequest,String strStartDate,String strEndDate) throws Exception { //ڼ String endDateLast = new DateTime(strEndDate).addDay(1).toString() ; String conditions =" handleTime>='"+strStartDate+"' and handleTime<'"+endDateLast+"' "; StatStatusDto statStatusDto = new StatStatusDto(); UIWorkFlowAction uiWorkFlowAction = new UIWorkFlowAction (); Collection statStatusDtoList = new ArrayList(); statStatusDtoList = uiWorkFlowAction.getNodeUserStatusStat(conditions); statStatusDto.setStatStatusList(statStatusDtoList); statStatusDto.setStartDate(strStartDate); statStatusDto.setEndDate(strEndDate); //ѯĽ뵽 httpServletRequest.setAttribute("statStatusDto",statStatusDto) ; return statStatusDto; } /** * ѯ--ʱ鿴ѯʱϢ * @param httpServletRequest HttpServletRequest * @param conditions String ѯ * @throws Exception * @return Collection */ public Collection getNodeTimeOutInfo(HttpServletRequest httpServletRequest,String conditions) throws Exception { Collection swfLogDtoList = new ArrayList(); Collection swfLogDtoLastList = new ArrayList(); UIWorkFlowAction uiWorkFlowAction = new UIWorkFlowAction(); UICodeAction uiCodeAction = new UICodeAction(); SwfLogDto swfLogDto = new SwfLogDto(); swfLogDtoList = uiWorkFlowAction.findNodesByConditions(conditions); Iterator it = swfLogDtoList.iterator() ; String riskCodeName =""; String nodeStatusName =""; String nodeTypeName =""; int count=0; while (it.hasNext() ) { //ת SwfLogDto swfLogDtoTemp = new SwfLogDto(); swfLogDtoTemp = (SwfLogDto)it.next() ; //㳬ʱʱ䳤 //public static int intervalDay(DateTime startDate, int startHour, DateTime endDate, int endHour) { return 0;} count =DateTime.intervalDay(new DateTime(swfLogDtoTemp.getHandleTime(),DateTime.YEAR_TO_DAY ),0,new DateTime(DateTime.current(),DateTime.YEAR_TO_DAY ) ,0) -1; //-1Ϊ˳ͳƵĵ swfLogDtoTemp.setTimeLimit(count); //ת riskCodeName = uiCodeAction.translateRiskCode(swfLogDtoTemp.getRiskCode(),true); swfLogDtoTemp.setRiskCodeName(riskCodeName); nodeStatusName =uiCodeAction.translateCodeCode("ClaimStatus",swfLogDtoTemp.getNodeStatus() ,true); swfLogDtoTemp.setNodeStatusName(nodeStatusName); nodeTypeName=uiCodeAction.translateCodeCode("ClaimNodeType",swfLogDtoTemp.getNodeType() ,true); swfLogDtoTemp.setNodeTypeName(nodeTypeName) ; swfLogDtoLastList.add(swfLogDtoTemp); } swfLogDto.setSwfLogList(swfLogDtoLastList); //ѯĽ뵽 httpServletRequest.setAttribute("swfLogDto",swfLogDto) ; return swfLogDtoLastList; } /** * ݽڵͲ״̬ͰԱѯ鿱Ϣ * @param httpServletRequest ظҳrequest * @param status ״̬ * @param user Ա/û * @param nodeType ڵ * @throws Exception */ public void getWorkFLowNodeStatsStat(HttpServletRequest httpServletRequest,UserDto user,String nodeType) throws Exception { //״̬ûIDSQL where Ӿ String conditions = ""; String riskType = httpServletRequest.getParameter("type"); //add by liuyanmei 20051110 //ʵڵ㲻ͬ if (nodeType.equals("compe") ) { //modify by liuyanmei modify 20051110 start //reason :⽡ͳֵͳ if( nodeType.equals("compe") && (httpServletRequest.getParameter("type") != null && httpServletRequest.getParameter("type").equals("acci"))) { conditions = conditions + " ((nodeStatus='0' AND NodeType ='compe'" + " and (flowStatus='1' or flowStatus='2') " + " and (riskcode like '07%' or riskCode like '06%'))" + " or (((nodeType='compp' and (riskcode like '07%' or riskCode like '06%') " + " and ((flowStatus='0' and (nodeStatus='4' or nodeStatus='5' ))" + " or (flowStatus='1' or flowStatus='2'))) and HandlerCode = '" + user.getUserCode()+"'))) " ; } else { conditions = conditions + " ((nodeStatus='0' AND NodeType ='compe'" + " and (flowStatus='1' or flowStatus='2') " + " and (riskcode not like '07%' and riskCode not like '06%'))" + " or (((nodeType='compp' and (riskcode like '07%' or riskCode like '06%') " +" and ((flowStatus='0' and (nodeStatus='4' or nodeStatus='5' ))" + " or (flowStatus='1' or flowStatus='2'))) and HandlerCode = '" + user.getUserCode()+"'))) " ; } //modify by liuyanmei modify 20051110 end }else{//ڵͳ //modify by wangwei add start 2005-06-12 //ԭ򣺸ݲͬIJѯ⽡պͷ⽡յѯ. if (httpServletRequest.getParameter("type") != null && httpServletRequest.getParameter("type").equals("acci")) { //Ϊղѯ conditions = conditions + " ((HandlerCode = '" + user.getUserCode() + "') or (handlerCode is Null and nodeStatus='0')or (handlerCode= '' and nodeStatus='0')) AND (NodeType = '" + nodeType+"') and (flowStatus='1' or flowStatus='2' or " + "(flowStatus='0' and (nodeStatus='4' or nodeStatus='5' ))) " + " and (riskcode like '07%' or riskCode like '06%')" ; System.out.println("=============Ϊղѯ" + conditions); } else { //Ϊղѯ if(nodeType.equals("verip")){ //˼Ҫѯ conditions = conditions + " ((HandlerCode = '" + user.getUserCode() + "') or (handlerCode is Null and nodeStatus='0')or (handlerCode= '' and nodeStatus='0')) AND (NodeType = 'verip'" + " or NodeType = 'verpo') and (flowStatus='1' or flowStatus='2' or " + "(flowStatus='0' and (nodeStatus='4' or nodeStatus='5' ))) " + " and riskcode not like '07%' and riskCode not like '06%'"; }else{ conditions = conditions + " ((HandlerCode = '" + user.getUserCode() + "') or (handlerCode is Null and nodeStatus='0')or (handlerCode= '' and nodeStatus='0')) AND (NodeType = '" + nodeType+"') and (flowStatus='1' or flowStatus='2' or " + "(flowStatus='0' and (nodeStatus='4' or nodeStatus='5' ))) " + " and riskcode not like '07%' and riskCode not like '06%'"; } System.out.println("=============Ϊղѯ" + conditions); } //modify by wangwei add end 2005-06-12 } //ʼʱ String statStartDate = httpServletRequest.getParameter("statStartDate"); if(statStartDate != null && statStartDate.trim().length()>0){ conditions = conditions +" AND HandleTime >= '" + statStartDate +"'"; } //ʱ String statEndDate = httpServletRequest.getParameter("statEndDate"); if(statEndDate != null && statEndDate.trim().length()>0){ conditions = conditions +" AND HandleTime <= '" + statEndDate +"'"; } //Ȩ޿ /**UIPrpPersonLimitAction uiPrpPersonLimitAction = new UIPrpPersonLimitAction(); String conditionRisk = uiPrpPersonLimitAction.findByUsercode(user.getUserCode()); conditions = conditions + conditionRisk;*/ //ƴȨ //modify by zhaolu 20060816 start UIPowerInterface uiPowerInterface = new UIPowerInterface(); UserDto userDto = (UserDto)httpServletRequest.getSession().getAttribute("user"); //conditions = conditions+uiPowerInterface.addPower(userDto.getUserCode(),com.sinosoft.claim.util.BusinessRuleUtil.transTaskCode(nodeType),"swflog",BusinessRuleUtil.getOuterCode(httpServletRequest,"RISKCODE_DAA")); conditions = conditions + uiPowerInterface.addPower(userDto,"swflog","","ComCode"); //modify by zhaolu 20060816 end //ѯڵ״̬Ϣ UIWorkFlowAction uiWorkFlowAction = new UIWorkFlowAction(); //õбϢ ArrayList claimStatusStatList = new ArrayList(); ArrayList claimNodeListLast = new ArrayList(); UICodeAction uiCodeAction = new UICodeAction(); String statusCode=""; String statusName=""; String oldStatus=""; String nowStatus=""; System.out.println("ǰ."); claimStatusStatList = (ArrayList)uiWorkFlowAction.getStatStatus(conditions) ; int intRetrun=0; System.out.println("."); Iterator it = claimStatusStatList.iterator() ; while (it.hasNext()) { StatStatusDto statStatusDtoTemp = new StatStatusDto(); statStatusDtoTemp = (StatStatusDto)it.next() ; statusCode = statStatusDtoTemp.getStatus() ; //if (statusCode.equals("0") &&statStatusDtoTemp.getUserCode()!=null) statusCode="1"; statusName=uiCodeAction.translateCodeCode("ClaimStatus",statusCode,true); //ͳеIJ if(statusCode.equals("0")||statusCode.equals("1")){ statStatusDtoTemp.setStatusName(""); } else { statStatusDtoTemp.setStatusName(statusName); } if(statusCode.equals("3")){intRetrun=statStatusDtoTemp.getCount(); System.out.println("-------intRetrun---------"+intRetrun);} //statStatusDtoTemp.setStatusName(statusName); statStatusDtoTemp.setStatus(statusCode); statStatusDtoTemp.setUserCode( user.getUserCode()); statStatusDtoTemp.setUserName( user.getUserName()); claimNodeListLast.add(statStatusDtoTemp); } for (int i = 0; i < claimNodeListLast.size(); i++) { StatStatusDto statStatusDtoTemp1 = (StatStatusDto)claimNodeListLast.get(i); if(statStatusDtoTemp1.getStatus().equals("0"))statStatusDtoTemp1.setCount(statStatusDtoTemp1.getCount()+intRetrun); } StatStatusDto statStatusDto = new StatStatusDto(); statStatusDto.setStatStatusList(claimNodeListLast); System.out.println("finish add list"); statStatusDto.setEditType((String)httpServletRequest.getAttribute("editType")) ; statStatusDto.setNodeType(nodeType); statStatusDto.setUserCode(user.getUserCode()); httpServletRequest.setAttribute("statStatusDto",statStatusDto) ; Collection claimStatusList = (ArrayList)uiCodeAction.getCodeType("ClaimStatus", "0000"); httpServletRequest.setAttribute("claimStatusList", claimStatusList); httpServletRequest.setAttribute("riskType", riskType); } /*========================ͳƲ============================*/ }
Go
UTF-8
281
2.921875
3
[]
no_license
package hamming import "errors" const TestVersion = 2 func Distance(s1, s2 string) (int, error) { if len(s1) != len(s2) { return 0, errors.New("strings must be of equal length") } dist := 0 for i := range s1 { if s1[i] != s2[i] { dist += 1 } } return dist, nil }
Shell
UTF-8
472
3.21875
3
[]
no_license
#!/bin/bash #this scripts will begin training, #setup vec files, and train #takes one argument (no. of positive files) if [[ $# -lt 1 ]]; then cat <<- EOF this scripts takes minimum 1 argument: (the number of positive images) and optional (view images : "true" ? ) EOF exit 0 fi opencv_createsamples -info positives.info -num "$1" -w 30 -h 30 -vec vector_positives.vec if [[ $2 ]]; then opencv_createsamples -vec vector_positives.vec -w 30 -h 30 fi mkdir data
Java
UTF-8
1,806
3.640625
4
[]
no_license
package edu.institution.clazz; import edu.institution.person.Person; import java.util.ArrayList; import java.util.List; /** * Represents an academic class at an institution. */ public class AcademicClass { final int id; private final String name; private final Person faculty; // A faculty member could be a student too private final List<Person> students; public AcademicClass(final int id, final String name, final Person person) { if (!person.isFaculty()) { throw new IllegalArgumentException("The supplied person is not a person!: " + person); } this.id = id; this.name = name; this.faculty = person; this.students = new ArrayList<Person>(); } public int getId() { return id; } public String getName() { return name; } public Person getFaculty() { return faculty; } public List<Person> getStudents() { return students; } public void addStudent(final Person person) { this.students.add(person); } /** * Checks whether the supplied person is a student in this class. * * @param person The person to check. * @return true if the person is a student of this class, false otherwise. */ public boolean hasStudent(final Person person) { for (final Person student : students) { if (student.equals(person)) { return true; } } return false; } @Override public String toString() { final StringBuilder sb = new StringBuilder("AcademicClass{"); sb.append("name='").append(name).append('\''); sb.append(", faculty=").append(faculty); sb.append('}'); return sb.toString(); } }
Swift
UTF-8
1,603
3
3
[ "MIT" ]
permissive
// // XcodeConsoleLogger.swift // // // Created by 刘万林 on 2021/9/2. // import Foundation #if SPM import BSKUtils #endif /// 在Xcode的控制台输出日志 open class BSKLogConsoleDestination: LogDestination { /// 详细模式,输出更多调试信息 open var detailMode = true /// 单条日志显示的最大长度,过长的日志打印会导致Xcode Console 白屏,可以设置这个属性来限制输出的最大长度,默认为nil,不限制。 open var maxLength: Int? open var printMode: PrintMode = .print public enum PrintMode { case nslog case print } public init() { } open func printLog(_ log: BSKLogObject) { var logStr = log.log let fileURL = URL(fileURLWithPath: log.file) let fileName = fileURL.lastPathComponent if let max = maxLength, log.log.count > max { logStr = String(log.log[..<max]) + "【内容过长,截取部分】" } var printStr = "" if detailMode { printStr.append("\n┌[\(log.level.flag)] 文件:\(fileName)第\(log.line)行 \(log.function) 线程:\(log.threadInfo) \n") printStr.append("│ ") printStr.append(logStr.replacingOccurrences(of: "\n", with: "\n│ ")) printStr.append("\n") printStr.append("└――――――") } else { printStr = "[\(log.level.flag)]: \(logStr)" } switch printMode { case .nslog: NSLog(printStr) case .print: print(printStr) } } }
TypeScript
UTF-8
3,791
2.71875
3
[ "MIT" ]
permissive
import { helpers } from '../../src/helpers'; // helpers.getMeasure-positive // import iMyModule from '../interfaces/IMyModule'; import { QueueWorker } from '../../src/modules/QueueWorker'; // private async processItem(item: PackageInfo): Promise<PackageInfo> { const delay = 100; const delayPadded = delay + delay * 0.2 + 100; const processItem = (input: string, id: string): Promise<string> => { let p = helpers.newPromise<string>(); helpers.sleep(delay).then(() => { // console.log('Resolved: ', id, input); p.resolve(input + '-xxx'); }); return p; //.getPromise(); }; const queueWorker = new QueueWorker<string, string>(processItem); beforeEach(() => {}); test('queue new', async () => { let p = queueWorker.enqueue('aaa', '0'); await expect(p).resolves.toEqual('aaa-xxx'); // p.then((res)=>{ // expect(res).toBe('aaa-xxx'); // }) }); test('queue with maxConcurrent 1 & serial', async () => { const queueWorker = new QueueWorker<string, string>(processItem, null, 1); const startDate = new Date().getTime(); let p1 = queueWorker.enqueue('aa1', '1'); p1.then((res) => { expect(new Date().getTime() - startDate).toBeLessThanOrEqual(delayPadded); }); await p1; let p2 = queueWorker.enqueue('aa2', '2'); await p2; let p3 = queueWorker.enqueue('aa3', '3'); await p3; let res = await Promise.all([p1, p2, p3]); expect(res).toEqual(['aa1-xxx', 'aa2-xxx', 'aa3-xxx']); }); test('queue with maxConcurrent 1', async () => { const queueWorker = new QueueWorker<string, string>(processItem, null, 1); const startDate = new Date().getTime(); let p1 = queueWorker.enqueue('aa1', '1'); p1.then((res) => { expect(new Date().getTime() - startDate).toBeLessThanOrEqual(delayPadded); }); let p2 = queueWorker.enqueue('aa2', '2'); p2.then((res) => { expect(new Date().getTime() - startDate).toBeLessThanOrEqual(delayPadded * 2); }); let p3 = queueWorker.enqueue('aa3', '3'); p3.then((res) => { expect(new Date().getTime() - startDate).toBeLessThanOrEqual(delayPadded * 3); }); let res = await Promise.all([p1, p2, p3]); expect(res).toEqual(['aa1-xxx', 'aa2-xxx', 'aa3-xxx']); }); test('queue with maxConcurrent 2', async () => { const queueWorker = new QueueWorker<string, string>(processItem, null, 2); const startDate = new Date().getTime(); let p1 = queueWorker.enqueue('aa1', '1'); let p2 = queueWorker.enqueue('aa2', '2'); p1.then((res) => { expect(new Date().getTime() - startDate).toBeLessThanOrEqual(delayPadded); }); p2.then((res) => { expect(new Date().getTime() - startDate).toBeLessThanOrEqual(delayPadded); }); let p3 = queueWorker.enqueue('aa3', '3'); p3.then((res) => { expect(new Date().getTime() - startDate).toBeLessThanOrEqual(delayPadded * 2); }); let res = await Promise.all([p1, p2, p3]); expect(res).toEqual(['aa1-xxx', 'aa2-xxx', 'aa3-xxx']); }); test('queue with maxConcurrent 3', async () => { const queueWorker = new QueueWorker<string, string>(processItem, null, 3); const startDate = new Date().getTime(); let p1 = queueWorker.enqueue('aa1', '1'); let p2 = queueWorker.enqueue('aa2', '2'); let p3 = queueWorker.enqueue('aa3', '3'); p1.then((res) => { expect(new Date().getTime() - startDate).toBeLessThanOrEqual(delayPadded); }); p2.then((res) => { expect(new Date().getTime() - startDate).toBeLessThanOrEqual(delayPadded); }); p3.then((res) => { expect(new Date().getTime() - startDate).toBeLessThanOrEqual(delayPadded); }); let res = await Promise.all([p1, p2, p3]); expect(res).toEqual(['aa1-xxx', 'aa2-xxx', 'aa3-xxx']); });
Java
UTF-8
1,758
2.15625
2
[]
no_license
package com.im.commons.zookeeper.properties; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.validation.annotation.Validated; /** * <p>Title: </p> * <p>Description: TODO(zookeeper配置文件)</p> * <p>Company: laixun</p> * @author Alix * @date 2019年8月15日 下午2:09:20 */ @ConfigurationProperties(prefix="zookeeper") @Validated public class ZookeeperProperties { private String server; private String namespace; private String digest; private Integer sessionTimeoutMs = 60000; private Integer connectionTimeoutMs = 6000; private Integer maxRetries = 3; private Integer baseSleepTimeMs = 1000; public String getServer() { return server; } public void setServer(String server) { this.server = server; } public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } public String getDigest() { return digest; } public void setDigest(String digest) { this.digest = digest; } public Integer getSessionTimeoutMs() { return sessionTimeoutMs; } public void setSessionTimeoutMs(Integer sessionTimeoutMs) { this.sessionTimeoutMs = sessionTimeoutMs; } public Integer getConnectionTimeoutMs() { return connectionTimeoutMs; } public void setConnectionTimeoutMs(Integer connectionTimeoutMs) { this.connectionTimeoutMs = connectionTimeoutMs; } public Integer getMaxRetries() { return maxRetries; } public void setMaxRetries(Integer maxRetries) { this.maxRetries = maxRetries; } public Integer getBaseSleepTimeMs() { return baseSleepTimeMs; } public void setBaseSleepTimeMs(Integer baseSleepTimeMs) { this.baseSleepTimeMs = baseSleepTimeMs; } }
Python
UTF-8
718
3.328125
3
[]
no_license
from random import shuffle class Trainer(object): def __init__(self, cards): self.cards = cards def shuffle(self): shuffle(self.cards) def train(self): for card in self.cards: Trainer.train_card(card) @staticmethod def train_card(card): for turn in card.turns: print(turn.prompt.prompt) for response in turn.responses: ans = input('') if not ans == response.response: print(u'\u274C') for response in turn.responses: print(response.response) print() return print(u'\u2705' + '\n')
Markdown
UTF-8
2,116
3.34375
3
[]
no_license
# cs-vis-project CS 329E Elements of Data Visualization Project By Anna-Maria Andreeva, Ishita Kumar, and Crystal Tse In this project, two visualizations were developed using Altair (Python visualization library) to inform prospective and current University of Texas system students about salary prospects of different areas of study based on historical data. Using the SeekUT dataset, which has major, industry, and salary data, we developed visualizations that provide easy access to comprehensive information about financial prospects of different areas of study. In visualization 1, users filter to their UT system university of interest by using the dropdown menu. Once a university has been selected, users can explore the average salaries of different industries of study for that campus, along with the institution median. Users can select as many or as few industries to explore salary information for. The resulting line chart from this visualization shows salary data at the 1, 5, and 10 year points after graduation. A tooltip allows users to determine the exact salary numbers at these points in time. <img src="./images/vis-1-demo.jpg" alt="Visualization 1. Each line represents an industry's median salary and its change over time." width = "700"/> In visualization 2, users get to explore salary data by industry of study even further for each school in the UT System. Users first select a university and a “years out of college” point in time they want to view salary data for. They can then select as many industries as they want from the histogram, and a boxplot of salary data for specific majors within each industry will be displayed about the median, 10th percentile, 25th percentile, 75th percentile, 90th percentile salary information for each major, also accessible through the tooltip. <img src="./images/vis-2-demo-pt1.jpg" alt="Visualization 2. Selecting individual bars/industries allows the user to see major distributions below." width = "700" /> <img src="./images/vis-2-demo-pt2.jpg" alt="Visualization 2. Individual major distributions can be viewed through the boxplots." width = "700" />
Java
UTF-8
284
1.8125
2
[]
no_license
package client.model; import shared.util.PropertyChangeSubject; public interface BlackJackDataModel extends PropertyChangeSubject { void giveCardToPlayer(); void giveCardToDealer(); void giveCardToDealer2(); void giveCardToPlayer2(); void getTheScore(); }
Java
UTF-8
18,315
1.757813
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 br.telas; import br.caixageral.CaixaGeral; import br.caixageral.CaixaGeralDAO; import br.contabancaria.ContaBancaria; import br.contabancaria.ContaBancariaDAO; import br.contabancaria.ItemContaBancaria; import br.contabancaria.ItemContaBancariaDAO; import br.contaspagar.ContasPagar; import br.contaspagar.ContasPagarDAO; import br.contasreceber.ContasReceber; import br.contasreceber.ContasReceberDAO; import br.livro.LivroCaixa; import br.livro.LivroCaixaDAO; import br.util.Ativo; import br.util.Util; import java.awt.event.KeyEvent; import java.util.Date; import javax.swing.JOptionPane; /** * * @author Pedro Saraiva */ public class TelaContaPagarRec extends javax.swing.JDialog { private static ContasPagar cr; /** * Creates new form TelaCliente */ public TelaContaPagarRec(ContasPagar cr) { initComponents(); this.cr = cr; setModal(true); setTitle("Receber Conta"); setLocationRelativeTo(null); lblCliente.setText(cr.getFornecedor() != null ? cr.getFornecedor().getRazaoSocial() : cr.getDescricao()); lblDataVencimento.setText(String.valueOf(cr.getDataVencimento())); lblValor.setText(String.valueOf(cr.getValor())); rbCxGeral.setSelected(true); preencheContas(); tfValor.requestFocus(); } public TelaContaPagarRec() { initComponents(); } public void preencheContas() { cbContaBancaria.removeAllItems(); cbContaBancaria.addItem("--"); ContaBancariaDAO cbDAO = new ContaBancariaDAO(); for (ContaBancaria col : cbDAO.list()) { cbContaBancaria.addItem(col); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroup1 = new javax.swing.ButtonGroup(); jPanel4 = new javax.swing.JPanel(); lbTexto = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); btCancelar = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); tfValor = new javax.swing.JFormattedTextField(); btSalvar = new javax.swing.JButton(); lblCliente = new javax.swing.JLabel(); lblDataVencimento = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); lblValor = new javax.swing.JLabel(); jLabel7 = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); rbContaBancaria = new javax.swing.JRadioButton(); rbCxGeral = new javax.swing.JRadioButton(); cbContaBancaria = new javax.swing.JComboBox(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setResizable(false); getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); jPanel4.setBackground(new java.awt.Color(0, 153, 255)); jPanel4.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); lbTexto.setFont(new java.awt.Font("Bitstream Vera Sans Mono", 1, 30)); // NOI18N lbTexto.setText("Receber Conta"); jPanel4.add(lbTexto, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 350, 40)); getContentPane().add(jPanel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 430, 40)); jPanel1.setBackground(new java.awt.Color(255, 255, 255)); jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); btCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/imagens/close.png"))); // NOI18N btCancelar.setToolTipText("Sair"); btCancelar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btCancelarActionPerformed(evt); } }); jPanel1.add(btCancelar, new org.netbeans.lib.awtextra.AbsoluteConstraints(370, 310, 43, 41)); jLabel2.setFont(new java.awt.Font("Bitstream Vera Sans Mono", 0, 12)); // NOI18N jLabel2.setText("Valor Pago.: *"); jPanel1.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 250, -1, -1)); tfValor.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.NumberFormatter(new java.text.DecimalFormat("#0.00")))); tfValor.setFont(new java.awt.Font("Bitstream Vera Sans Mono", 0, 12)); // NOI18N tfValor.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tfValorActionPerformed(evt); } }); tfValor.addFocusListener(new java.awt.event.FocusAdapter() { public void focusLost(java.awt.event.FocusEvent evt) { tfValorFocusLost(evt); } }); tfValor.addKeyListener(new java.awt.event.KeyAdapter() { public void keyPressed(java.awt.event.KeyEvent evt) { tfValorKeyPressed(evt); } }); jPanel1.add(tfValor, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 270, 180, -1)); btSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/imagens/pataverde.png"))); // NOI18N btSalvar.setToolTipText("Salvar"); btSalvar.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btSalvarActionPerformed(evt); } }); jPanel1.add(btSalvar, new org.netbeans.lib.awtextra.AbsoluteConstraints(320, 310, 43, -1)); lblCliente.setFont(new java.awt.Font("Bitstream Vera Sans Mono", 0, 12)); // NOI18N lblCliente.setText("Cliente.: *"); jPanel1.add(lblCliente, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 120, -1, -1)); lblDataVencimento.setFont(new java.awt.Font("Bitstream Vera Sans Mono", 0, 12)); // NOI18N lblDataVencimento.setText("Data Vencimento.: *"); jPanel1.add(lblDataVencimento, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 170, -1, -1)); jLabel5.setFont(new java.awt.Font("Bitstream Vera Sans Mono", 0, 12)); // NOI18N jLabel5.setText("Descrição.:"); jPanel1.add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 100, -1, -1)); jLabel6.setFont(new java.awt.Font("Bitstream Vera Sans Mono", 0, 12)); // NOI18N jLabel6.setText("Data Vencimento.: "); jPanel1.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 150, -1, -1)); lblValor.setFont(new java.awt.Font("Bitstream Vera Sans Mono", 0, 12)); // NOI18N lblValor.setText("Data Vencimento.: *"); jPanel1.add(lblValor, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 220, -1, -1)); jLabel7.setFont(new java.awt.Font("Bitstream Vera Sans Mono", 0, 12)); // NOI18N jLabel7.setText("Valor.:"); jPanel1.add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 200, -1, -1)); jPanel2.setBackground(new java.awt.Color(255, 255, 255)); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Pagar Com")); jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout()); rbContaBancaria.setBackground(new java.awt.Color(255, 255, 255)); buttonGroup1.add(rbContaBancaria); rbContaBancaria.setText("Conta Bancária"); rbContaBancaria.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { rbContaBancariaItemStateChanged(evt); } }); rbContaBancaria.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { rbContaBancariaActionPerformed(evt); } }); jPanel2.add(rbContaBancaria, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 20, -1, -1)); rbCxGeral.setBackground(new java.awt.Color(255, 255, 255)); buttonGroup1.add(rbCxGeral); rbCxGeral.setText("Caixa Geral"); rbCxGeral.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { rbCxGeralItemStateChanged(evt); } }); rbCxGeral.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { rbCxGeralActionPerformed(evt); } }); jPanel2.add(rbCxGeral, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 20, -1, -1)); cbContaBancaria.setFont(new java.awt.Font("Bitstream Vera Sans Mono", 0, 11)); // NOI18N cbContaBancaria.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "--" })); cbContaBancaria.setEnabled(false); jPanel2.add(cbContaBancaria, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 50, 270, -1)); jPanel1.add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 10, 400, 80)); getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 40, 430, 370)); pack(); }// </editor-fold>//GEN-END:initComponents private void btCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCancelarActionPerformed setVisible(false); }//GEN-LAST:event_btCancelarActionPerformed private void btSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSalvarActionPerformed if (!tfValor.getText().equals("")) { if (JOptionPane.showConfirmDialog(rootPane, "Deseja Pagar Essa Conta?", "Paar", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { if (rbContaBancaria.isSelected()) { if (cbContaBancaria.getSelectedIndex() == 0) { JOptionPane.showMessageDialog(rootPane, "Informe a Conta Bancária!"); return; } } double valoraReceber = Double.parseDouble(tfValor.getText().replace(",", ".")); cr.setDataPagamento(new Date()); cr.setPaga(true); cr.setValorPago(valoraReceber); ContasPagarDAO cDAO = new ContasPagarDAO(); cDAO.update(cr); if (rbCxGeral.isSelected()) { CaixaGeral cg = new CaixaGeral(); cg.setContaPagar(cr); cg.setData(new Date()); String descricao = cr.getFornecedor() != null ? cr.getFornecedor().getRazaoSocial() : cr.getDescricao(); cg.setDescricao("CONTA PAGA de " + descricao + " Nº" + cr.getNrConta()); cg.setValorSaida(valoraReceber); cg.setValorEntrada(0); CaixaGeralDAO cgDAO = new CaixaGeralDAO(); cgDAO.add(cg); } else { ItemContaBancaria icb = new ItemContaBancaria(); icb.setContaBancaria((ContaBancaria) cbContaBancaria.getSelectedItem()); icb.setContaPagar(cr); icb.setData(new Date()); String descricao = cr.getFornecedor() != null ? cr.getFornecedor().getRazaoSocial() : cr.getDescricao(); icb.setDescricao("CONTA PAGA de " + descricao + " Nº" + cr.getNrConta()); icb.setEntrada(0); icb.setSaida(valoraReceber); ItemContaBancariaDAO icbDAO = new ItemContaBancariaDAO(); icbDAO.add(icb); } if (valoraReceber < cr.getValor()) { if (JOptionPane.showConfirmDialog(rootPane, "Valor Pago Menor que Valor da Conta" + "\nDeseja Criar uma nova Conta com o Restante do Valor?", "Pagar", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) { ContasPagar cr2 = new ContasPagar(); if (cr.getFornecedor() != null) { cr2.setFornecedor(cr.getFornecedor()); } cr2.setDescricao(cr.getDescricao()); cr2.setDataVencimento(cr.getDataVencimento()); cr2.setNrConta("P" + cr.getNrConta()); cr2.setNrParcela(cr.getNrParcela()); cr2.setValor(cr.getValor() - valoraReceber); cr2.setPaga(false); cDAO.add(cr2); } } dispose(); } } else { JOptionPane.showMessageDialog(rootPane, "Informe o Valor à receber!"); } }//GEN-LAST:event_btSalvarActionPerformed private void tfValorActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfValorActionPerformed }//GEN-LAST:event_tfValorActionPerformed private void tfValorKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfValorKeyPressed if (evt.getKeyCode() == KeyEvent.VK_ENTER) { btSalvarActionPerformed(null); } }//GEN-LAST:event_tfValorKeyPressed private void tfValorFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_tfValorFocusLost if (Util.verificaValor(tfValor.getText(), 0) == null) { tfValor.setText(""); } }//GEN-LAST:event_tfValorFocusLost private void rbContaBancariaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbContaBancariaActionPerformed // TODO add your handling code here: }//GEN-LAST:event_rbContaBancariaActionPerformed private void rbCxGeralActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbCxGeralActionPerformed }//GEN-LAST:event_rbCxGeralActionPerformed private void rbCxGeralItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_rbCxGeralItemStateChanged if (rbCxGeral.isSelected()) { cbContaBancaria.setEnabled(false); } else { cbContaBancaria.setEnabled(true); } }//GEN-LAST:event_rbCxGeralItemStateChanged private void rbContaBancariaItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_rbContaBancariaItemStateChanged if (rbCxGeral.isSelected()) { cbContaBancaria.setEnabled(false); } else { cbContaBancaria.setEnabled(true); } }//GEN-LAST:event_rbContaBancariaItemStateChanged /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(TelaContaPagarRec.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(TelaContaPagarRec.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(TelaContaPagarRec.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(TelaContaPagarRec.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new TelaContaPagarRec().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btCancelar; private javax.swing.JButton btSalvar; private javax.swing.ButtonGroup buttonGroup1; private javax.swing.JComboBox cbContaBancaria; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel4; private javax.swing.JLabel lbTexto; private javax.swing.JLabel lblCliente; private javax.swing.JLabel lblDataVencimento; private javax.swing.JLabel lblValor; private javax.swing.JRadioButton rbContaBancaria; private javax.swing.JRadioButton rbCxGeral; private javax.swing.JFormattedTextField tfValor; // End of variables declaration//GEN-END:variables }
Markdown
UTF-8
9,848
2.875
3
[ "MIT" ]
permissive
--- id: Foldable2v title: Foldable2v --- [Source](https://github.com/gcanti/fp-ts/blob/master/src/Foldable2v.ts) # Foldable2v **Signature** (type class) [Source](https://github.com/gcanti/fp-ts/blob/master/src/Foldable2v.ts#L36-L39) ```ts export interface Foldable2v<F> extends Foldable<F> { readonly foldMap: <M>(M: Monoid<M>) => <A>(fa: HKT<F, A>, f: (a: A) => M) => M readonly foldr: <A, B>(fa: HKT<F, A>, b: B, f: (a: A, b: B) => B) => B } ``` Added in v1.10.0 ## elem Test whether a value is an element of a data structure **Signature** (function) [Source](https://github.com/gcanti/fp-ts/blob/master/src/Foldable2v.ts#L438-L440) ```ts export function elem<F, A>(S: Setoid<A>, F: Foldable2v<F>): (a: A, fa: HKT<F, A>) => boolean { ... } ``` **Example** ```ts import { elem } from 'fp-ts/lib/Foldable2v' import { setoidNumber } from 'fp-ts/lib/Setoid' import { Tree, tree } from 'fp-ts/lib/Tree' const t = new Tree(1, [new Tree(2, []), new Tree(3, []), new Tree(4, [])]) assert.strictEqual(elem(setoidNumber, tree)(2, t), true) assert.strictEqual(elem(setoidNumber, tree)(5, t), false) ``` Added in v1.14.0 ## findFirst Find the first element which satisfies a predicate function **Signature** (function) [Source](https://github.com/gcanti/fp-ts/blob/master/src/Foldable2v.ts#L468-L477) ```ts export function findFirst<F>(F: Foldable2v<F>): <A>(fa: HKT<F, A>, p: Predicate<A>) => Option<A> { ... } ``` **Example** ```ts import { findFirst } from 'fp-ts/lib/Foldable2v' import { Tree, tree } from 'fp-ts/lib/Tree' import { some } from 'fp-ts/lib/Option' const t = new Tree(1, [new Tree(2, []), new Tree(3, []), new Tree(4, [])]) assert.deepStrictEqual(findFirst(tree)(t, a => a > 2), some(3)) ``` Added in v1.10.0 ## fold A generalization of monoidal `fold` **Signature** (function) [Source](https://github.com/gcanti/fp-ts/blob/master/src/Foldable2v.ts#L194-L196) ```ts export function fold<M, F>(M: Monoid<M>, F: Foldable2v<F>): (fa: HKT<F, M>) => M { ... } ``` **Example** ```ts import { fold } from 'fp-ts/lib/Foldable2v' import { Tree, tree } from 'fp-ts/lib/Tree' import { monoidSum } from 'fp-ts/lib/Monoid' const t = new Tree(1, [new Tree(2, []), new Tree(3, []), new Tree(4, [])]) assert.strictEqual(fold(monoidSum, tree)(t), 10) ``` Added in v1.10.0 ## foldM Similar to 'reduce', but the result is encapsulated in a monad. Note: this function is not generally stack-safe, e.g., for monads which build up thunks a la `IO`. **Signature** (function) [Source](https://github.com/gcanti/fp-ts/blob/master/src/Foldable2v.ts#L237-L242) ```ts export function foldM<M, F>( M: Monad<M>, F: Foldable2v<F> ): <A, B>(fa: HKT<F, A>, b: B, f: (b: B, a: A) => HKT<M, B>) => HKT<M, B> { ... } ``` **Example** ```ts import { foldM } from 'fp-ts/lib/Foldable2v' import { option, some } from 'fp-ts/lib/Option' import { Tree, tree } from 'fp-ts/lib/Tree' const t = new Tree(1, [new Tree(2, []), new Tree(3, []), new Tree(4, [])]) assert.deepStrictEqual(foldM(option, tree)(t, 0, (b, a) => (a > 2 ? some(b + a) : some(b))), some(7)) ``` Added in v1.10.0 ## getFoldableComposition Returns the composition of two foldables **Signature** (function) [Source](https://github.com/gcanti/fp-ts/blob/master/src/Foldable2v.ts#L163-L173) ```ts export function getFoldableComposition<F, G>(F: Foldable2v<F>, G: Foldable2v<G>): Foldable2vComposition<F, G> { ... } ``` **Example** ```ts import { getFoldableComposition } from 'fp-ts/lib/Foldable2v' import { array } from 'fp-ts/lib/Array' import { option, some, none } from 'fp-ts/lib/Option' import { monoidString } from 'fp-ts/lib/Monoid' const F = getFoldableComposition(array, option) assert.strictEqual(F.reduce([some('a'), some('b'), some('c')], '', monoidString.concat), 'abc') assert.strictEqual(F.reduce([some('a'), none, some('c')], '', monoidString.concat), 'ac') ``` Added in v1.10.0 ## intercalate Fold a data structure, accumulating values in some `Monoid`, combining adjacent elements using the specified separator **Signature** (function) [Source](https://github.com/gcanti/fp-ts/blob/master/src/Foldable2v.ts#L355-L361) ```ts export function intercalate<M, F>(M: Monoid<M>, F: Foldable2v<F>): (sep: M, fm: HKT<F, M>) => M { ... } ``` **Example** ```ts import { intercalate } from 'fp-ts/lib/Foldable2v' import { monoidString } from 'fp-ts/lib/Monoid' import { Tree, tree } from 'fp-ts/lib/Tree' const t = new Tree('a', [new Tree('b', []), new Tree('c', []), new Tree('d', [])]) assert.strictEqual(intercalate(monoidString, tree)('|', t), 'a|b|c|d') ``` Added in v1.10.0 ## max Find the largest element of a structure, according to its `Ord` instance **Signature** (function) [Source](https://github.com/gcanti/fp-ts/blob/master/src/Foldable2v.ts#L524-L527) ```ts export function max<F, A>(O: Ord<A>, F: Foldable2v<F>): (fa: HKT<F, A>) => Option<A> { ... } ``` **Example** ```ts import { max } from 'fp-ts/lib/Foldable2v' import { some } from 'fp-ts/lib/Option' import { ordNumber } from 'fp-ts/lib/Ord' import { Tree, tree } from 'fp-ts/lib/Tree' const t = new Tree(1, [new Tree(2, []), new Tree(3, []), new Tree(4, [])]) assert.deepStrictEqual(max(ordNumber, tree)(t), some(4)) ``` Added in v1.10.0 ## ~~member~~ (deprecated) Use [elem](#elem) instead **Signature** (function) [Source](https://github.com/gcanti/fp-ts/blob/master/src/Foldable2v.ts#L627-L629) ```ts export function member<F, A>(S: Setoid<A>, F: Foldable2v<F>): (a: A, fa: HKT<F, A>) => boolean { ... } ``` Added in v1.10.0 ## min Find the smallest element of a structure, according to its `Ord` instance **Signature** (function) [Source](https://github.com/gcanti/fp-ts/blob/master/src/Foldable2v.ts#L499-L502) ```ts export function min<F, A>(O: Ord<A>, F: Foldable2v<F>): (fa: HKT<F, A>) => Option<A> { ... } ``` **Example** ```ts import { min } from 'fp-ts/lib/Foldable2v' import { some } from 'fp-ts/lib/Option' import { ordNumber } from 'fp-ts/lib/Ord' import { Tree, tree } from 'fp-ts/lib/Tree' const t = new Tree(1, [new Tree(2, []), new Tree(3, []), new Tree(4, [])]) assert.deepStrictEqual(min(ordNumber, tree)(t), some(1)) ``` Added in v1.10.0 ## oneOf Combines a collection of elements using the `Alt` operation **Signature** (function) [Source](https://github.com/gcanti/fp-ts/blob/master/src/Foldable2v.ts#L318-L320) ```ts export function oneOf<P, F>(P: Plus<P>, F: Foldable2v<F>): <A>(fga: HKT<F, HKT<P, A>>) => HKT<P, A> { ... } ``` **Example** ```ts import { array } from 'fp-ts/lib/Array' import { oneOf } from 'fp-ts/lib/Foldable2v' import { option, some } from 'fp-ts/lib/Option' assert.deepStrictEqual(oneOf(option, array)([some(2), some(1)]), some(2)) ``` Added in v1.10.0 ## product Find the product of the numeric values in a data structure **Signature** (function) [Source](https://github.com/gcanti/fp-ts/blob/master/src/Foldable2v.ts#L408-L410) ```ts export function product<F, A>(S: Semiring<A>, F: Foldable2v<F>): (fa: HKT<F, A>) => A { ... } ``` **Example** ```ts import { fieldNumber } from 'fp-ts/lib/Field' import { product } from 'fp-ts/lib/Foldable2v' import { Tree, tree } from 'fp-ts/lib/Tree' const t = new Tree(1, [new Tree(2, []), new Tree(3, []), new Tree(4, [])]) assert.strictEqual(product(fieldNumber, tree)(t), 24) ``` Added in v1.10.0 ## sequence\_ Perform all of the effects in some data structure in the order given by the `Foldable2v` instance, ignoring the final result. **Signature** (function) [Source](https://github.com/gcanti/fp-ts/blob/master/src/Foldable2v.ts#L280-L283) ```ts export function sequence_<M, F>(M: Applicative<M>, F: Foldable2v<F>): <A>(fa: HKT<F, HKT<M, A>>) => HKT<M, void> { ... } ``` **Example** ```ts import { array } from 'fp-ts/lib/Array' import { sequence_ } from 'fp-ts/lib/Foldable2v' import { io, IO } from 'fp-ts/lib/IO' let log = '' const append = (s: string) => new IO(() => (log += s)) sequence_(io, array)([append('a'), append('b'), append('c')]).run() assert.strictEqual(log, 'abc') ``` Added in v1.10.0 ## sum Find the sum of the numeric values in a data structure **Signature** (function) [Source](https://github.com/gcanti/fp-ts/blob/master/src/Foldable2v.ts#L382-L384) ```ts export function sum<F, A>(S: Semiring<A>, F: Foldable2v<F>): (fa: HKT<F, A>) => A { ... } ``` **Example** ```ts import { fieldNumber } from 'fp-ts/lib/Field' import { sum } from 'fp-ts/lib/Foldable2v' import { Tree, tree } from 'fp-ts/lib/Tree' const t = new Tree(1, [new Tree(2, []), new Tree(3, []), new Tree(4, [])]) assert.strictEqual(sum(fieldNumber, tree)(t), 10) ``` Added in v1.10.0 ## toArray Transforms a foldable into an array **Signature** (function) [Source](https://github.com/gcanti/fp-ts/blob/master/src/Foldable2v.ts#L547-L550) ```ts export function toArray<F>(F: Foldable2v<F>): <A>(fa: HKT<F, A>) => Array<A> { ... } ``` **Example** ```ts import { toArray } from 'fp-ts/lib/Foldable2v' import { Tree, tree } from 'fp-ts/lib/Tree' const t = new Tree(1, [new Tree(2, []), new Tree(3, []), new Tree(4, [])]) assert.deepStrictEqual(toArray(tree)(t), [1, 2, 3, 4]) ``` Added in v1.10.0 ## traverse\_ Traverse a data structure, performing some effects encoded by an `Applicative` functor at each value, ignoring the final result. **Signature** (function) [Source](https://github.com/gcanti/fp-ts/blob/master/src/Foldable2v.ts#L592-L600) ```ts export function traverse_<M, F>( M: Applicative<M>, F: Foldable2v<F> ): <A, B>(fa: HKT<F, A>, f: (a: A) => HKT<M, B>) => HKT<M, void> { ... } ``` **Example** ```ts import { array } from 'fp-ts/lib/Array' import { traverse_ } from 'fp-ts/lib/Foldable2v' import { io, IO } from 'fp-ts/lib/IO' let log = '' const append = (s: string) => new IO(() => (log += s)) traverse_(io, array)(['a', 'b', 'c'], append).run() assert.strictEqual(log, 'abc') ``` Added in v1.10.0
Shell
UTF-8
389
2.71875
3
[]
no_license
#!/bin/bash set timeout 60 set host 192.168.60.225 set name mlbc set password mlbc2019 spawn ssh $host -l $name expect{ "(yes/no)?"{ send "yes\n" expect "assword:" send "$password\n" } "assword:"{ send "$password\n" } } expect "#" send "uname\n" expect "mlbc" send_ser "Now you can do some operation on this terminal\n" Interact
Python
UTF-8
2,324
2.5625
3
[]
no_license
import json from flask_restplus import Namespace, Resource, fields # import mongoengine.fields as fields from flask import request, jsonify from mongoengine import DoesNotExist, ValidationError from controller.campaign_controller import CampaignController from models.campaign import Campaign api = Namespace('campaign', description='Campaign namespace') def get_controller(): controller = CampaignController(model=Campaign, request=request) return controller campaign_model = api.model('Campaign', { 'name': fields.String(required=True, description="Campaign's name"), 'gameMaster': fields.String(required=True), 'players': fields.List(fields.String), 'characters': fields.List(fields.String), 'rules': fields.List(fields.String), }) @api.route('/') class CampaignList(Resource): @api.doc("Campaign List") def get(self): controller = get_controller() query = controller.list_elements() return jsonify(query) @api.doc("Campaign Creation") @api.expect(campaign_model) def post(self): controller = get_controller() args = controller.new() return {'id': args} @api.route('/<string:id>') @api.response(200, 'Success') @api.response(400, 'Item not found') @api.param('id', 'Item identifier') class CampaignDetail(Resource): param = "An integer that represents the campaign's id" @api.doc("Get information on a specific campaign", params={'id': param}) @api.response(400, 'Campaign not found') def get(self, id): controller = get_controller() try: campaign = controller.get_element_detail(id) except (DoesNotExist, ValidationError): api.abort(400, 'Campaign with id {} does not exist') return json.loads(campaign) @api.doc("Update an campaign", params={'id': param}) @api.expect(campaign_model) def put(self, id): controller = get_controller() try: new_campaign = controller.edit(id) except(DoesNotExist, ValidationError): api.abort(400, "Campaign with id {} does not exist") return new_campaign @api.doc("Delete a campaign", params={'id': param}) def delete(self, id): controller = get_controller() deleted = controller.delete(id) return deleted
Python
UTF-8
1,112
2.890625
3
[ "MIT" ]
permissive
import altair as alt import pandas as pd def history_to_dataframe(history, key): if isinstance(history, dict): dfs = [] for name, history_ in history.items(): df = history_to_dataframe(history_, key) df["name"] = name dfs.append(df) return pd.concat(dfs) if isinstance(key, list): df = None for key_ in key: df_ = history_to_dataframe(history, key_) df = df_ if df is None else df.merge(df_) return df dfs = [] for key_ in [key, "val_" + key]: df = pd.DataFrame({"epoch": history.epoch, key: history.history[key_]}) if key_.startswith("val_"): df["type"] = "validation" else: df["type"] = "train" dfs.append(df) return pd.concat(dfs) def plot_history(history, key, **kwargs): df = history_to_dataframe(history, key) chart = alt.Chart(df).encode(x="epoch", y=key, **kwargs) return chart.mark_line().encode(detail="type") + chart.mark_point().encode( shape="type" ).properties(width=260, height=200)
Java
UTF-8
2,548
2.5
2
[]
no_license
package com.tmw.tracking.service.impl; import com.tmw.tracking.entity.TrackingSite; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.net.SocketTimeoutException; import java.text.MessageFormat; import java.util.concurrent.Callable; /** * Created by pzhelnov on 11/25/2016. */ public class TrackThread implements Callable<String> { private final TrackingSite trackingSite; private final String container; private final static Logger logger = LoggerFactory.getLogger(TrackingServiceImpl.class); public TrackThread(TrackingSite trackingSite, String container) { this.trackingSite = trackingSite; this.container = container; } @Override public String call() throws Exception { String url = MessageFormat.format(trackingSite.getGetUrl(), container); logger.info("Calling url "+ url); Document document = null; int count = 0; do { try { document = Jsoup. connect(url). //cookies(cookies). userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.120 Safari/535.2"). timeout(3000). get(); } catch (SocketTimeoutException exception) { logger.warn("Time out " + trackingSite.getGetUrl()); } } while (count++ <3); if (document == null) { return null; } String result = analyze(document.html(), trackingSite); if (!result.isEmpty()) { logger.info("Got result!" + trackingSite.getGetUrl()); return result; } else { return null; } } private String analyze(String response, TrackingSite trackingSite) { //failure first if (response == null || response.isEmpty()) { return ""; } int failureIndex = response.indexOf(trackingSite.getFailureElement()); if (failureIndex>0) { return ""; } int firstIndex = response.indexOf(trackingSite.getSuccessElement()); if (firstIndex<0) { return ""; } String sub1 = response.substring(firstIndex); int encloseIndex = sub1.indexOf(trackingSite.getEnclose()); String sub2 = encloseIndex>0?sub1.substring(0, encloseIndex):sub1; return Jsoup.parse(sub2).text(); } }
Python
UTF-8
998
3.15625
3
[ "MIT" ]
permissive
import unittest import os from dfs_connected_cell_in_a_grid import maxRegion class TestMaxRegion(unittest.TestCase): def parse_test_data_file(self, file): n = int(file.readline()) m = int(file.readline()) grid = [] for _ in range(n): grid.append(list(map(int, file.readline().rstrip().split()))) expected_result = int(file.readline()) return grid, expected_result def test_passes_on_sample_test_cases(self): test_data_filenames = ['sample_test_case_{}.txt'.format(i) for i in range(3)] for test_data_filename in test_data_filenames: test_data_path = os.path.join(os.path.abspath('.'), test_data_filename) with open(test_data_path) as f: grid, expected_result = self.parse_test_data_file(f) res = maxRegion(grid) self.assertEqual(expected_result, res, 'Wrong Answer. Expected: {}, Actual: {}'.format(expected_result, res))
Markdown
UTF-8
1,250
2.59375
3
[]
no_license
--- layout: post title: Technical Thanksgiving tags: [technology, musings] last_updated: 2011-12-13 --- I'm thankful for standards and software that supports them. I can now charge my wife's phone and my phone using the same micro-USB connector. My machine can talk to a wide variety of printers without me worrying about getting the right drivers and fiddling with some file in the `etc` subdirectory. I haven't had to worry about IRQ conflicts in ages. I'm thankful for ubiquitous networking and the services it supports. I grumble about email sometimes, and sometimes I think better when disconnected. But it's really handy to have my email and my calendar available whenever and wherever, and to be able to Google things. I'm thankful for cheap GPS. My cell phone has a better sense of direction than I do. How cool is that? I'm thankful for improvements in battery technology (though we still have a ways to go). I'm thankful for high level programming languages. Since I started programming, it has gotten way easier to put together interesting software prototypes for ideas, and to avoid constantly writing boilerplate code. I'm thankful that the week after Thanksgiving is the last week of instruction for the semester!
Markdown
UTF-8
16,922
3.0625
3
[ "Apache-2.0" ]
permissive
#Advanced usage ## Getting Tipser ids <aside class="notice"> To run Tipser Elements components you will need to pass <code>productId</code> or <code>collectionId</code>. To get <code>productId</code>, log in to <a href="https://app.tipser.com/" target="_blank">app.tipser.com</a> using your publisher's account, find a product in "Insert Products" section, click on the "<>" sign and copy it's <code>productId</code>. To curate a collection click "+" sign on a product tile and type the name of the collection. Then click "add". Your product is added to the collection. When all the products are added to the collection, click "<" on the right side of the site and then "<>" to copy the the <code>collectionId</code>. </aside> ## Publisher data In order to associate a piece of data owned by the publisher with an order item in Tipser, you can use a concept called `posData`. A `posData` is an arbitrary string that can be used to store additional information (e.g. session id, user id in your system, etc) attached to order in Tipser's database. After the transaction is finalized, the string passed as `posData` will be available back in the response from the <a href="https://developers.tipser.com/rest-api/purchase-data" target="_blank">Commissions API</a> that can be consumed by your backend code (e.g. reporting systems). <aside class="notice">Because <code>posData</code> is treated as a string in the Tipser system, then if you need to store a structured data (a common use case), please call <code>JSON.stringify()</code> function on a JS object before passing it to Tipser (see: the examples below) and parse it back to JS object when receiving it back.</aside> There are three ways to enable `posData`: Option 1: As a global configuration setting that is passed to Elements/SDK initialization (good for static data, like the release number): ```javascript const tipserConfig = { posData: "release_2.1.5" }; ``` Option 2: After Elements/Script initialization with `updateConfig(posData: string)` function (useful for the data that is not yet available at the time of initialization): in Tipser Script: ```javascript const someData = JSON.stringify({sessionId: "5fa01be88b51", userId: "5fa01bfd3be2"}); tipserScript.updateConfig({posData: someData}); ``` in Elements: Just update the value passed to the config prop of TipserElementsProvider in the next render cycle: ```javascript const someData = JSON.stringify({sessionId: "5fa01be88b51", userId: "5fa01bfd3be2"}); const elementsConfigWithPosData = {...baseElementsConfig, posData: someData}; return <TipserElementsProvider config={elementsConfigWithPosData}> ... </TipserElementsProvider> ``` This will apply for the next and all the subsequent products added to cart. <aside class="notice">The timing of calling <code>setPosData</code> is relevant. The <code>posData</code> is being sent in the Tipser backend with the add to cart API request. This means that to have any effect, <code>setPosData</code> needs to be called <strong>before</strong> the product is added to cart (either from the API or by user's action).</aside> Option 3: In the second parameter of `addToCart` or `openDirectToCheckoutDialog` function (convenient if each product added to cart needs to have a different value of `posData`): <aside class="warning">Please note, that Tipser SDK is deprecated</aside> ```javascript const addToCartOptions = { posData: JSON.stringify({sessionId: "5fa01be88b51", userId: "5fa01bfd3be2"}) }; tipserSdk.addToCart(productId, addToCartOptions); ``` <aside class="warning">Warning: for performance reasons, the number of characters in <code>posData</code> is limited to 4000. Longer strings will be truncated down to 4000 characters.</aside> ## Checkout submit functions You can access the checkout context and create custom functions for submitting delivery and billing address forms as well as Stripe payment details. ### in Tipser Elements: If you're using React in your project, you can apply `useCheckoutContext` hook: ```javascript const CustomSubmitButton = () => { const checkoutContext = useCheckoutContext(); const handleClick = useCallback(() => { // for delivery addres submition use: checkoutContext.addresses.deliveryAddressForm.submit() // for billing address submition use: checkoutContext.addresses.billingAddressForm.submit(); // for payment submition use: checkoutContext.payment.paymentForm.submit(); }, [checkoutContext]); return <button onClick={handleClick}>Submit delivery address</button> } ``` ### in Tipser Script: Even if you don't use React in your project, we allow you to access the checkout context and create custom functions for submitting delivery and billing address forms as well as Stripe payment details. To access the context, create an Event Listener attached to your checkout wrapper (the element with `data-tipser-modular-checkout` attribute): ```javascript const modularCheckoutDiv = document.querySelector('#modular_checkout_root'); let getCheckoutContext = null; modularCheckoutDiv.addEventListener('checkout-context-ready', (evt) => { getCheckoutContext = evt.detail.getCheckoutContext; }); ``` Now create your custom Submit button, eg: ```html <button id="submit-button" onclick="customSubmit()"></button> ``` and define your submit delivery address function: ```javascript const customSubmit = () => { const checkoutContext = getCheckoutContext(); // for delivery addres submition use: checkoutContext.addresses.deliveryAddressForm.submit(); // for billing address submition use: checkoutContext.addresses.billingAddressForm.submit(); // for payment submition use: checkoutContext.payment.paymentForm.submit(); }; ``` ## Accessing Tipser SDK <aside class="warning">Please note, that Tipser SDK is deprecated. Until Q2 2021 we plan to stop bug fixing and in Q3 2021 we'll stop supporting it altogether. The following documentation is for users who are currently in transition to Tipser Elements. If you need help with choosing the right Tipser solution to fit your technology stack, please contact us at <a href="mailto:tech@tipser.com">tech@tipser.com</a></aside> Low level operations, like programatically opening Tipser dialogs can be done by using the underlying [Tipser SDK](#tipser-sdk) instance, which is a part of the Tipser Elements library. __If you use Tipser Elements:__ ```javascript const elements = tipser.elements(posId, config); elements.sdkInstance.openProductDialog(productId); ``` __If you use Tipser React Elements:__ 1. Create a custom React component and mount it anywhere under `TipserElementsProvider` in React elements hierarchy. 2. Inside that component you can use tipserSdk instance from the context `TipserContext`. This how it can be done with [React Hooks](https://reactjs.org/docs/hooks-intro.html): ```javascript import { useTipserSdk } from `@tipser/tipser-elements`; const DialogOpener = () => { const sdk = useTipserSdk(); useEffect(() => { sdk.openProductDialog(productId); }, []); } ``` This will only work if the `DialogOpener` component is under `TipserElementsProvider` in React components hierarchy: ```html <TipserElementsProvider> <!-- Any number of other components --> <DialogOpener /> </TipserElementsProvider> ``` *** ## Buyable banners [![](buyable-banners.gif)](/images/buyable-banners.gif) Tipser dialogs can be opened by the banners on your site. That way you can use your banners for E-commerce. To connect your banner to Tipser, you need to do the following two steps: 1. follow the instructions from [Initializing Tipser Elements](#initializing-tipser-script) 2. Add the line of javascript posted below to you banner. It should be invoked when the banner is clicked. __To display product dialog:__ ```javascript window.top.postMessage({command: 'tipser.api.displayProduct', productId: tipserProductId}, '*') ``` __To open the checkout view for a product directly:__ ```javascript window.top.postMessage({command: 'tipser.api.directToCheckout', productId: tipserProductId}, '*') ``` Check [this](#getting-tipser-ids) section to learn how to obtain the `tipserProductId`. <a href="https://bbc-bootstrap.netlify.com/" target="_blank">Live demo</a> <aside class="notice"> In case your banner is not nested in an iframe but is simply a part of your site, POST messages should be sent to `window object` instead of `window.top`, e.g: </aside> ```javascript window.postMessage({command: 'tipser.api.displayProduct', productId: '5b59bfa4ca60310e30c9ac37'}, '*') ``` *** ## Server side rendering To render Tipser Elements components on the server side, you can choose between two methods: 1. Basic, in which you need to provide the `id`s of the Tipser Elements components that are used on the website. 2. Smart, where you don't need to know the `id`s, but there would be two subsequent renders. In the first one, 'dry run', we collect information about components used on the website and the proper rendering, that uses the previously collected data. Server-side rendering takes place in several steps: - building a state containing the data needed for rendering - passing the state to the `SsrTipserElementsProvider` - rendering the application - sending the same state to the browser and passing it back to the `SsrTipserElementsProvider` on the client side. ### Basic method In the basic method, you should use the `StateBuilder` class to build the state. Start with creating its instances (which can be global): ```typescript import { StateBuilder } from '@tipser/tipser-elements'; const stateBuilder = new StateBuilder(POS_ID); ``` Then, while handling a specific request, use the `stateBuilder.buildState` method, passing an object containing information about which elements are placed on the website, i.e. what products (PRODUCT_IDS), collections (COLLECTION_IDS) and whether there is the shop component (IS_SHOP_ON_PAGE). ```typescript stateBuilder.buildState({ productIds: PRODUCT_IDS, collectionIds: COLLECTION_IDS, shouldFetchStore: IS_SHOP_ON_PAGE, }) ``` This method returns a promise in which the ready state will be available, which should then be passed to `SsrTipserElementsProvider`: ```typescript stateBuilder.buildState({ productIds: dataToFetch.productIds, collectionIds: dataToFetch.collectionIds, shouldFetchStore: dataToFetch.shouldFetchStore }).then((initialState) => { const markup = renderToString( <TipserElementsProvider posId={POS_ID}> <SsrTipserElementsProvider initialState={initialState}> <App/> </SsrTipserElementsProvider> </TipserElementsProvider> ); ... }); ``` The `initialState` should then be transferred to the browser. For this purpose, it can be assigned to the global window object and placed in the returned html document: ```html <script>window.TIPSER_STATE = ${JSON.stringify(initialState)}</script> ``` On the client side, use `window.TIPSER_STATE` as the `initialState` of `SsrTipserElementsProvider`: ```typescript <TipserElementsProvider posId={POS_ID}> <SsrTipserElementsProvider initialState={window.TIPSER_STATE}> <App/> </SsrTipserElementsProvider> </TipserElementsProvider> ``` That's all! The complete example is available [here](https://github.com/Tipser/tipser-elements-ssr-bootstrap). ### Smart method In the smart version, the `ComponentsStateSsrManager` class should be used to build the state. For this purpose, you should create an instance of this class, which cannot be global, i.e. a new instance should be created for each request: ```typescript const componentsStateSsrManager = new ComponentsStateSsrManager(POS_ID); ``` Then perform the first rendering that will collect information about the components on the page: ```typescript const componentsStateSsrManager = new ComponentsStateSsrManager(POS_ID, 'prod') const toRender = ( <TipserElementsProvider posId={POS_ID}> <SsrTipserElementsProvider componentsStateManager={componentsStateSsrManager}> <App/> </SsrTipserElementsProvider> </TipserElementsProvider> ); //first render renderToString(toRender); ``` Next, use the `buildState` method available on the components instance of `StateSsrManager`, which returns a promise: ```typescript const componentsStateSsrManager = new ComponentsStateSsrManager(POS_ID) const toRender = ( <TipserElementsProvider posId={POS_ID}> <SsrTipserElementsProvider componentsStateManager={componentsStateSsrManager}> <App/> </SsrTipserElementsProvider> </TipserElementsProvider> ); //first render renderToString(toRender); componentsStateSsrManager.buildState().then(() => { //second render const markup = renderToString(toRender); ... }); ``` In this case, you no longer need to manually pass the state to the `SsrTipserElementsProvider`, it is done automatically. The last step is to transfer the state to the browser in a similar way as it was done in the basic version, but this time the state should be extracted from `componentsStateSsrManager` using the `getState` method: ```typescript <script>window.TIPSER_STATE = ${JSON.stringify(componentsStateSsrManager.getState())}</script> ``` The state should be passed to the `SsrTipserElementsProvider` on the browser side: ```typescript <TipserElementsProvider posId={POS_ID}> <SsrTipserElementsProvider initialState={window.TIPSER_STATE}> <App/> </SsrTipserElementsProvider> </TipserElementsProvider>, ``` ## Native apps Tipser Elements is a web-based library and currently we don't provide a native version for Android or iOS (let us know if you'd like us to build it for you!) However it is possible to embed Elements in a native app if you are using WebViews. We recommend you to follow one of the patterns described below. ### Pattern 1: Full web integration In case your articles are managed by a Web CMS and are displayed in WebView you can simply install and use Tipser Elements in your web articles. Just follow the instructions from [Tipser Elements](#tipser-elements) or [Tipser Elements React](#tipser-react-elements) sections, depending on your technology of choice. The only customization that we recommend is using `disableDialog` option, as described below. *Replacing dialogs with redirects* By default, when a product tile is clicked, it opens a full screen product dialog. It may not be desired behavior in your mobile app. Set the configuration option: `disableDialog` to `true` to replace the dialog with a _redirect_ to the product page. That way pressing the back button will bring the user back to your article. ### Pattern 2: API integration If you want to deliver native experience to your users, you can build your custom native e-commerce components (product tiles, shopping cart icon, etc) and use [Tipser Rest API](https://developers.tipser.com/rest-api) to populate them. With this pattern, only the checkout part needs to be displayed in a WebView. Below is a basic example of a native view with a single product that opens Tipser checkout view when clicked. Step 1: Rendering a product on your page 1. Use the Tipser product API to get the product that you want to sell, e.g: `https://t3-stage-api.tipser.com/v3/products/5d932be284da04000116ae3c?pos=59e86b79b8f3f60a94ecd26a` (please, replace the example product id with the desired product and the pos parameter with your own POS id) 2. Render your custom product component based on the response data <aside class="notice"> Here we describe displaying a single product. If you'd be interested to render multiple products, it's best to use the collections API. </aside> Step2: Opening the checkout view 1. Create a WebView screen in your app project 2. When your product is clicked, open the WebView with the URL like: `https://www.tipser.com/direct-checkout?productId=productId&posId=59e86b79b8f3f60a94ecd26a` (again, please make sure to replace the `posId` with your POS id and `productId` with the Tipser id of the product that was clicked) <aside class="notice"> If your use case is not covered in this section, please discuss it with your Tipser integration support person. </aside> ## Merchant signup on your site It is possible to let merchants sign-up to Tipser directly from your site. To make it possible, you need to have Tipser Elements installed on your page and you need to prepare a dedicated subpage for merchants, with a "Sign up" button that invokes the following code: ```javascript const elements = tipser.elements(posId, config); elements.sdkInstance.openDialog(`https://merchsignup.netlify.app/#/start/${posId}`); ```
Java
UTF-8
1,612
2.46875
2
[]
no_license
package com.unqualsevol.moviesproject1.adapters; import android.content.Context; import android.database.Cursor; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.unqualsevol.moviesproject1.R; import com.unqualsevol.moviesproject1.fragments.MoviesGridFragment; import com.unqualsevol.moviesproject1.utils.MoviesUtils; import com.unqualsevol.moviesproject1.viewholders.PosterViewHolder; public class FavoritesAdapter extends RecyclerView.Adapter<PosterViewHolder> { private Cursor mCursor; @Override public PosterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { Context context = parent.getContext(); View view = LayoutInflater.from(context).inflate(R.layout.movie_grid_item, parent, false); return new PosterViewHolder(view); } @Override public void onBindViewHolder(PosterViewHolder holder, int position) { mCursor.moveToPosition(position); int movieId = mCursor.getInt(MoviesGridFragment.INDEX_MOVIE_ID); byte[] posterInBytes = mCursor.getBlob(MoviesGridFragment.INDEX_POSTER_IMAGE); float voteAverage = mCursor.getFloat(MoviesGridFragment.INDEX_VOTE_AVERAGE) / 2; holder.updateViewHolder(movieId, MoviesUtils.getImage(posterInBytes), voteAverage); } @Override public int getItemCount() { if (null == mCursor) return 0; return mCursor.getCount(); } public void swapCursor(Cursor newCursor) { mCursor = newCursor; notifyDataSetChanged(); } }
Swift
UTF-8
1,543
2.75
3
[ "MIT" ]
permissive
import XCTest import AttributedString_swift class Tests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } func testForegroundColor() { let color = UIColor.red let attributedText = NSAttributedString( string: "Hello World", attrs: [.foregroundColor(color)]) let attributes = attributedText.attributes(at: 0, effectiveRange:nil) XCTAssertEqual(attributes[.foregroundColor] as! UIColor, color) } func testBackgroundColor() { let color = UIColor.red let attributedText = NSAttributedString( string: "Hello World", attrs: [.backgroundColor(color)]) let attributes = attributedText.attributes(at: 0, effectiveRange:nil) XCTAssertEqual(attributes[.backgroundColor] as! UIColor, color) } func testFont() { let font = UIFont.systemFont(ofSize: 100) let attributedText = NSAttributedString( string: "Hello World", attrs: [.font(font)]) let attributes = attributedText.attributes(at: 0, effectiveRange:nil) XCTAssertEqual(attributes[.font] as! UIFont, font) } func testUnderlineStyle() { let style = NSUnderlineStyle.styleSingle let attributedText = NSAttributedString( string: "Hello World", attrs: [.underlineStyle(style)]) let attributes = attributedText.attributes(at: 0, effectiveRange:nil) XCTAssertEqual(NSUnderlineStyle(rawValue: attributes[.underlineStyle] as! Int), style) } }
C#
UTF-8
9,363
2.640625
3
[ "LicenseRef-scancode-nysl-0.9982" ]
permissive
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SimpleFTP { sealed class ReplyCode { /// <summary>再開のマーカー応答。テキストは厳密で特有の実装は許されない。フォーマットはMARK yyyy = mmmmでyyyyはユーザプロセスデータストリームマーカ、mmmmはサーバに対応するマーカ</summary> public static readonly ReplyCode _110 = new ReplyCode(110, "Restart marker reply."); /// <summary>サービスはnnn分後に準備できる。</summary> public static readonly ReplyCode _120 = new ReplyCode(120, "Service ready in nnn minutes."); /// <summary>データコネクションは既に確立されている。転送をはじめる。</summary> public static readonly ReplyCode _125 = new ReplyCode(125, "Data connection already open; transfer starting."); /// <summary>ファイルステータスは問題ない。データコネクションを確立する</summary> public static readonly ReplyCode _150 = new ReplyCode(150, "File status okay; about to open data connection."); /// <summary>コマンドOK</summary> public static readonly ReplyCode _200 = new ReplyCode(200, "Command okay."); /// <summary>コマンドは実装されていない。このサイトでは不必要である。</summary> public static readonly ReplyCode _202 = new ReplyCode(202, "Command not implemented, superfluous at this site."); /// <summary>システムのステータスまたは、システムヘルプの返答</summary> public static readonly ReplyCode _211 = new ReplyCode(211, "System status, or system help reply."); /// <summary>ディレクトリのステータス</summary> public static readonly ReplyCode _212 = new ReplyCode(212, "Directory status."); /// <summary>ファイルのステータス</summary> public static readonly ReplyCode _213 = new ReplyCode(213, "File status."); /// <summary>ヘルプメッセージ。サーバや特有の非標準コマンドの使用法。この返答は人間のユーザにのみ有用である。</summary> public static readonly ReplyCode _214 = new ReplyCode(214, "Help message."); /// <summary>NAME システムタイプ。NAMEにはAssigned Numbersにリストされている公式のシステム名が入る。</summary> public static readonly ReplyCode _215 = new ReplyCode(215, "NAME system type."); /// <summary>新しいユーザのためにサービスが準備できた。</summary> public static readonly ReplyCode _220 = new ReplyCode(220, "Service ready for new user."); /// <summary>コントロールコネクションのサービスを切断する。</summary> public static readonly ReplyCode _221 = new ReplyCode(221, "Service closing control connection."); /// <summary>データコネクションを確立した。現在転送は行われていない。</summary> public static readonly ReplyCode _225 = new ReplyCode(225, "Data connection open; no transfer in progress."); /// <summary>データコネクションを切断する。リクエストしたファイルへのアクションは成功した(例としてファイル転送時やファイル転送中止時)</summary> public static readonly ReplyCode _226 = new ReplyCode(226, "Closing data connection."); /// <summary>パッシブモードに入る (host1,host2,host3,host4,port1,port2)。</summary> public static readonly ReplyCode _227 = new ReplyCode(227, "Entering Passive Mode (h1,h2,h3,h4,p1,p2)."); /// <summary>ユーザのログインに成功した。</summary> public static readonly ReplyCode _230 = new ReplyCode(230, "User logged in, proceed."); /// <summary>リクエストされたファイルへのアクションは問題なく完了した。</summary> public static readonly ReplyCode _250 = new ReplyCode(250, "Requested file action okay, completed."); /// <summary>PATHNAMEを作成した</summary> public static readonly ReplyCode _257 = new ReplyCode(257, "PATHNAME created."); /// <summary>ユーザーネームは正しい。パスワードが必要である。</summary> public static readonly ReplyCode _331 = new ReplyCode(331, "User name okay, need password."); /// <summary>ログインアカウントが必要である。</summary> public static readonly ReplyCode _332 = new ReplyCode(332, "Need account for login."); /// <summary>リクエストされたファイルへのアクションは、更に詳細な情報が必要である。</summary> public static readonly ReplyCode _350 = new ReplyCode(350, "Requested file action pending further information."); /// <summary>サービスは利用できない。コントロールコネクションを切断する。サービスがシャットダウンすることを知っている場合、いかなるコマンドに対しても返す。</summary> public static readonly ReplyCode _421 = new ReplyCode(421, "Service not available, closing control connection."); /// <summary>データコネクションを確立できない。</summary> public static readonly ReplyCode _425 = new ReplyCode(425, "Can't open data connection."); /// <summary>コネクションは切断された。転送は中止された。</summary> public static readonly ReplyCode _426 = new ReplyCode(426, "Connection closed; transfer aborted."); /// <summary>リクエストされたファイルのアクションは実行できない。</summary> public static readonly ReplyCode _450 = new ReplyCode(450, "Requested file action not taken."); /// <summary>リクエストされたアクションは中止された。実行中ローカルエラーが発生した。.</summary> public static readonly ReplyCode _451 = new ReplyCode(451, "Requested action aborted: local error in processing."); /// <summary>リクエストされたアクションは実行できない。ストレージの容量が不足している。ファイルが利用できない(ビジー状態)。</summary> public static readonly ReplyCode _452 = new ReplyCode(452, "Requested action not taken."); /// <summary>文法エラー。コマンドが解釈できない。このエラーはコマンドが長すぎる場合も含まれる。</summary> public static readonly ReplyCode _500 = new ReplyCode(500, "Syntax error, command unrecognized."); /// <summary>パラメータや引数において文法エラーがある。</summary> public static readonly ReplyCode _501 = new ReplyCode(501, "Syntax error in parameters or arguments."); /// <summary>コマンドは実装されていない。</summary> public static readonly ReplyCode _502 = new ReplyCode(502, "Command not implemented."); /// <summary>コマンドの順序が間違っている。</summary> public static readonly ReplyCode _503 = new ReplyCode(503, "Bad sequence of commands."); /// <summary>そのパラメータに対してコマンドは実装されていない。</summary> public static readonly ReplyCode _504 = new ReplyCode(504, "Command not implemented for that parameter."); /// <summary>ログインできない。</summary> public static readonly ReplyCode _530 = new ReplyCode(530, "Not logged in."); /// <summary>ファイルの格納にはアカウントが必要である。</summary> public static readonly ReplyCode _532 = new ReplyCode(532, "Need account for storing files."); /// <summary>リクエストされたアクションは実行できない。ファイルは利用できない(見つからない、アクセスできない)</summary> public static readonly ReplyCode _550 = new ReplyCode(550, "Requested action not taken."); /// <summary>リクエストされたアクションは中止された。ページタイプが不明である。</summary> public static readonly ReplyCode _551 = new ReplyCode(551, "Requested action aborted: page type unknown."); /// <summary>リクエストされたアクションは中止された。(現在のディレクトリやデータセットに)割り当てられたストレージを超過した。</summary> public static readonly ReplyCode _552 = new ReplyCode(552, "Requested file action aborted."); /// <summary>リクエストされたアクションは実行できない。ファイル名が受け付けられない。</summary> public static readonly ReplyCode _553 = new ReplyCode(553, "Requested action not taken."); // public int Code { get; private set; } public string Message { get; private set; } public ReplyCode(int code, string message) { this.Code = code; this.Message = message; } public override string ToString() { return String.Format("{0} {1}", this.Code, this.Message); } } }
PHP
UTF-8
1,117
2.984375
3
[]
no_license
<?php class Timezone { var $id; var $ht; function Timezone($id){ $this->id=0; return $this->load($id); } function load($id=0) { if(!$id && !($id=$this->getId())) return false; $sql='SELECT * FROM '.TIMEZONE_TABLE.' WHERE id='.db_input($id); if(!($res=db_query($sql)) || !db_num_rows($res)) return false; $this->ht=db_fetch_array($res); $this->id=$this->ht['id']; return $this->id; } function reload() { return $this->load(); } function getId() { return $this->id; } function getOffset() { return $this->ht['offset']; } function getName() { return $this->info['timezone']; } function getDesc() { return $this->getName(); } /* static functions */ function lookup($id) { return ($id && is_numeric($id) && ($tz= new Timezone($id)) && $tz->getId()==$id)?$tz:null; } function getOffsetById($id) { return ($tz=Timezone::lookup($id))?$tz->getOffset():0; } } ?>
PHP
UTF-8
470
2.703125
3
[]
no_license
<?php namespace Neko\Facade; use Neko\Session\SessionManager; class Session { protected static $Instance; public static function __callStatic($method, $args) { if (!static::$Instance) { static::$Instance = new SessionManager(null); } return call_user_func_array(array(static::$Instance, $method), $args); } public static function setInstance($Instance) { static::$Instance = $Instance; } } ?>
Java
UTF-8
3,857
2
2
[]
no_license
package org.chromium.media.mojom; import org.chromium.mojo.bindings.DeserializationException; import org.chromium.mojo.bindings.Interface$AbstractProxy; import org.chromium.mojo.bindings.Interface$Manager; import org.chromium.mojo.bindings.Interface; import org.chromium.mojo.bindings.InterfaceControlMessagesHelper; import org.chromium.mojo.bindings.Message; import org.chromium.mojo.bindings.MessageHeader; import org.chromium.mojo.bindings.MessageReceiver; import org.chromium.mojo.bindings.MessageReceiverWithResponder; import org.chromium.mojo.bindings.ServiceMessage; import org.chromium.mojo.system.Core; class FrameResourceReleaser_Internal { final class org.chromium.media.mojom.FrameResourceReleaser_Internal$1 extends Manager { org.chromium.media.mojom.FrameResourceReleaser_Internal$1() { super(); } public FrameResourceReleaser[] buildArray(int arg1) { return new FrameResourceReleaser[arg1]; } public Interface[] buildArray(int arg1) { return this.buildArray(arg1); } public Proxy buildProxy(Core arg2, MessageReceiverWithResponder arg3) { return new Proxy(arg2, arg3); } public org.chromium.mojo.bindings.Interface$Proxy buildProxy(Core arg1, MessageReceiverWithResponder arg2) { return this.buildProxy(arg1, arg2); } public Stub buildStub(Core arg2, FrameResourceReleaser arg3) { return new Stub(arg2, arg3); } public org.chromium.mojo.bindings.Interface$Stub buildStub(Core arg1, Interface arg2) { return this.buildStub(arg1, ((FrameResourceReleaser)arg2)); } public String getName() { return "media::mojom::FrameResourceReleaser"; } public int getVersion() { return 0; } } final class Proxy extends AbstractProxy implements org.chromium.media.mojom.FrameResourceReleaser$Proxy { Proxy(Core arg1, MessageReceiverWithResponder arg2) { super(arg1, arg2); } } final class Stub extends org.chromium.mojo.bindings.Interface$Stub { Stub(Core arg1, FrameResourceReleaser arg2) { super(arg1, ((Interface)arg2)); } public boolean accept(Message arg4) { try { ServiceMessage v4_1 = arg4.asServiceMessage(); MessageHeader v1 = v4_1.getHeader(); if(!v1.validateHeader(0)) { return 0; } if(v1.getType() != -2) { return 0; } return InterfaceControlMessagesHelper.handleRunOrClosePipe(FrameResourceReleaser_Internal.MANAGER, v4_1); } catch(DeserializationException v4) { System.err.println(v4.toString()); return 0; } } public boolean acceptWithResponder(Message arg4, MessageReceiver arg5) { try { ServiceMessage v4_1 = arg4.asServiceMessage(); MessageHeader v1 = v4_1.getHeader(); if(!v1.validateHeader(1)) { return 0; } if(v1.getType() != -1) { return 0; } return InterfaceControlMessagesHelper.handleRun(this.getCore(), FrameResourceReleaser_Internal.MANAGER, v4_1, arg5); } catch(DeserializationException v4) { System.err.println(v4.toString()); return 0; } } } public static final Manager MANAGER; static { FrameResourceReleaser_Internal.MANAGER = new org.chromium.media.mojom.FrameResourceReleaser_Internal$1(); } FrameResourceReleaser_Internal() { super(); } }
Rust
UTF-8
11,687
3.09375
3
[]
no_license
use scrap::{Capturer, Display}; use std::io::ErrorKind; use std::is_x86_feature_detected; use log::debug; mod converters; use converters::{ avx2_bgra_to_rgba, avx2_cmp_and_convert, avx2_cmp, avx2_convert_in_place }; #[derive(PartialEq, Eq, Debug)] enum RegionType { Unknown = 0, Similarity = 1, Difference = 2, } pub struct Bigtile { pub x: u16, pub y: u16, pub w: u16, pub h: u16, pub tile: Vec::<u8>, } impl Bigtile { // TODO this will be shit slow. pub fn from_image(image: &Vec<u8>, bpr: i32, startx: i32, starty: i32, endx: i32, endy: i32) -> Self { let x = (startx/4) as u16; // count in pixels, not bytes, for front end. let y = starty as u16; let w = ((endx - startx) / 4) as u16; let h = (endy - starty) as u16; let mut tile = Vec::<u8>::with_capacity( ((endx-startx) * (endy-starty)) as usize ); let now = std::time::Instant::now(); for j in starty..endy { let mut v = Vec::with_capacity( (endx-startx) as usize ); unsafe{ v.set_len( (endx-startx) as usize);} v.clone_from_slice( &image[ ((j*bpr + startx) as usize)..((j*bpr + endx) as usize)]); tile.append(&mut v); } debug!("tile copy took {} ms", now.elapsed().as_millis()); Bigtile{x, y, w, h, tile} } } pub struct Snapper { capturer: Capturer, pub width: usize, pub height: usize, pub last: Vec<u8>, // a copy of the previous screen buffer for incremental modes. } unsafe impl Send for Snapper {} unsafe impl Sync for Snapper {} impl Drop for Snapper { fn drop(&mut self) { } } impl Snapper { pub fn new() -> Self { if ! is_x86_feature_detected!("avx2") { panic!("This library depends upon the AVX2 extensions, which this processor does not support"); } let display = Display::primary().expect("Couldn't get a handle for the primary display"); let capturer = Capturer::new(display).expect("Couldn't instatiate capturer for the primary display"); let width = capturer.width(); let height = capturer.height(); Snapper{ capturer, width, height, last: Vec::with_capacity(0), //don't attempt to presize because stride != width. } } fn get_frame(&mut self) -> Vec<u8> { loop { match self.capturer.frame() { Ok(buf) => return buf.to_vec(), Err(e) => match e.kind() { ErrorKind::WouldBlock => continue, _ => panic!( "Could not capture screen: {:?}", e), }, }; } } pub fn snap_bigtiles(&mut self) -> Vec<Bigtile> { let mut tiles = Vec::<Bigtile>::new(); let mut pixels = self.get_frame(); let bytes_per_row = pixels.len() / self.height; if self.last.len() != pixels.len() { panic!("Called for a hextile update but the previous framebuffer length {} does not match current {}", self.last.len(), pixels.len()); } // convert the pixels to RGBA before comparing against the previous frame (which is RGBA) unsafe { for i in (0 .. pixels.len() ).step_by(32) { avx2_convert_in_place(i as isize, &mut pixels); } } let now = std::time::Instant::now(); // start splitting the regions horizontally //tiles.append( &mut self.split_h(&pixels, bytes_per_row as i32, 0, 0, bytes_per_row as i32, self.height as i32) ); tiles.append( &mut self.son_of_krunch(&pixels, bytes_per_row as i32, 0, 0, bytes_per_row as i32, self.height as i32) ); self.last = pixels.clone(); debug!("tiling took {} ms", now.elapsed().as_millis()); tiles } // attempt at an O(n) split algorithm fn son_of_krunch(&mut self, data: &Vec<u8>, bytes_per_row: i32, startx: i32, starty: i32, endx: i32, endy: i32) -> Vec<Bigtile> { let mut tiles = Vec::<Bigtile>::new(); let mut region_type = RegionType::Unknown; let now = std::time::Instant::now(); for y in (starty..endy).step_by(16) { // define a 16px x 16px (or less at the edges) tile. for x in (startx .. endx).step_by(64) { // 16 px X 4 channel RGBA let mut identical = true; // start by assuming this tile is identical between screens for row in 0..16 { unsafe { let left = (( (y + row) * bytes_per_row) + x) as isize; identical = avx2_cmp( left, &data, &mut self.last ) && identical; let right = (( (y + row) * bytes_per_row) + x + 32) as isize; identical = avx2_cmp( right, &data, &mut self.last ) && identical; } } // the first tile determines whether we will extract a region of similarity or // difference. if region_type == RegionType::Unknown{ region_type = match identical { true => RegionType::Similarity, false => RegionType::Difference, }; } else if (region_type == RegionType::Difference) && identical { // End of a region of difference: send everything above the current row if(y > starty) { tiles.push( Bigtile::from_image(&data, bytes_per_row, startx, starty, endx, y)); } // (2) search the region to the right from the current row tiles.append( &mut self.son_of_krunch(data, bytes_per_row, x, y, endx, endy)); // (3) search the region to the left on the current row if x > startx { tiles.append( &mut self.son_of_krunch(data, bytes_per_row, startx, y, x, endy)); // should this actuall end at x+64? } // println!("(A)son of krunch took {} ms", now.elapsed().as_millis()); return tiles; } else if (region_type == RegionType::Similarity) && !identical { // End of a region of similarity: (1) discard everything above the current // row which is unchanged // (2) search the region to the left below the current row (as everything // immediately left is unchanged) if x > startx { tiles.append( &mut self.son_of_krunch(data, bytes_per_row, startx, y + 16, x, endy)); } // (3) search the region to the right on the current row tiles.append( &mut self.son_of_krunch(data, bytes_per_row, x, y, endx, endy)); println!("(B)son of krunch took {} ms", now.elapsed().as_millis()); return tiles; } else if region_type == RegionType::Difference && x == endx && y == endy { tiles.push( Bigtile::from_image(&data, bytes_per_row, startx, starty, endx, endy)); println!("(C)son of krunch took {} ms", now.elapsed().as_millis()); return tiles; } } } tiles } fn split_v(&mut self, data: &Vec<u8>, bytes_per_row: i32, startx: i32, starty: i32, endx: i32, endy: i32) -> Vec<Bigtile> { let mut tiles = Vec::<Bigtile>::new(); let mut sx: i32 = endx; let mut ex: i32 = -1; for x in (startx .. endx).step_by(64) { // 16 px X 4 channel RGBA let mut identical = true; for y in (starty..endy).step_by(16) { // define a 16px x 16px (or less at the edges) tile. for row in 0..16 { unsafe { let left = (( (y + row) * bytes_per_row) + x) as isize; identical = avx2_cmp( left, &data, &mut self.last ) && identical; let right = (( (y + row) * bytes_per_row) + x + 32) as isize; identical = avx2_cmp( right, &data, &mut self.last ) && identical; } } } if ! identical { if x < sx { sx = x; } if x + 64 > ex { ex = x + 64}; } if (identical && ex != -1) || (!identical && (x + 64) >= endx) { // if we didn't split the area, return one big tile if( sx == startx && ex == endx ) { tiles.push( Bigtile::from_image(&data, bytes_per_row, startx, starty, endx, endy)); } else { // keep trying to split until we can't (consists of one 16px sq) tiles.append( &mut self.split_h(data, bytes_per_row, sx, starty, ex, endy) ); } sx = endx; ex = -1; } } tiles } fn split_h(&mut self, data: &Vec<u8>, bytes_per_row: i32, startx: i32, starty: i32, endx: i32, endy: i32) -> Vec<Bigtile> { let mut tiles = Vec::<Bigtile>::new(); let mut sy: i32 = endy; let mut ey: i32 = -1; for y in (starty..endy).step_by(16) { // define a 16px x 16px (or less at the edges) tile. let mut identical = true; // test whether this row of tiles differs from the previous frame for x in (startx .. endx).step_by(64) { // 16 px X 4 channel RGBA for row in 0..16 { unsafe { let left = (( (y + row) * bytes_per_row) + x) as isize; identical = avx2_cmp( left, &data, &mut self.last ) && identical; let right = (( (y + row) * bytes_per_row) + x + 32) as isize; identical = avx2_cmp( right, &data, &mut self.last ) && identical; } } } if ! identical { if y < sy { sy = y; } if y + 16 > ey { ey = y + 16}; } if (identical && ey != -1) || (!identical && (y+16) >= endy) { // if we didn't split the area, return one big tile if( sy == starty && ey == endy ) { tiles.push( Bigtile::from_image(&data, bytes_per_row, startx, starty, endx, endy)); } else { // keep trying to split until we can't (consists of one 16px sq) tiles.append( &mut self.split_v(data, bytes_per_row, startx, sy, endx, ey) ); } sy = endy; ey = -1; } } tiles } // Populate last, no matter what may have been there before pub fn snap(&mut self) -> Vec<u8> { loop { match self.capturer.frame() { Ok(buf) => { let bgra = buf.to_vec(); self.last = Vec::with_capacity(buf.len()); unsafe { self.last.set_len(buf.len()); for i in (0 .. buf.len() ).step_by(32) { avx2_bgra_to_rgba(i as isize, &bgra, &mut self.last); } } break; }, Err(e) => match e.kind() { ErrorKind::WouldBlock => continue, _ => panic!("Screen grab failed with error {:?}", e), }, }; } self.last.clone() } }
Java
UTF-8
397
1.632813
2
[]
no_license
package com.cheetahlabs.quiz.models; import com.fasterxml.jackson.annotation.JsonProperty; import lombok.Getter; import lombok.Setter; import java.util.Map; @Getter @Setter public class SubmitRequestDTO { @JsonProperty("test_id") private int testId; @JsonProperty("user_id") private int userId; @JsonProperty("response_map") private Map<String, String> responseMap; }