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
|
|---|---|---|---|---|---|---|---|
Markdown
|
UTF-8
| 1,604
| 3
| 3
|
[
"MIT"
] |
permissive
|
# Raspberry Pi Human Detection
## Components
This program enables a Raspberry Pi (tested with Raspberry pi 3 Model B), to
detect a human and plays a sound clip whenever it detects a human in the
vicinity of the sendor. It uses a PIR sensor (passive infrared) connected to the
Raspbery Pi's GPIO pin number 11.
The hardware components used are:
* Raspberry Pi device
* PIR sensor
* Speaker
## Sound clips
The sound clips are not included in this repository. They need to be .mp3 files
and placed in the soundclips directory.
**Note:** When connecting a speaker and the sound output is too low, run the
following command in a terminal window. This sets the output volume to 100%:
```
amixer sset PCM,0 100%
```
## Running the script
Script can be run from a terminal window using:
```
python main.py
```
This will produce a log file: output.log in the same directory where the main.py
file resides.
Alternatively, the main.py file can be executed directly. For this to work,
first set the script to be executable, for example:
```
chmod a+x main.py
```
And then it's callable directly:
```
./main.py
```
To make the program run in the background as soon as the Raspberry Pi restarts,
edit the file /etc/rc.local with an editor. For example, using vi:
```
sudo vi /etc/rc.local
```
Then add the following line to run the main.py file when the device starts up
the next time:
```
/home/pi/projects/rpi-detect-human/main.py &
```
**Note:** this assumes the main.py file was made executable before (see above) and
that the location is within the /home/pi/projects/rpi-detect-human directory.
|
Python
|
UTF-8
| 1,625
| 4.03125
| 4
|
[] |
no_license
|
"""
The accompanying file weather.dat contains weather data for a single month as space-separated values. The first column (Dy) contains the day of the month; the second (MxT) contains the maximum temperature for that day, while the third (MnT) contains the minimum temperature.
The final row contains aggregate values for the entire month.
Write a program to find the row with the maximum spread in the weather.dat file, where spread is defined as the difference between MxT and MnT. For example, the spread for day 2 was (79 - 63) = 16.
Your program should print the day of the month and spread to standard output.
Assuming that your program is called weather.py, then a sample run will look like:
$ python weather.py
2 16
(The actual day and spread will depend on the contents of the file.)
"""
# import pandas module as varible p
import pandas as pd
# open the the weather.dat file
open_file = pd.read_csv('weather.dat', sep='\s+')
# get the columns we need and strip off any non integer character bypassing an an anonymous
# function as an argument to openfile
open_file[['MxT', 'MnT']] = open_file[['MxT', 'MnT']].apply(lambda x: x.str[:2].astype(int))
# find the difference between the two columns
spread = open_file.MxT - open_file.MnT
# find the maximum spread and the index
max_spread = spread.index[spread==max(spread)].tolist()
# find the row with the highest spread unstack them to a list
max_spread_column = open_file.loc[max_spread][['Dy', 'MxT', 'MnT']].unstack().tolist()
# customize the results to get the desired output
print max_spread_column[0], max_spread_column[1]-max_spread_column[2]
|
Java
|
UTF-8
| 1,547
| 2.953125
| 3
|
[] |
no_license
|
package HolderClass;
import java.sql.Timestamp;
public class CycleHolder {
private int cycleId;
private String cycleName="";
private int cycleDay;
private Timestamp cycleDate;
private String cycleRemark="";
public CycleHolder() {
super();
// TODO Auto-generated constructor stub
}
public CycleHolder(int cycleId, String cycleName, int cycleDay, Timestamp cycleDate, String cycleRemark) {
super();
this.cycleId = cycleId;
this.cycleName = cycleName;
this.cycleDay = cycleDay;
this.cycleDate = cycleDate;
this.cycleRemark = cycleRemark;
}
public int getCycleId() {
return cycleId;
}
public String getCycleName() {
return cycleName;
}
public Timestamp getCycleDate() {
return cycleDate;
}
public String getCycleRemark() {
return cycleRemark;
}
public void setCycleId(int cycleId) {
this.cycleId = cycleId;
}
public void setCycleName(String cycleName) {
if(cycleName != null)
this.cycleName = cycleName;
}
public void setCycleDate(Timestamp cycleDate) {
this.cycleDate = cycleDate;
}
public void setCycleRemark(String cycleRemark) {
if(cycleRemark != null)
this.cycleRemark = cycleRemark;
}
public int getCycleDay() {
return cycleDay;
}
public void setCycleDay(int cycleDay) {
this.cycleDay = cycleDay;
}
@Override
public String toString() {
return "CycleHolder [cycleId=" + cycleId + ", cycleName=" + cycleName + ", cycleDay=" + cycleDay
+ ", cycleDate=" + cycleDate + ", cycleRemark=" + cycleRemark + "]";
}
}
|
Go
|
UTF-8
| 672
| 2.890625
| 3
|
[] |
no_license
|
package base62_test
import (
"testing"
"github.com/d4n13l-4lf4/restful-web-services-with-go/chapter07/base62Example/base62"
)
func TestEncodeBase62(t *testing.T) {
expectedEncode := "1C"
numberToEncode := 100
result := base62.ToBase62(numberToEncode)
if result != expectedEncode {
t.Errorf("Expected encode of %d was %s, it does not match %s", numberToEncode, result, expectedEncode)
}
}
func TestDecodeBase62(t *testing.T) {
expectedDecode := 100
encodeToDecode := "1C"
result := base62.ToBase10(encodeToDecode)
if result != expectedDecode {
t.Errorf("Expected decode of %s was %d, it does not match %d", encodeToDecode, result, expectedDecode)
}
}
|
C#
|
UTF-8
| 3,475
| 2.921875
| 3
|
[] |
no_license
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using InvoiceProject;
using System;
using System.Collections.Generic;
using System.Text;
namespace InvoiceProject.Tests
{
[TestClass()]
public class InvoiceTests
{
[TestMethod()]
public void AddInvoiceLineTest()
{
var invoice = new Invoice();
var invoiceLine = new InvoiceLine(1, 6.99m, 1, "Apple");
invoice.AddInvoiceLine(invoiceLine);
Assert.IsTrue(invoice.LineItems.Count == 1);
Assert.AreEqual(invoiceLine, invoice.LineItems[0]);
using (System.IO.StringWriter sw = new System.IO.StringWriter())
{
Console.SetOut(sw);
invoice.AddInvoiceLine(null);
Assert.IsTrue(sw.ToString().Contains("Warning"));
Assert.IsTrue(invoice.LineItems.Count == 1);
}
}
[TestMethod()]
public void RemoveInvoiceLineTest()
{
var invoice = new Invoice();
var appleInvoiceLine = new InvoiceLine(1, 6.99m, 1, "Apple");
var orangeInvoiceLine = new InvoiceLine(1, 7.01m, 1, "Orange");
invoice.AddInvoiceLine(appleInvoiceLine);
invoice.AddInvoiceLine(orangeInvoiceLine);
invoice.RemoveInvoiceLine(1);
Assert.IsTrue(invoice.LineItems.Count == 1);
Assert.AreEqual(appleInvoiceLine, invoice.LineItems[0]);
using (System.IO.StringWriter sw = new System.IO.StringWriter())
{
Console.SetOut(sw);
invoice.RemoveInvoiceLine(10);
Assert.IsTrue(sw.ToString().Contains("ERROR"));
}
}
[TestMethod()]
public void GetTotalTest()
{
var invoice = new Invoice();
invoice.AddInvoiceLine(new InvoiceLine(1, 10.21m, 4, "Banana"));
invoice.AddInvoiceLine(new InvoiceLine(2, 5.21m, 1, "Orange"));
invoice.AddInvoiceLine(new InvoiceLine(3, 5.21m, 5, "Pineapple"));
Assert.AreEqual(72.10m, invoice.GetTotal());
}
[TestMethod()]
public void MergeInvoicesTest()
{
var invoice1 = new Invoice();
invoice1.AddInvoiceLine(new InvoiceLine(1, 10.21m, 4, "Banana"));
var invoice2 = new Invoice();
invoice2.AddInvoiceLine(new InvoiceLine(2, 5.21m, 1, "Orange"));
invoice2.AddInvoiceLine(new InvoiceLine(3, 5.21m, 5, "Pineapple"));
invoice1.MergeInvoices(invoice2);
Assert.AreEqual(72.10m, invoice1.GetTotal());
}
[TestMethod()]
public void CloneTest()
{
var invoice = new Invoice();
invoice.AddInvoiceLine(new InvoiceLine(1, 10.21m, 4, "Banana"));
invoice.AddInvoiceLine(new InvoiceLine(2, 5.21m, 1, "Orange"));
invoice.AddInvoiceLine(new InvoiceLine(3, 5.21m, 5, "Pineapple"));
var clonedInvoice = invoice.Clone();
Assert.AreEqual(72.10m, clonedInvoice.GetTotal());
}
[TestMethod()]
public void ToStringTest()
{
var invoice = new Invoice(DateTime.Now, 1000);
invoice.AddInvoiceLine(new InvoiceLine(1, 6.99m, 1, "Apple"));
var expected = "Invoice Number: 1000, InvoiceDate: 30/09/2020, LineItemCount: 1";
Assert.AreEqual(expected, invoice.ToString());
}
}
}
|
Ruby
|
UTF-8
| 199
| 3.328125
| 3
|
[] |
no_license
|
def second_great_low(arr)
if arr.size == 2
return "#{arr.max}, #{arr.min}"
end
arr = arr.uniq.map {|x| x.to_i }.sort!
return "#{arr[1]},#{arr[-2]}"
end
p second_great_low([2,4,1,3,6])
|
Java
|
UTF-8
| 2,353
| 2.1875
| 2
|
[] |
no_license
|
package com.lenecoproekt.weatherapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.content.res.Configuration;
import android.os.Bundle;
import android.widget.FrameLayout;
public class MainActivity extends AppCompatActivity {
FrameLayout container;
FrameLayout container2;
FrameLayout container3;
FragmentManager myFragmentManager;
MainFragment mainFragment;
SettingsFragment settingsFragment;
CityChangerFragment cityChangerFragment;
ForecastFragment forecastFragment;
TestFragment testFragment;
final static String TAG_1 = "MAIN_WINDOW";
final static String TAG_2 = "SETTINGS";
final static String TAG_3 = "CITY_CHANGER";
final static String TAG_4 = "WEATHER_FORECAST";
final static String KEY_MSG_1 = "FRAGMENT1_MSG";
final static String KEY_MSG_2 = "FRAGMENT2_MSG";
final static String KEY_MSG_3 = "FRAGMENT3_MSG";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
container = findViewById(R.id.container);
container2 = findViewById(R.id.container2);
container3 = findViewById(R.id.container3);
myFragmentManager = getSupportFragmentManager();
mainFragment = new MainFragment();
settingsFragment = new SettingsFragment();
cityChangerFragment = new CityChangerFragment();
forecastFragment = new ForecastFragment();
if (savedInstanceState == null) {
// при первом запуске программы
FragmentTransaction fragmentTransaction = myFragmentManager
.beginTransaction();
// добавляем в контейнер при помощи метода add()
fragmentTransaction.add(R.id.container, mainFragment, TAG_1);
fragmentTransaction.add(R.id.container2, forecastFragment, TAG_4);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
fragmentTransaction.add(R.id.container3, cityChangerFragment, TAG_3);
}
fragmentTransaction.commit();
}
}
}
|
Go
|
UTF-8
| 1,879
| 2.640625
| 3
|
[] |
no_license
|
package store
import (
"context"
"email-acceptor/helpers"
"email-acceptor/models"
"encoding/json"
"github.com/Zetkolink/go-amqp-reconnect/rabbitmq"
"github.com/biezhi/gorm-paginator/pagination"
"github.com/lithammer/shortuuid"
"github.com/streadway/amqp"
"strings"
)
type MessageStore struct {
db helpers.DbConnection
ex string
ch *rabbitmq.Channel
}
func NewMessageStore(db helpers.DbConnection, ch *rabbitmq.Channel, ex string) *MessageStore {
return &MessageStore{
db: db,
ch: ch,
ex: ex,
}
}
func (ms MessageStore) Migrate() {
msg := models.Messages{}
msg.Migrate(ms.db.DB)
}
func (ms MessageStore) Send(msg models.MessageRequest) (string, error) {
id := shortuuid.New()
msg.UniqueId = &id
request, err := json.Marshal(msg)
if err != nil {
return id, err
}
err = ms.ch.Publish(ms.ex, "", false, false, amqp.Publishing{
ContentType: "application/json",
Body: request,
})
if err != nil {
return id, err
}
resp := models.Success{Id: id}
respJson, _ := json.Marshal(resp)
return string(respJson), nil
}
func (ms MessageStore) GetMessageRequest(_ context.Context, uniqueId string) (string, error) {
messages := models.Messages{}
err := ms.db.Where("id = ?", uniqueId).Find(&messages).Error
if err != nil {
return "", err
}
return messages.Obj, nil
}
func (ms MessageStore) GetMessageRequestAll(_ context.Context, page int, perPage int) (string, int, int, int, int) {
messages := make([]models.Messages, 0)
pagin := pagination.Paging(&pagination.Param{
DB: ms.db.Where("id != ?", ""),
Page: page,
Limit: perPage,
OrderBy: []string{"id desc"},
ShowSQL: false,
}, &messages)
res := make([]string, 0, len(messages))
for _, v := range messages {
res = append(res, v.Obj)
}
return "[" + strings.Join(res, ",") + "]", pagin.TotalRecord, pagin.TotalPage, pagin.NextPage, pagin.PrevPage
}
|
C#
|
UTF-8
| 2,740
| 3.09375
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace VehicleRental
{
public partial class RentCarForm : Form
{
private VehicleRepository _vehicleRepository = new VehicleRepository();
private BindingSource _vehicleBindingSource = new BindingSource();
private string filePath;
public RentCarForm()
{
InitializeComponent();
}
//this method is called when the rent car form loads.
//it calls GetVehicleData method to get rent details
private void RentCarForm_Load(object sender, EventArgs e)
{
GetVehicleData(sender, e);
}
private void GetVehicleData(object sender, EventArgs e)
{
//to display in grid
//it get's vehicle data from vehicleRepository class.
_vehicleBindingSource.DataSource = _vehicleRepository.GetVehicles();
//if set to true creates a new object if the list is empty.
_vehicleBindingSource.AllowNew = false;
vehicleComboBOx.DataSource = _vehicleBindingSource;
vehicleComboBOx.DisplayMember = "VehicleName";
vehicleComboBOx.ValueMember = "VehicleName";
}
public VehicleRentDetail VehicleRentDetail
{
get
{
var rentDetail = new VehicleRentDetail();
rentDetail.VehicleName = Convert.ToString(vehicleComboBOx.SelectedValue);
rentDetail.Date = datePicker.Value.Date;
rentDetail.InTime = inTimePicker.Value.TimeOfDay;
rentDetail.OutTime = outTimeDatePicker.Value.TimeOfDay;
rentDetail.TotalHours = rentDetail.CalculateTotalHours();
return rentDetail;
}
}
private void SerializeVehicleData(List<Vehicle> vehicles)
{
//step 1: create a new file/ opens the file if it already exisits.
Stream str = File.Open(filePath + @"\vehicleDetails.dat", FileMode.Create);
//BinaryFormatter class has method to convert c# list to .dat file. i.e. serialization.
BinaryFormatter bF = new BinaryFormatter();
//step 2: convert c# list to .dat file.
bF.Serialize(str, vehicles);
//step 3: writes to the file.
str.Flush();
//step 4: close the stream.
str.Close();
MessageBox.Show("Vehicle Details saved to file");
}
}
}
|
C#
|
UTF-8
| 1,390
| 2.8125
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Worker
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
while(true)
{
UpdateDB();
}
}
public static void UpdateDB ()
{
bool Status;
Random random = new Random();
string Id = "1";
Status = random.Next(2) == 0 ? true : false;
var json = Newtonsoft.Json.JsonConvert.SerializeObject(new
{
Name = Id,
Value = Status,
});
var request = WebRequest.CreateHttp("https://parkingdb-a7779.firebaseio.com/Parcare1/.json");
request.Method = "PATCH";
request.ContentType = "application/json";
var buffer = Encoding.UTF8.GetBytes(json);
request.ContentLength = buffer.Length;
request.GetRequestStream().Write(buffer, 0, buffer.Length);
var response = request.GetResponse();
json = (new StreamReader(response.GetResponseStream())).ReadToEnd();
}
}
}
|
Shell
|
UTF-8
| 1,287
| 3.40625
| 3
|
[] |
no_license
|
#!/bin/sh
SERVICE='mariadb'
while true
do
if [ "`systemctl is-active $SERVICE`" != "active" ]
then
attemptcount=0
while [ $attemptcount -lt 3 ]
do
#echo "$SERVICE is not running"
systemctl start $SERVICE.service
if [ "`systemctl is-active $SERVICE`" = "active" ]
then
#echo "$SERVICE service restarted and running, everything is fine"
echo "$SERVICE service is restarted!" | mail -s "$SERVICE service is restarted" tejbahadur.singh@clique.sg prashant.kawe@clique.sg nikhil.karmokar@clique.sg
break
else
attemptcount=`expr $attemptcount + 1`
fi
if [ $attemptcount -eq 3 ]
then
systemctl restart php-fpm.service
systemctl restart nginx.service
systemctl start $SERVICE.service
if [ "`systemctl is-active $SERVICE`" = "active" ]
then
#echo "whole service restarted and running, everything is fine"
echo "$SERVICE ,php-fpm, mariadb are restarted!" | mail -s "whole service is restarted" tejbahadur.singh@clique.sg prashant.kawe@clique.sg nikhil.karmokar@clique.sg
else
echo "$SERVICE is not running!" | mail -s "$SERVICE is down" tejbahadur.singh@clique.sg prashant.kawe@clique.sg nikhil.karmokar@clique.sg
fi
fi
done
fi
sleep 5
done
|
TypeScript
|
UTF-8
| 681
| 3.015625
| 3
|
[
"Apache-2.0"
] |
permissive
|
import { appState } from './../state/app.state';
export function appReducer(action:any, state = appState) {
// The reducer normally looks at the action type field to decide what happens
switch (action.type) {
case 'CounterComponent/add':
action.payload++;
return {...state, counter: action.payload};
case 'CounterComponent/subtract':
action.payload--;
return {...state, counter: action.payload};
default:
// If this reducer doesn't recognize the action type, or doesn't
// care about this specific action, return the existing state unchanged
return state
}
}
|
Java
|
UTF-8
| 625
| 1.679688
| 2
|
[] |
no_license
|
package com.excalibur.funwithgles.cropimage.b612crop;
import com.excalibur.funwithgles.cropimage.b612crop.view.CropAngleView;
public final class g implements CropAngleView.a {
//final /* synthetic */ this$0;
//g(EditFeatureCropFragment editFeatureCropFragment) {
// this.this$0 = editFeatureCropFragment;
// }
public void i(int i, int i2, boolean z) {
//this.this$0.zc(i);
//EditFeatureCropFragment editFeatureCropFragment = this.this$0;
//editFeatureCropFragment.uxa = (editFeatureCropFragment.uxa + i2) % 360;
//this.this$0.Dp().a(this.this$0.uxa, z, !z);
}
}
|
C++
|
UTF-8
| 2,245
| 3.171875
| 3
|
[] |
no_license
|
//在上次打劫完一条街道之后和一圈房屋后,小偷又发现了一个新的可行窃的地区。这个地区只有一个入口,我们称之为“根”。 除了“根”之外,每栋房子有且只有一个“父“
//房子与之相连。一番侦察之后,聪明的小偷意识到“这个地方的所有房屋的排列类似于一棵二叉树”。 如果两个直接相连的房子在同一天晚上被打劫,房屋将自动报警。
//
// 计算在不触动警报的情况下,小偷一晚能够盗取的最高金额。
//
// 示例 1:
//
// 输入: [3,2,3,null,3,null,1]
//
// 3
// / \
// 2 3
// \ \
// 3 1
//
//输出: 7
//解释: 小偷一晚能够盗取的最高金额 = 3 + 3 + 1 = 7.
//
// 示例 2:
//
// 输入: [3,4,5,1,3,null,1]
//
// 3
// / \
// 4 5
// / \ \
// 1 3 1
//
//输出: 9
//解释: 小偷一晚能够盗取的最高金额 = 4 + 5 = 9.
//
// Related Topics 树 深度优先搜索
// 👍 574 👎 0
/**
* @Author: muzhikid
* @CreatedTime: 2020-09-15 16:02:53
*/
#include <iostream>
#include <map>
#include <queue>
#include <unordered_map>
#include <vector>
#include <algorithm>
using namespace std;
//leetcode submit region begin(Prohibit modification and deletion)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
struct TreeNode{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x):val(x),left(NULL),right(NULL){}
};
//vector<int>recordTree;
unordered_map<int,int>recordTree;
void init(TreeNode *pNode,int id) {
if(pNode==NULL){
return;
}else{
recordTree[id]=pNode->val;
cout<<"Id is "<<id<<" and val is "<<recordTree[id];
init(pNode->left,id*2);
init(pNode->right,id*2+1);
}
}
int rob(TreeNode* root) {
init(root,1);
return 0;
}
};
//leetcode submit region end(Prohibit modification and deletion)
int main(){
Solution s;
//s.method(params*);
//cout<<s.method(params*);
}
|
Markdown
|
UTF-8
| 932
| 2.546875
| 3
|
[] |
no_license
|


根据商业组织形式分类,预言机可以是中心化的单一预言者的机制(如 Oraclize)——中心化预言机,同样也可以是去中心化的多个预言者的机制(如 Chainlink、DOS Network 等)——去中心化预言机。
典型的预言机项目有 ChainLink、Oraclize、DOS Network、
OracleChain 等。
* Oraclize 是一个具有真实性证明的中心化预言机,目前支持以
太坊(Ethereum)、Rootstock、R3 Corda、Hyperledger Fabric 和 EOS
等多个平台。
参考:
[如何在智能合约中使用 Oraclize 调取外部接口](https://blog.junezhu.top/2019/01/29/how-to-use-oraclize-at-ethereum.html)
[Chainlink预言机基本原理](https://segmentfault.com/a/1190000022774144)
[【以太坊开发】区块链中的预言机:Oraclize原理介绍](https://www.cnblogs.com/gzhlt/p/10052362.html)
|
PHP
|
UTF-8
| 1,176
| 2.84375
| 3
|
[] |
no_license
|
<?php
header("Content-type: text/xml");
// Start XML file, echo parent node
echo "<?xml version='1.0' ?>";
echo "<markers>";
$ind=0;
function parseToXML($htmlStr)
{
$xmlStr=str_replace('<','<',$htmlStr);
$xmlStr=str_replace('>','>',$xmlStr);
$xmlStr=str_replace('"','"',$xmlStr);
$xmlStr=str_replace("'",''',$xmlStr);
$xmlStr=str_replace("&",'&',$xmlStr);
return $xmlStr;
}
include('include/include_all.php');
function get_crime(){
$result = dbQuery("
SELECT *
FROM county_crime
")->fetchAll();
return $result;
}
get_crime();
// Iterate through the rows, adding XML nodes for each
while ($row = get_crime()){
echo "<marker ";
echo"id='" . $row['id'] . "' ";
echo"offense='" . $row['offense'] . "' ";
echo"type='" . $row['type'] . "' ";
echo"occurred='" . $row['occurred'] . "' ";
echo"address='" . $row['address'] . "' ";
echo"precinct='" . $row['precinct'] . "' ";
echo"reporting_jurisdiction='" . $row['reporting_jurisdiction'] . "' ";
echo"for_jurisdiction='" . $row['for_jurisdiction'] . "' ";
echo"lat='" . $row['lat'] . "' ";
echo"lng='" . $row['lng'] . "' ";
echo '/>';
$ind = $ind + 1;
}
echo "</markers>";
?>
|
Swift
|
UTF-8
| 5,458
| 2.53125
| 3
|
[
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// SnapshotTestCase
// edX
//
// Created by Akiva Leffert on 5/14/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import Foundation
private let StandardTolerance : CGFloat = 0.005
protocol SnapshotTestable {
func snapshotTestWithCase(_ testCase : FBSnapshotTestCase, referenceImagesDirectory: String, imageDiffDirectory: String, identifier: String) throws
var snapshotSize : CGSize { get }
}
extension UIView : SnapshotTestable {
func snapshotTestWithCase(_ testCase: FBSnapshotTestCase, referenceImagesDirectory: String, imageDiffDirectory: String, identifier: String) throws {
try testCase.compareSnapshot(of: self, referenceImagesDirectory: referenceImagesDirectory, imageDiffDirectory: imageDiffDirectory, identifier: identifier, overallTolerance: StandardTolerance)
}
var snapshotSize : CGSize {
return bounds.size
}
}
extension CALayer : SnapshotTestable {
func snapshotTestWithCase(_ testCase: FBSnapshotTestCase, referenceImagesDirectory: String, imageDiffDirectory: String, identifier: String) throws {
try testCase.compareSnapshot(of: self, referenceImagesDirectory: referenceImagesDirectory, imageDiffDirectory: imageDiffDirectory, identifier: identifier, overallTolerance: StandardTolerance)
}
var snapshotSize : CGSize {
return bounds.size
}
}
extension UIViewController : SnapshotTestable {
func prepareForSnapshot() {
let window = UIWindow(frame: UIScreen.main.bounds)
window.rootViewController = self
window.makeKeyAndVisible()
}
func snapshotTestWithCase(_ testCase: FBSnapshotTestCase, referenceImagesDirectory: String, imageDiffDirectory: String, identifier: String) throws {
try testCase.compareSnapshot(of: self.view, referenceImagesDirectory: referenceImagesDirectory, imageDiffDirectory: imageDiffDirectory, identifier: identifier, overallTolerance: StandardTolerance)
}
func finishSnapshot() {
view.window?.removeFromSuperview()
}
var snapshotSize : CGSize {
return view.bounds.size
}
}
class SnapshotTestCase : FBSnapshotTestCase {
override func setUp() {
super.setUp()
// Run "./gradlew recordSnapshots --continue" to regenerate all snapshots
#if RECORD_SNAPSHOTS
recordMode = true
#endif
}
var screenSize : CGSize {
// Standardize on a size so we don't have to worry about different simulators
// etc.
// Pick a non standard width so we can catch width assumptions.
return CGSize(width: 380, height: 568)
}
fileprivate var majorVersion : Int {
return ProcessInfo.processInfo.operatingSystemVersion.majorVersion
}
fileprivate final func qualifyIdentifier(_ identifier : String?, content : SnapshotTestable) -> String {
let rtl = UIApplication.shared.userInterfaceLayoutDirection == .rightToLeft ? "_rtl" : ""
let suffix = "ios\(majorVersion)\(rtl)_\(Int(content.snapshotSize.width))x\(Int(content.snapshotSize.height))"
if let identifier = identifier {
return identifier + suffix
}
else {
return suffix
}
}
// Asserts that a snapshot matches expectations
// This is similar to the objc only FBSnapshotTest macros
// But works in swift
func assertSnapshotValidWithContent(_ content : SnapshotTestable, identifier : String? = nil, message : String? = nil, file : StaticString = #file, line : UInt = #line) {
let qualifiedIdentifier = qualifyIdentifier(identifier, content : content)
do {
try content.snapshotTestWithCase(self, referenceImagesDirectory: SNAPSHOT_TEST_DIR, imageDiffDirectory: SNAPSHOT_TEST_FAILURE_DIFF_DIR, identifier: qualifiedIdentifier)
}
catch let error as NSError {
XCTFail("Snapshot comparison failed (\(qualifiedIdentifier)): \(error.localizedDescription )", file : file, line : line)
if let message = message {
XCTFail(message, file : file, line : line)
}
else {
XCTFail(file : file, line : line)
}
}
XCTAssertFalse(recordMode, "Test ran in record mode. Reference image is now saved. Disable record mode to perform an actual snapshot comparison!", file : file, line : line)
}
func inScreenNavigationContext(_ controller : UIViewController, action : () -> ()) {
let container = UINavigationController(rootViewController: controller)
inScreenDisplayContext(container, action: action)
}
/// Makes a window and adds the controller to it
/// to ensure that our controller actually loads properly
/// Otherwise, sometimes viewWillAppear: type methods don't get called
func inScreenDisplayContext(_ controller : UIViewController, action : () -> ()) {
let window = UIWindow(frame: CGRect.zero)
window.rootViewController = controller
window.frame = CGRect(x: 0, y: 0, width: screenSize.width, height: screenSize.height)
window.makeKeyAndVisible()
controller.view.frame = window.bounds
controller.view.updateConstraintsIfNeeded()
controller.view.setNeedsLayout()
controller.view.layoutIfNeeded()
action()
window.removeFromSuperview()
}
}
|
C
|
UTF-8
| 1,677
| 2.65625
| 3
|
[] |
no_license
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* server.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: bemmanue <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/10/04 16:30:44 by bemmanue #+# #+# */
/* Updated: 2021/10/04 16:30:46 by bemmanue ### ########.fr */
/* */
/* ************************************************************************** */
#include "minitalk.h"
t_info g_info;
void handler(int signum, siginfo_t *siginfo, void *context)
{
(void)context;
(void)siginfo;
if (signum == SIGUSR1)
g_info.character += (0 << g_info.index);
else if (signum == SIGUSR2)
g_info.character += (1 << g_info.index);
g_info.index++;
if (g_info.index == 8)
{
write(1, &(g_info.character), 1);
g_info.index = 0;
g_info.character = 0b00000000;
}
}
int main(void)
{
struct sigaction act;
g_info.character = 0b00000000;
g_info.index = 0;
act.sa_sigaction = handler;
act.sa_flags = SA_SIGINFO;
if (sigaction(SIGUSR1, &act, NULL))
terminate();
if (sigaction(SIGUSR2, &act, NULL))
terminate();
ft_putstr_fd("Server PID: ", 1);
ft_putnbr_fd(getpid(), 1);
ft_putchar_fd('\n', 1);
while (1)
sleep (1);
return (0);
}
|
JavaScript
|
UTF-8
| 2,897
| 2.8125
| 3
|
[] |
no_license
|
//Close modal on close button click
$('#close').on("click", event => {
$('#myModal').modal('hide');
})
//Console log JSON object on export button click
$('#export').on("click", function( event ) {
console.log($('#previewSite').attr('src').substr(41));
})
//Form submit
$( "form" ).on( "submit", function( event ) {
event.preventDefault();
//Validate all input fields have values
var emptyInputs = $(this).parent().find('input[type="text"]').filter(function() { return $(this).val() == ""; });
if (emptyInputs.length) {
alert('Please complete all fields.');
} else {
//Launch modal
$('#myModal').modal();
let info = {
businessName: $('#businessName').val(),
street: $('#street').val(),
city: $('#city').val(),
state: $('#state').val(),
postalCode: $('#postalCode').val(),
country: $('#country').val(),
phoneNumber: $('#phoneNumber').val()
}
let infoJSON = JSON.stringify(info);
//Modify iframe src attribute to include site parameter
$('#previewSite').attr('src', 'http://localhost:3000/live-preview/?site=' + infoJSON);
//Get data from query string
$.get('/business.json', info, data => {
let dataToPass = {businessName: data.data.businessName,
street: data.data.street,
city: data.data.city,
state: data.data.state,
postalCode: data.data.postalCode,
country: data.data.country,
phoneNumber: data.data.phoneNumber
};
//Insert text on iframe load
$('#previewSite').on("load", dataToPass, event => {
const frame = document.getElementById("previewSite"),
site = frame.contentWindow.document,
businessName = site.getElementById('lpBusiness'),
street = site.getElementById('lpStreet'),
city = site.getElementById('lpCity'),
state = site.getElementById('lpState'),
postalCode = site.getElementById('lpPostalCode'),
country = site.getElementById('lpCountry'),
phoneNumber = site.getElementById('lpPhoneNumber');
businessName.innerHTML = event.data.businessName;
street.innerHTML = event.data.street;
city.innerHTML = event.data.city + ",";
state.innerHTML = event.data.state;
postalCode.innerHTML = event.data.postalCode;
country.innerHTML = event.data.country;
phoneNumber.innerHTML = event.data.phoneNumber;
})
})
}
})
|
JavaScript
|
UTF-8
| 1,236
| 2.734375
| 3
|
[] |
no_license
|
var http = require('http');
var url = require('url');
var server = http.createServer(function(request, response){
//1. 실제 요청한 주소 전체를 콘솔에 출력
console.log(request.url);
var parsedUrl = url.parse(request.url);
//2. parsing 된 url 중에 서버URI에 해당하는 pathname만 따로 저장
var resource = parsedUrl.pathname;
console.log('resource path=%s', resource);
//3. 리소스에 해당하는 문자열이 아래와 같으면 해당 메시지를 클라이언트에 전달
if(resource == '/address'){
response.writeHead(200, {'Content-Type':'text/plqin; charset=utf-8'});
response.end('서울특별시 동대문구 천호대로');
}else if(resource == '/phone'){
response.writeHead(200, {'Content-Type':'text/plqin; charset=utf-8'});
response.end('010-1234-5678');
}else if(resource == '/name'){
response.writeHead(200, {'Content-Type':'text/plqin; charset=utf-8'});
response.end('Seong Hyun Min');
}else{
response.writeHead(404, {'Content-Type':'text/plqin; charset=utf-8'});
response.end('404 Page Not Found!');
}
});
server.listen(7000, function(){
console.log('Server is running...');
});
|
Java
|
UTF-8
| 2,802
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
package de.paillier.crypto;
import static org.junit.Assert.assertEquals;
import java.math.BigInteger;
import org.junit.Before;
import org.junit.Test;
import de.paillier.key.KeyPair;
import de.paillier.key.KeyPairBuilder;
import de.paillier.key.PublicKey;
public class HomomorphicPropertiesTest {
private KeyPair keypair;
private PublicKey publicKey;
@Before
public void init() {
KeyPairBuilder keygen = new KeyPairBuilder();
this.keypair = keygen.generateKeyPair();
this.publicKey = keypair.getPublicKey();
}
@Test
public void testHomomorphicAddition() {
BigInteger plainA = BigInteger.valueOf(102);
BigInteger plainB = BigInteger.valueOf(203);
BigInteger encryptedA = JPaillier.encrypt(plainA, publicKey);
BigInteger encryptedB = JPaillier.encrypt(plainB, publicKey);
BigInteger decryptedProduct = JPaillier.decrypt(encryptedA.multiply(
encryptedB).mod(publicKey.getnSquared()), keypair);
BigInteger plainSum = plainA.add(plainB).mod(publicKey.getN());
assertEquals(decryptedProduct, plainSum);
}
@Test
public void testHomomorphicConstantMultiplication() {
BigInteger plainA = BigInteger.valueOf(14);
BigInteger plainB = BigInteger.valueOf(203);
BigInteger encryptedA = JPaillier.encrypt(plainA, publicKey);
BigInteger decryptedPow = JPaillier.decrypt(encryptedA.modPow(plainB,
publicKey.getnSquared()), keypair);
BigInteger plainSum = plainA.multiply(plainB).mod(publicKey.getN());
assertEquals(decryptedPow, plainSum);
}
@Test
public void testHomomorphicMultiplication() {
BigInteger plainA = BigInteger.valueOf(23);
BigInteger plainB = BigInteger.valueOf(234);
BigInteger encryptedA = JPaillier.encrypt(plainA, publicKey);
BigInteger decryptedPowA = JPaillier.decrypt(encryptedA.modPow(
plainB, publicKey.getnSquared()), keypair);
BigInteger plainSumA = plainA.multiply(plainB).mod(publicKey.getN());
assertEquals(decryptedPowA, plainSumA);
BigInteger encryptedB = JPaillier.encrypt(plainB, publicKey);
BigInteger decryptedPowB = JPaillier.decrypt(encryptedB.modPow(
plainA, publicKey.getnSquared()), keypair);
BigInteger plainSumB = plainA.multiply(plainB).mod(publicKey.getN());
assertEquals(decryptedPowB, plainSumB);
assertEquals(decryptedPowA, decryptedPowB);
}
@Test
public void testHomomorphicMultiplicationPowG() {
BigInteger plainA = BigInteger.valueOf(230);
BigInteger plainB = BigInteger.valueOf(100);
BigInteger g = publicKey.getG();
BigInteger encryptedA = JPaillier.encrypt(plainA, publicKey);
BigInteger decryptedPow = JPaillier.decrypt(encryptedA.multiply(g.modPow(
plainB, publicKey.getnSquared()).mod(publicKey.getnSquared())), keypair);
BigInteger plainSumA = plainA.add(plainB).mod(publicKey.getN());
assertEquals(decryptedPow, plainSumA);
}
}
|
JavaScript
|
UTF-8
| 185
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
/**
* Created by Birkenstab (http://birkenstab.de) on 2017-01-29
*/
const mathUtil = require("util/mathUtil");
const result = mathUtil.add(3, 9);
console.log("3 + 9 = " + result);
|
Java
|
UTF-8
| 652
| 2.3125
| 2
|
[] |
no_license
|
package com.voicepin.flow.client.ssl;
import java.security.NoSuchAlgorithmException;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
/**
* @author Lukasz Warzecha
*/
public class TrustedCertificateStrategy implements CertificateStrategy {
@Override
public HostnameVerifier getHostnameVerifer() {
return (String hostname, SSLSession session) -> true;
}
@Override
public SSLContext getSSLContext() {
try {
return SSLContext.getDefault();
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException(e);
}
}
}
|
JavaScript
|
UTF-8
| 5,269
| 2.5625
| 3
|
[] |
no_license
|
const express = require("express");
const server = express();
const port = 9000;
server.use(express.json());
const projects = require('./data/helpers/projectModel');
const actions = require('./data/helpers/actionModel');
// ** Project Routes **
//get all projects
server.get('/api/projects', (req, res) => {
projects
.get()
.then(projects => {
res.status(200).json(projects);
})
.catch(err => {
res.status(500).json({message: 'No Projects Found'});
});
});
//get projects by id
server.get('/api/projects/:id', (req, res) => {
const id = req.params.id;
projects
.get(id)
.then(project => {
if(!project) {
res.status(404).json({message: 'No Project with this ID exists'})
} else {
res.status(200).send(project);
}
})
.catch(err => {
res.status(500).json({error: 'project can not be populated at this time'});
});
});
//create new project
server.post('/api/projects/', (req, res) => {
const projectModel = req.body;
projects
.insert(projectModel)
.then(response => {
res.status(201).json(response);
})
.catch(err => {
if (err.errno === 19) {
res.status(404).json({message: 'please provide all required fields'});
} else {
res.status(500).json({message: 'Not able to create new project at this time'});
}
});
});
//update project *** come back to check error handling
server.put('/api/projects/:id', (req, res) => {
const id = req.params.id;
const update = req.body;
projects
.update(id, update)
.then(projects => {
res.status(200).json(projects);
})
.catch(err => {
res.status(500).json({message: 'Server cannot update project at this time.'});
});
});
//delete project
server.delete('/api/projects/:id', (req, res) => {
const id = req.params.id;
projects
.remove(id)
.then(response => {
res.status(200).json({message: 'project deleted' })
})
.catch(err => {
res.status(500).json({message: 'unable to remove project from server'});
});
});
// ** Action Routes **
//get all actions
server.get('/api/actions', (req, res) => {
actions
.get()
.then(actions => {
res.status(200).json(actions);
})
.catch(err => {
res.status(500).json({message: 'No Actions Found'});
});
});
//get actions by id
server.get('/api/actions/:id', (req, res) => {
const id = req.params.id;
actions
.get(id)
.then(action => {
if(!action) {
res.status(404).json({message: 'No Action with this ID exists'})
} else {
res.status(200).send(action);
}
})
.catch(err => {
res.status(500).json({error: 'action can not be populated at this time'});
});
});
//get actions by project id
server.get('/api/projects/:id/actions/', (req, res) => {
const id = req.params.id;
projects
.getProjectActions(id)
.then(actions => {
if(!actions) {
res.status(404).json({message:'no actions found for this project'});
} else {
res.status(200).send(actions);
}
})
.catch(err => {
res.status(500).json({message:'actions cannot be populated at this time.'});
});
});
//create new action
server.post('/api/actions', (req, res) => {
const newAction = {
"project_id": req.body.project_id,
"description": req.body.description,
"notes": req.body.notes
}
if (!newAction.description || !newAction.notes || !newAction.project_id) {
return res.status(400).json({msg: 'please provide all required fields'});
}
actions
.insert(newAction)
.then(response => {
res.status(201).json(response);
})
.catch(err => {
res.status(500).json({message: 'Not able to create new action at this time'});
});
});
//update action by id *** come back to check error handling
server.put('/api/actions/:id', (req, res) => {
const id = req.params.id;
const update = req.body;
actions
.update(id, update)
.then(action => {
res.status(200).json(action)
})
.catch(err => {
res.status(500).json({message: 'Server cannot update project at this time.'});
});
})
//delete action
server.delete('/api/actions/:id', (req, res) => {
const id = req.params.id;
actions
.get(id)
.then(action => {
actions
.remove(id)
.then(action => {
res.status(200).json({message: 'action has been deleted'})
})
.catch(err => {
res.status(500).json(err)
});
})
.catch(err => {
res.status(404).json({message: 'action not found'});
});
});
server.listen(port, () => {
console.log (`\n ******* Server Running on Port ${port} ********\n`)
})
|
Markdown
|
UTF-8
| 1,441
| 2.84375
| 3
|
[] |
no_license
|
---
title: ubuntu下构建deb包
date: 2019-07-23 20:17:33
categories: 开发者手册
---
本文讲解如何构建一个deb包
### dpgk
首先介绍下dpkg,dpkg是debian系统下软件包管理工具,用dpkg可以很方便的安装管理我们的deb包,为什么呢,因为deb包都是用dpkg构建的。类似于rethat系列的软件用rpm一样,rethat用rpm管理软件,用rpmbuild构建软件。
<!-- more -->
### 如何用dpkg构建一个软件包呢
1. 模仿,找一个流行的deb包,拆开里面的内容,看看它们是怎么写的,模仿他们准没错。我们可以上 dpkg.org 去查找比较流行的程序。这里我以sshd服务举例
2. 解压sshd基本资源
```bash
dpkg -x openssh-server_6.6p1-2ubuntu1_amd64.deb openssh
```
现在解压的都是sshd自身的东西,比如可执行程序,man文档,启动脚本之类的
3. 解压 debian 包构建脚本
```bash
dpkg -e openssh-server_6.6p1-2ubuntu1_amd64.deb openssh/DEBIAN
```
这DEBIAN里面就是构建deb包所需要的脚本, 我们最需要关注的就是control,其他的可有可无
4. 以上内容就是构建sshd服务的所有内容了,重新打包下试试
```bash
dpkg -b openssh openssh.deb
```
以上就是构建包的整理流程,但是你要是构建软件,你可能还需要一些其他的知识,比如Linux service脚本编写, /etc/init.d/脚本编写等等。
|
C
|
UTF-8
| 442
| 3.09375
| 3
|
[] |
no_license
|
#include <stdio.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
void sigHandler (int s){
}
int main() {
int status = 0;
signal(SIGINT, sigHandler);
int pid = fork();
if (pid == 0) //if pid == 0, it is child
{
printf("child PID = %d\n", getpid());
pause();
exit(5);
}
else
{
waitpid(pid, &status, 0);
printf("\nchild PID = %d, exitstatus = %d\n", pid, WEXITSTATUS(status));
}
return 0;
}
|
JavaScript
|
UTF-8
| 704
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
var run = require('tape').test
var arp = require('arp-table')
var parse = require('arp-parse')
var localip = require('my-local-ip')()
var arpulate = require('../')
run('add 20 addresses that surround the local computer', function(test) {
arpulate(localip, 20, function() {
var addresses = []
var parser = parse()
arp().stdout
.pipe(parser)
parser.on('data', function(device) {
addresses.push(device.ip)
})
parser.on('end', function() {
var neighbours = addresses.filter(function(ip) {
return ip !== localip
})
test.ok(neighbours.length >= 20, localip + ' now has at least 20 neighbouring addresses')
test.end()
})
})
})
|
Markdown
|
UTF-8
| 559
| 2.625
| 3
|
[] |
no_license
|
# forecastAPI
- Gather daily weather information based on location id and given range date
- Produce pivoted table report of precipitation probability of each location id on given date.
Tools Used:
- python
- Panda
API used:
- Google Map API
- Dark Sky API
Instruction to run:
- Setup environmnet variable with its respective API keys:
- DSKY_KEY = [KEY]
- GMAPS_KEY = [KEY]
- Use following command to setup env variable:
export DSKY_KEY='[KEY]'
export GMAPS_KEY='[KEY]
- Get Location.csv into directory and run forecast python program.'
|
Markdown
|
UTF-8
| 2,360
| 2.984375
| 3
|
[
"MIT"
] |
permissive
|
# Slack-chat-with-SMS
You love [Slack](https://slack.com/)?
Now anyone can send you text messages / SMS.
The conversation starts in its own Slack channel, and you can reply `/sms anything you like`.

## Setup and configuration
```bash
git clone git@github.com:arthur-flam/slack-chat-with-sms.git
cd slack-chat-with-sms
cp config.js.sample config.js
npm install
```
Before you type `npm start`, you will need to setup the Slack and SMS integrations...
Sorry it is a bit long, but consider how amazing it is to chat with anyone via SMS through Slack ;)
First of all type your hostname/ip/protocole in the new `config.js` file.
### Setting up Nexmo (inexpensive and friendly SMS provider)
1. Get a [Nexmo account](https://nexmo.com)
2. Get a sms-enabled phone number and type it in the *config.js* file.
3. Copy-paste the `APP_ID` or `KEY` and `APP_SECRET` available on the *API settings* on the config file.
5. Configure the SMS settings for you number. The Callback URL should be *http://YOUR_HOSTNAME/v1/sms/in*
### Slack integration
1. Type your team name (like *NAME.slack.com*) in the config file.
2. [Setup a slash command](https://lookies.slack.com/apps/manage/custom-integrations) as a custom integration. This will let you reply with `/sms` :
* As URL use `http://YOUR_HOSTNAME/v1/hook`
* As command name use `/sms` or `reply`. `/s` is already the search command!
* Check method is **POST**
* You can copy-paste the command token in the *config.js* file
* Use any custom, name, icon, label, description...
3. [Create an API token](https://api.slack.com/web). This will enable our app to act on your behalf and create / post on channels.
* Set it for you team
* It should look like this `xoxp-ffff-ffffff-ffffff-fffffff`
## Starting the app
```bash
npm start
```
You should be live.
## TODO
- Write tests.
- Think use 1-click Slack integration button to get the tokens faster.
- Remember if channels exists with Slack's `channels.list` method instead if trying to create them each time.
- Features : mute, ask for Nexmo balance...
## Contributors & Contributing
- [Arthur Flam](https://twitter.com/ArthurFlam). Slack fan, into data science. Based in TLV.
I will be more than happy to receive pull requests and hear about bugs/issues :)
|
Java
|
UTF-8
| 2,887
| 2.234375
| 2
|
[] |
no_license
|
package com.dqsy.sparkvisualization.controller;
import com.alibaba.fastjson.JSONObject;
import com.dqsy.sparkvisualization.entity.*;
import com.dqsy.sparkvisualization.service.IPageService;
import com.dqsy.sparkvisualization.service.ITaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.*;
/**
* @author liusinan
* @version 1.0.0
* @ClassName SessionController.java
* @Description TODO
* @createTime 2020年03月29日 19:07:00
*/
@RestController
@RequestMapping("/pageshow")
@Slf4j
public class PageController {
@Autowired
private IPageService pageService;
@Autowired
private ITaskService taskService;
@RequestMapping(value = "/show", method = RequestMethod.GET, produces = "application/json")
public List<Tmp> show(Integer taskid) {
PageSplitConvertRate page = pageService.getPage(taskid);
String pageresult = page.getConvertRate();
String[] res = pageresult.split("\\|");
Map<String, Double> map = new HashMap<>();
for (int i = 0; i < res.length; i++) {
String[] tmp = res[i].split("=");
map.put(tmp[0], Double.valueOf(tmp[1]));
}
Task task = taskService.getTask(taskid);
List<Tmp> list = new ArrayList<>();
list.add(new Tmp("taskid", task.getTaskid()));
JSONObject taskParam = JSONObject.parseObject(task.getTaskParam());
String str = taskParam.getString("targetPageFlow");
str = str.substring(2, str.length() - 2);
System.out.println(str);
String[] strS = str.split(",");
for (int i = 0; i < strS.length - 1; i++) {
String name = strS[i] + "_" + strS[i + 1];
list.add(new Tmp(name, map.get(name)));
}
return list;
}
@RequestMapping(value = "/showJob", method = {RequestMethod.GET, RequestMethod.POST})
public Object showJob(Integer taskid) {
Task task = taskService.getTask(taskid);
if (pageService.getPage(taskid) == null || !task.getTaskParam().contains("targetPageFlow")) {
log.error("查看的不是page任务" + task.toString());
return null;
} else {
if (task.getTaskStatus().equals("FINISH")) {
log.info("被查看:" + task.toString());
return pageService.getAllPageList(taskid);
} else if (task.getTaskStatus().equals("CREATE")) {
log.error("未执行:" + task.toString());
} else if ((task.getTaskStatus().equals("KILLED"))) {
log.error("未成功:" + task.toString());
}
}
return null;
}
}
|
Java
|
UTF-8
| 738
| 1.96875
| 2
|
[] |
no_license
|
package com.smart;
import com.smart.service.UserService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.testng.annotations.Test;
public class TransactionTest {
static Logger logger = LogManager.getLogger(TransactionTest.class.getName());
@Test
public void testTransaction(){
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
logger.info("begining...");
UserService service = (UserService) ctx.getBean("userService");
service.logon("zhangsan");
logger.info("ending...");
}
}
|
C#
|
UTF-8
| 5,770
| 2.6875
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using System.Threading.Tasks;
using System.Net;
using Android.Gms.Maps.Model;
using CHARE_REST_API.JSON_Object;
namespace CHARE_System.Class
{
class MapHelper
{
private const string _GoogleDistanceMatrixAPIAddress = "https://maps.googleapis.com/maps/api/distancematrix/json";
private const string _GoogleDirectionAPIAddress = "https://maps.googleapis.com/maps/api/directions/json";
private const string _GoogleAPIKey = "AIzaSyBxXCmp-C6i5LwwRSTuvzIjD9_roPjJ4EI";
//?origin=3.2718236,101.6489234&destination=3.1161034,101.6392469&waypoints=optimize:true|3.209876,101.659176|3.302183,101.598181&key=AIzaSyBxXCmp-C6i5LwwRSTuvzIjD9_roPjJ4EI";";
public static List<LatLng> DecodePolylinePoint(string ePoints)
{
if (string.IsNullOrEmpty(ePoints))
return null;
var polyLatLng= new List<LatLng>();
char[] polychars = ePoints.ToCharArray();
int index = 0;
int currentLat = 0;
int currentLng = 0;
int next5bits;
int sum;
int shifter;
while (index < polychars.Length)
{
// calculate next latitude
sum = 0;
shifter = 0;
do
{
next5bits = (int)polychars[index++] - 63;
sum |= (next5bits & 31) << shifter;
shifter += 5;
} while (next5bits >= 32 && index < polychars.Length);
if (index >= polychars.Length)
break;
currentLat += (sum & 1) == 1 ? ~(sum >> 1) : (sum >> 1);
//calculate next longitude
sum = 0;
shifter = 0;
do
{
next5bits = (int)polychars[index++] - 63;
sum |= (next5bits & 31) << shifter;
shifter += 5;
} while (next5bits >= 32 && index < polychars.Length);
if (index >= polychars.Length && next5bits >= 32)
break;
currentLng += (sum & 1) == 1 ? ~(sum >> 1) : (sum >> 1);
LatLng p = new LatLng(Convert.ToDouble(currentLat) / 100000.0, Convert.ToDouble(currentLng) / 100000.0);
polyLatLng.Add(p);
}
return polyLatLng;
}
public static async Task<string> DownloadStringAsync(string strUri)
{
WebClient webclient = new WebClient();
string strResultData;
try
{
strResultData = await webclient.DownloadStringTaskAsync(new Uri(strUri));
Console.WriteLine(strResultData);
}
catch
{
strResultData = "Exception";
}
finally
{
webclient.Dispose();
webclient = null;
}
return strResultData;
}
public static async Task<string> DownloadStringAsync(TripDetails trips)
{
string waypoints = "";
foreach (TripPassenger tp in trips.TripPassengers)
{
waypoints += "|"+tp.originLatLng;
Console.WriteLine("=== waypoints " + waypoints);
}
string strUri = _GoogleDirectionAPIAddress + "?origin=" + trips.originLatLng + "&destination=" + trips.destinationLatLng +
"&waypoints=optimize:true" + waypoints + "&key=" + _GoogleAPIKey;
Console.WriteLine("=== uri " + strUri);
WebClient webclient = new WebClient();
string strResultData;
try
{
strResultData = await webclient.DownloadStringTaskAsync(new Uri(strUri));
Console.WriteLine(strResultData);
}
catch
{
strResultData = "Exception";
}
finally
{
webclient.Dispose();
webclient = null;
}
return strResultData;
}
public static async Task<string> DownloadStringAsync(TripDetails trips, string type)
{
string strUri = _GoogleDirectionAPIAddress + "?origin=" + trips.originLatLng + "&destination=" + trips.destinationLatLng +
"&waypoints=optimize:true&key=" + _GoogleAPIKey;
WebClient webclient = new WebClient();
string strResultData;
try
{
strResultData = await webclient.DownloadStringTaskAsync(new Uri(strUri));
Console.WriteLine(strResultData);
}
catch
{
strResultData = "Exception";
}
finally
{
webclient.Dispose();
webclient = null;
}
return strResultData;
}
public static string GoogleDirectionAPIAddress(string originLatLng, string destinationLatLng)
{
return _GoogleDirectionAPIAddress + "?origin=" + originLatLng + "&destination="
+ destinationLatLng + "&key=" + _GoogleAPIKey;
}
public static string GoogleDistanceMatrixAPIAddress(string originLatLng, string destinationLatLng)
{
return _GoogleDistanceMatrixAPIAddress + "?origins=" + originLatLng + "&destinations="
+ destinationLatLng + "&key=" + _GoogleAPIKey;
}
}
}
|
Swift
|
UTF-8
| 1,448
| 2.578125
| 3
|
[] |
no_license
|
//
// AxisGrid.swift
// ARMeasure
//
// Created by cc on 8/23/17.
// Copyright © 2017 Laan Labs. All rights reserved.
//
import Foundation
import SceneKit
class AxisGrid : SCNNode {
init(radius : CGFloat = 0.002, height : CGFloat = 0.3) {
super.init()
let x = SCNCapsule(capRadius: radius, height: height)
x.firstMaterial?.lightingModel = .constant
x.firstMaterial?.diffuse.contents = UIColor.red
let xn = SCNNode(geometry:x)
xn.position = SCNVector3(height/2.0, 0.0, 0.0)
xn.eulerAngles.z = 90.0 * Float.pi / 180.0
self.addChildNode(xn)
let y = SCNCapsule(capRadius: radius, height: height)
y.firstMaterial?.lightingModel = .constant
y.firstMaterial?.diffuse.contents = UIColor.green
let yn = SCNNode(geometry:y)
yn.position = SCNVector3(0.0, height/2.0, 0.0)
self.addChildNode(yn)
let z = SCNCapsule(capRadius: radius, height: height)
z.firstMaterial?.lightingModel = .constant
z.firstMaterial?.diffuse.contents = UIColor.blue
let zn = SCNNode(geometry:z)
zn.position = SCNVector3(0.0, 0.0, height/2.0)
zn.eulerAngles.x = 90.0 * Float.pi / 180.0
self.addChildNode(zn)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
Java
|
UTF-8
| 10,313
| 2.796875
| 3
|
[] |
no_license
|
package wsa.web;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.Predicate;
public class SimpleCrawler implements Crawler{
private volatile Set<URI> succDownload;
private volatile Set<URI> toDownload;
private volatile Set<URI> failDownload;
private final Predicate<URI> rule;
private volatile AsyncLoader loader;
private volatile boolean running;
private volatile ConcurrentLinkedQueue<Future<LoadResult>> tasks;
private volatile ConcurrentLinkedQueue<CrawlerResult> results;
private volatile Thread downloadThread;
public SimpleCrawler(Collection<URI> succDownload, Collection<URI> toDownload, Collection<URI> failDownload, Predicate<URI> rule) {
this.succDownload = new HashSet<>(succDownload);
this.toDownload = new HashSet<>(toDownload);
this.failDownload = new HashSet<>(failDownload);
if(rule!=null)
this.rule=rule;
else
this.rule=(s)->true;
loader=WebFactory.getAsyncLoader();
running=false;
tasks=new ConcurrentLinkedQueue<>();
results=new ConcurrentLinkedQueue<>();
}
/**
* Aggiunge un URI all'insieme degli URI da scaricare. Se però è presente
* tra quelli già scaricati, quelli ancora da scaricare o quelli che sono
* andati in errore, l'aggiunta non ha nessun effetto. Se invece è un nuovo
* URI, è aggiunto all'insieme di quelli da scaricare.
*
* @param uri un URI che si vuole scaricare
* @throws IllegalStateException se il Crawler è cancellato
*/
@Override
public void add(URI uri) throws IllegalStateException{
if(!loader.isShutdown()){
Set<URI> allURIs = new HashSet<>(succDownload);
allURIs.addAll(toDownload);
allURIs.addAll(failDownload);
if(!allURIs.contains(uri))
toDownload.add(uri);
}
else
throw new IllegalStateException();
}
/**
* Inizia l'esecuzione del Crawler se non è già in esecuzione e ci sono URI
* da scaricare, altrimenti l'invocazione è ignorata. Quando è in esecuzione
* il metodo isRunning ritorna true.
*
* @throws IllegalStateException se il Crawler è cancellato
*/
@Override
public void start() throws IllegalStateException{
if (!loader.isShutdown()) {
if(!running) {
running = true;
downloadThread = new Thread(() -> {
while (running && toDownload.size() > 0) {
Iterator<URI> uris = toDownload.iterator();
while (uris.hasNext()) {
URI u = uris.next();
boolean tested = rule.test(u);
Exception ex = null;
try {
URL url = u.toURL();
tasks.add(loader.submit(url));
} catch (Exception e) {
ex = e;
results.add(new CrawlerResult(u, tested, null, null, ex));
uris.remove();
toDownload.remove(u);
failDownload.add(u);
}
}
while (!tasks.isEmpty()) {
Future<LoadResult> t = tasks.poll();
LoadResult res = null;
URI u = null;
boolean tested = false;
Exception ex = null;
try {
res = t.get(2000, TimeUnit.MILLISECONDS);
if (res.exc == null) {
u = res.url.toURI();
tested = rule.test(u);
ex = res.exc;
List<String> resLinks = res.parsed.getLinks();
List<String> failLinks = new ArrayList<>(resLinks);
List<URI> absLinks = new ArrayList<>();
Iterator<String> links = resLinks.iterator();
if (tested) {
while (links.hasNext()) {
try {
String s = links.next();
URI var = URI.create(s);
URI newURI = u.resolve(var);
URL url = newURI.toURL();
absLinks.add(newURI);
links.remove();
failLinks.remove(s);
add(newURI);
} catch (Exception e) {
System.out.println(u);
ex = e;
links.remove();
toDownload.remove(u);
failDownload.add(u);
}
}
}
if (toDownload.remove(u))
succDownload.add(u);
results.add(new CrawlerResult(u, tested, absLinks, failLinks, ex));
}
} catch (URISyntaxException e) {
ex = e;
results.add(new CrawlerResult(u, tested, null, null, ex));
} catch (TimeoutException | ExecutionException | InterruptedException e) {
tasks.add(t);
}
}
}
});
downloadThread.setDaemon(true);
downloadThread.start();
}
} else
throw new IllegalStateException();
}
/**
* Sospende l'esecuzione del Crawler. Se non è in esecuzione, ignora
* l'invocazione. L'esecuzione può essere ripresa invocando start. Durante
* la sospensione l'attività del Crawler dovrebbe essere ridotta al minimo
* possibile (eventuali thread dovrebbero essere terminati).
*
* @throws IllegalStateException se il Crawler è cancellato
*/
@Override
public void suspend() throws IllegalStateException{
if(!loader.isShutdown())
if(running) {
running = false;
downloadThread.interrupt();
}
else
throw new IllegalStateException();
}
/**
* Cancella il Crawler per sempre. Dopo questa invocazione il Crawler non
* può più essere usato. Tutte le risorse devono essere rilasciate.
*/
@Override
public void cancel() {
suspend();
loader.shutdown();
}
/**
* Ritorna il risultato relativo al prossimo URI. Se il Crawler non è in
* esecuzione, ritorna un Optional vuoto. Non è bloccante, ritorna
* immediatamente anche se il prossimo risultato non è ancora pronto.
*
* @return il risultato relativo al prossimo URI scaricato
* @throws IllegalStateException se il Crawler è cancellato
*/
@Override
public Optional<CrawlerResult> get() throws IllegalStateException{
if(!loader.isShutdown()){
if(running) {
while (results.isEmpty())
try {
Thread.sleep(10);
} catch (InterruptedException e) {}
return Optional.of(results.poll());
}
else
return Optional.empty();
}
else
throw new IllegalStateException();
}
/**
* Ritorna l'insieme di tutti gli URI scaricati, possibilmente vuoto.
*
* @return l'insieme di tutti gli URI scaricati (mai null)
* @throws IllegalStateException se il Crawler è cancellato
*/
@Override
public Set<URI> getLoaded() throws IllegalStateException{
if(!loader.isShutdown())
return succDownload;
else
throw new IllegalStateException();
}
/**
* Ritorna l'insieme, possibilmente vuoto, degli URI che devono essere
* ancora scaricati. Quando l'esecuzione del crawler termina normalmente
* l'insieme è vuoto.
*
* @return l'insieme degli URI ancora da scaricare (mai null)
* @throws IllegalStateException se il Crawler è cancellato
*/
@Override
public Set<URI> getToLoad() throws IllegalStateException{
if(!loader.isShutdown())
return toDownload;
else
throw new IllegalStateException();
}
/**
* Ritorna l'insieme, possibilmente vuoto, degli URI che non è stato
* possibile scaricare a causa di errori.
*
* @return l'insieme degli URI che hanno prodotto errori (mai null)
* @throws IllegalStateException se il crawler è cancellato
*/
@Override
public Set<URI> getErrors() throws IllegalStateException{
if(!loader.isShutdown())
return failDownload;
else
throw new IllegalStateException();
}
/**
* Ritorna true se il Crawler è in esecuzione.
*
* @return true se il Crawler è in esecuzione
*/
@Override
public boolean isRunning() {
return running;
}
/**
* Ritorna true se il Crawler è stato cancellato. In tal caso non può più
* essere usato.
*
* @return true se il Crawler è stato cancellato
*/
@Override
public boolean isCancelled() {
return loader.isShutdown();
}
}
|
SQL
|
UTF-8
| 2,790
| 3.421875
| 3
|
[] |
no_license
|
-- Gera relatorio em HTML de FK sem indice
set echo off
set linesize 255
set trims on
set trimo on
set feedback off
set pagesize 0
set arraysize 1
prompt Aguarde a obtencao das FKs sem indices...
set termout off
spool fknoindex.htm
prompt <HTML><HEAD><TITLE>FKs sem Indices</TITLE>
prompt <STYLE type="text/css">
select 'h1 {' from dual union all
select ' font-family: Verdana, Arial;' from dual union all
select ' font-size: 18px;' from dual union all
select ' font-weight : bold; ' from dual union all
select ' color: silver; ' from dual union all
select ' margin: 50px 0px 50px 20px;' from dual union all
select ' }' from dual union all
select '' from dual union all
select '' from dual union all
select ' td {' from dual union all
select ' font-family: Tahoma, verdana, arial;' from dual union all
select ' font-size: 10px;' from dual union all
select ' font-weight: normal;' from dual union all
select ' }' from dual union all
select '' from dual union all
select ' th { font-family: verdana, arial;' from dual union all
select ' font-size: 10px;' from dual union all
select ' font-weight: bold;' from dual union all
select ' text-align: left;' from dual union all
select ' vertical-align : top;' from dual union all
select ' background-color: silver;' from dual union all
select ' color: white;' from dual union all
select ' }' from dual;
prompt </STYLE></HEAD>
prompt <BODY>
set heading off
select '<h1>FKs sem indices (' || name || ') ' || to_char(sysdate,'YYYY.MON.DD HH:MI:SS') || '</h1>'
from v$database;
prompt <TABLE border="1" cellspacing="0" cellpadding="3">
prompt <TR><TH>Owner pai</TH><TH>Pai</th><th>Owner filha</th><th>Filha</th><th>Nome FK</th><th>Coluna</th></tr>
select '<tr><td>' || rc.owner || '</td><td>' || chr(10) ||
rc.table_name || '</td><td>' || acc.owner || '</td><td>' || chr(10) ||
acc.table_name || '</td><td>' || acc.constraint_name || '</td><td>' || chr(10) ||
acc.column_name ||'['||acc.position||']</td></tr>'
from dba_constraints rc, dba_cons_columns acc, dba_constraints ac
where ac.constraint_name = acc.constraint_name
and ac.owner = acc.owner
and ac.constraint_type = 'R'
and rc.constraint_name = ac.r_constraint_name
and rc.owner = ac.r_owner
and (acc.owner, acc.table_name, acc.column_name, acc.position) in
(select acc.owner, acc.table_name, acc.column_name, acc.position
from dba_cons_columns acc, dba_constraints ac
where ac.constraint_name = acc.constraint_name
and ac.constraint_type = 'R'
MINUS
select table_owner, table_name, column_name, column_position
from dba_ind_columns)
order by rc.owner, rc.table_name, acc.owner, acc.table_name, acc.column_name, acc.position;
prompt </table></body></html>
spool off;
set termout on
prompt Terminado!
host iexplore fknoindex.htm
|
Java
|
UTF-8
| 569
| 1.804688
| 2
|
[
"Apache-2.0"
] |
permissive
|
package com.taobao.api.response;
import com.taobao.api.internal.mapping.ApiField;
import com.taobao.api.domain.Sku;
import com.taobao.api.TaobaoResponse;
/**
* TOP API: taobao.item.sku.get response.
*
* @author auto create
* @since 1.0, null
*/
public class ItemSkuGetResponse extends TaobaoResponse {
private static final long serialVersionUID = 6565889194722457545L;
/**
* Sku
*/
@ApiField("sku")
private Sku sku;
public void setSku(Sku sku) {
this.sku = sku;
}
public Sku getSku( ) {
return this.sku;
}
}
|
C++
|
UTF-8
| 393
| 2.859375
| 3
|
[] |
no_license
|
//
// Created by user on 1/13/2020.
//
#ifndef GAMMA_SOUP_H
#define GAMMA_SOUP_H
#include <string>
#include "FoodFactory.h"
class Soup : public FoodFactory
{
public:
int getPrice(std::string type) const override {
if (type == "thai") return thai;
if (type == "visitor") return visitor;
}
private:
int thai = 60;
int visitor = 120;
};
#endif //GAMMA_SOUP_H
|
Python
|
UTF-8
| 1,983
| 3.5
| 4
|
[] |
no_license
|
from warehouse import Warehouse
from sales import Sales
from finance import Finance
class UserInterface:
def __init__(self):
self.warehouse = Warehouse()
self.sales = Sales()
self.finance = Finance()
def add_new_bike(self, model, price, colour, size, gender, quantity):
self.warehouse.add_item(model, price, colour, size, gender, quantity)
def display_stock(self):
self.warehouse.print_all_items()
# def add_bike_to_cart(self,model,quantity):
# if self.warehouse.can_buy(model,quantity) :
# self.sales.add_to_cart(model,quantity)
def add_to_cart(self):
bike_model = input("Enter bike model:")
bike_index = self.warehouse.find_bike_by_model(bike_model)
if(bike_index == -1):
print("We don't have that model")
else:
bike = self.warehouse.stock[bike_index]
amount = int(input("How many of bikes would you buy?"))
if(amount > bike.quantity):
print("We don't have enough of that model")
else:
self.sales.add_to_cart(bike, amount)
def make_purchase(self):
cart = self.sales.get_cart()
if(len(cart) == 0):
print("No items in cart!")
else:
for bike, amount in cart:
self.warehouse.decrease_quantity_by(bike.model, amount)
report = self.finance.create_report(cart)
print(report)
self.sales.make_purchase()
def display_cart(self):
self.sales.display_cart()
def display_reports(self):
self.finance.display_reports()
def empty_the_cart(self):
self.sales.empty_the_cart()
# if __name__ == '__main__':
# ui = UserInterface #create a concrete object
# if choice =2 '1':
# model = input("enter")
#
# ui.add_new_bike(model,price,colour,size,gender,quantity)
#
# if choice == '2'
# ui.add_bike_to_cart()
|
PHP
|
UTF-8
| 2,458
| 3.125
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace Reborn\Console;
use Symfony\Component\Console\Command\Command as SfCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
/**
* Class Compile Command for Memeory Reduce
*
* @package Reborn\Console
* @author Myanmar Links Professional Web Development Team
**/
class CompileCommand extends SfCommand
{
/**
* Configures the current command.
*/
protected function configure()
{
$this->setName('compile')
->setDescription('PHP Class File Compiler for Performance');
}
/**
* Executes the current command.
*
*
* @param InputInterface $input An InputInterface instance
* @param OutputInterface $output An OutputInterface instance
*
* @return null|integer null or 0 if everything went fine, or an error code
*/
protected function execute(InputInterface $input, OutputInterface $output)
{
$output->writeln("<info>--- Start Compiling ---</info>");
$outputfile = STORAGES.'compile.php';
if (file_exists($outputfile)) {
@unlink($outputfile);
}
$files = require APP.'config/compile_lists.php';
if (!$handle = fopen($outputfile, 'w')) {
throw new \RuntimeException(
"Unable to open {$outputfile} for writing"
);
}
fwrite($handle, "<?php\n");
$output->writeln('Compiling classes');
foreach ($files as $file) {
$output->writeln("Written for {$file}");
fwrite($handle, $this->getContent($file) . "\n");
}
fclose($handle);
$output->writeln("<info>Finish compiled and written to {$outputfile}</info>");
}
/**
* Get Class Content from given file
*
* @param string $file
* @return string
**/
protected function getContent($file)
{
if (!is_readable($file)) {
throw new \RuntimeException("Cannot open {".$file."} for reading");
}
// Get content without comment and whitespace
$content = php_strip_whitespace($file);
if (substr($content, 0, 5) == "<?php") {
$content = substr($content, 5);
}
if (false === strpos($content, 'namespace ') and
$content !== ''
) {
$content = "namespace {\n" . $content . "\n}\n";
}
return $content;
}
}
|
C#
|
UTF-8
| 3,876
| 2.5625
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
using System;
using System.Data.Entity;
using System.Net;
using System.Threading.Tasks;
using System.Web.Mvc;
using OneAspNetSample.Models;
namespace OneAspNetSample.Controllers
{
public class ProductController : Controller
{
private OneAspNetSampleContext db = new OneAspNetSampleContext();
// GET: /Product/
public async Task<ActionResult> Index()
{
return View(await db.Product.ToListAsync());
}
// GET: /Product/Details/5
public async Task<ActionResult> Details(Guid? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Product product = await db.Product.FindAsync(id);
if (product == null)
{
return HttpNotFound();
}
return View(product);
}
// GET: /Product/Create
public ActionResult Create()
{
return View();
}
// POST: /Product/Create
// To protect from over posting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
//
// Example: public ActionResult Update([Bind(Include="ExampleProperty1,ExampleProperty2")] Model model)
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(Product product)
{
if (ModelState.IsValid)
{
product.Id = Guid.NewGuid();
db.Product.Add(product);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(product);
}
// GET: /Product/Edit/5
public async Task<ActionResult> Edit(Guid? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Product product = await db.Product.FindAsync(id);
if (product == null)
{
return HttpNotFound();
}
return View(product);
}
// POST: /Product/Edit/5
// To protect from over posting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
//
// Example: public ActionResult Update([Bind(Include="ExampleProperty1,ExampleProperty2")] Model model)
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit(Product product)
{
if (ModelState.IsValid)
{
db.Entry(product).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(product);
}
// GET: /Product/Delete/5
public async Task<ActionResult> Delete(Guid? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Product product = await db.Product.FindAsync(id);
if (product == null)
{
return HttpNotFound();
}
return View(product);
}
// POST: /Product/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<ActionResult> DeleteConfirmed(Guid id)
{
Product product = await db.Product.FindAsync(id);
db.Product.Remove(product);
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
}
|
Go
|
UTF-8
| 1,895
| 2.9375
| 3
|
[
"MIT"
] |
permissive
|
package boost
import (
"time"
"github.com/rjansen/boost"
testify "github.com/stretchr/testify/mock"
)
func NewClientPoolMock() *ClientPoolMock {
return new(ClientPoolMock)
}
//ClientPoolMock is a mock for a cache client pool
type ClientPoolMock struct {
testify.Mock
}
//Get returns a cache Client instance
func (m *ClientPoolMock) Get() (boost.Client, error) {
args := m.Called()
result := args.Get(0)
if result != nil {
return result.(boost.Client), args.Error(1)
}
return nil, args.Error(1)
}
//Close finalizes the pool instance
func (m *ClientPoolMock) Close() error {
args := m.Called()
return args.Error(0)
}
//NewClientMock creates a new mock instance of the cache client component
func NewClientMock() *ClientMock {
return new(ClientMock)
}
//MockClient is a mock client for cache system
type ClientMock struct {
testify.Mock
}
//Get reads the value associated with the provided key
func (m *ClientMock) Get(key string) ([]byte, error) {
args := m.Called(key)
result := args.Get(0)
if result != nil {
return result.([]byte), args.Error(1)
}
return nil, args.Error(1)
}
//Add inserts a new item in the cache, Add throws error if the provided key was already defined
func (m *ClientMock) Add(key string, expires time.Duration, item []byte) error {
args := m.Called(key, expires, []byte(item))
return args.Error(0)
}
//Set inserts a new item in the cache if the key is new or modifies the value associated with the provided key
func (m *ClientMock) Set(key string, expires time.Duration, item []byte) error {
args := m.Called(key, expires, []byte(item))
return args.Error(0)
}
//Delete removes the item associated with the provided key
func (m *ClientMock) Delete(key string) error {
args := m.Called(key)
return args.Error(0)
}
//Close finalizes the client instance
func (m *ClientMock) Close() error {
args := m.Called()
return args.Error(0)
}
|
C++
|
UTF-8
| 1,476
| 2.640625
| 3
|
[] |
no_license
|
#ifndef COMSTRUCTIBLE_H
#define COMSTRUCTIBLE_H
#include <vector>
#include <map>
#include <SFML/Graphics.hpp>
#include <string>
#include <iostream>
#include <sstream>
#include <queue>
#include <set>
#include "Enum.hpp"
#include "Cible.hpp"
/*
Constructible
/\ |
| |
| |
Tour "mur" et "flag"
| |
| |
"tour" "piege" */
class Case;
class Effet;
class Constructible : public Cible
{
public :
Constructible();
virtual ~Constructible();
// geteurs
virtual unsigned int getTempsDeConstructionDeBase() const { return tempsDeConstructionDeBase;};
// seteur
virtual void setTempsDeConstructionDeBase ( const unsigned int p_temps);
virtual void arriveEnJeu (Case *p_position);
virtual void removeEffetPropre (Effet* p_effet);
virtual void addEffetPropre (Effet* p_effet);
virtual void ajoutCibleAuSelecteur (SelecteurCible* p_selecteur);
virtual void removeCibleAuSelecteur (SelecteurCible* p_selecteur);
virtual void QuiEstLa () { std::cout << "Constructible" << std::endl;};
protected :
unsigned int tempsDeConstructionDeBase;
};
#endif COMSTRUCTIBLE_H
|
C#
|
UTF-8
| 1,025
| 2.890625
| 3
|
[
"Apache-2.0"
] |
permissive
|
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using MiniJSON;
public static class Localization
{
public static SystemLanguage Language
{
get
{
return _language;
}
set
{
_language = value;
ChangeLanguage(_language);
}
}
public static string Get(string key)
{
return _dictionary[key];
}
private static SystemLanguage _language;
private static Dictionary<string, string> _dictionary;
static Localization()
{
var lang = Application.systemLanguage;
if(lang == SystemLanguage.Bulgarian || lang == SystemLanguage.English)
Language = lang;
else
Language = SystemLanguage.English;
}
private static void ChangeLanguage(SystemLanguage lang)
{
var jsonString = (Resources.Load("Localization/" + lang.ToString()) as TextAsset).text;
var dict = Json.Deserialize(jsonString) as Dictionary<string,object>;
_dictionary = new Dictionary<string, string>();
foreach(var item in dict)
{
_dictionary.Add(item.Key, (string)item.Value);
}
}
}
|
Python
|
UTF-8
| 2,617
| 2.765625
| 3
|
[] |
no_license
|
# pymodbus code based on the example from http://www.solarpoweredhome.co.uk/
from pymodbus.client.sync import ModbusSerialClient as ModbusClient
from time import sleep
import datetime
import numpy as np
import pandas as pd
import csv
import os
client = ModbusClient(method = 'rtu', port = '/dev/ttyUSB0', baudrate = 115200)
client.connect()
while True:
#doesn't need to happen every time, just at midnight
fileName = '/home/pi/EPSolar_Tracer/data/tracerData'+str(datetime.date.today())+'.csv'
result = client.read_input_registers(0x3100,16,unit=1)
solarVoltage = float(result.registers[0] / 100.0)
solarCurrent = float(result.registers[1] / 100.0)
solarPowerL = float(result.registers[2] / 100.0)
solarPowerH = float(result.registers[3] / 100.0)
batteryVoltage = float(result.registers[4] / 100.0)
chargeCurrent = float(result.registers[5] / 100.0)
chargePowerL = float(result.registers[6] / 100.0)
chargePowerH = float(result.registers[7] / 100.0)
loadVoltage = float(result.registers[8] / 100.0)
loadCurrent= float(result.registers[9] / 100.0)
loadPower= float(result.registers[10] / 100.0)
result = client.read_input_registers(0x311A,2,unit=1)
batteryPercentage = float(result.registers[0] / 100.0)
dateTimeNow = datetime.datetime.now()
currentTime = dateTimeNow.time()
currentDate = datetime.date.today() #updated but not pushed - check that it is correct and works
# Do something with the data
'''
print("PV Voltage: " + str(solarVoltage))
print("PV Current" + str(solarCurrent))
print("Battery Voltage: " + str(batteryVoltage))
print("Charge Current: " + str(chargeCurrent))
print("Load Current" + str(loadCurrent))
print("Load Power: " + str(loadPower))
print("Local time: " + str(currentDate))
'''
newDF = pd.DataFrame(data={
"PV voltage": [solarVoltage],
"PV current": [solarCurrent],
"PV power L": [solarPowerL],
"PV power H": [solarPowerH],
"battery voltage":[batteryVoltage],
"charge current":[chargeCurrent],
"charge power L":[chargePowerL],
"charge power H": [chargePowerH],
"load voltage":[loadVoltage],
"load current": [loadCurrent],
"load power": [loadPower],
"battery percentage": [batteryPercentage],
"time": [currentTime],
"date" : [currentDate]})
# check if the file already exists
try:
with open(fileName) as csvfile:
df = pd.read_csv(fileName)
print(df)
df = df.append(newDF, ignore_index = True)
df.to_csv(fileName, sep=',',index=False)
#print("It exists!")
except:
print("first file of the day!")
newDF.to_csv(fileName, sep=',',index=False)
#runs every minute
sleep(60)
client.close()
|
Markdown
|
UTF-8
| 4,443
| 2.78125
| 3
|
[] |
no_license
|
想打造 New Relic 那样漂亮的实时监控系统我们只需要 InfluxDB/collectd/Grafana 这三个工具,这三个工具的关系是这样的:
> 采集数据(collectd)-> 存储数据(InfluxDB) -> 显示数据(Grafana)。
- InfluxDB 是 Go 语言开发的一个开源分布式时序数据库,非常适合存储指标、事件、分析等数据,看版本号(v0.8.8)就知道这个项目还很年轻;
- collectd 就不用介绍了吧,C 语言写的一个系统性能采集工具;
- Grafana 是纯 Javascript 开发的前端工具,用于访问 InfluxDB,自定义报表、显示图表等。
## 安装 InfluxDB
InfluxDB 是 Go 写的,不依赖任何其他包或库,很干净。安装很容易:
```shell
wget https://dl.influxdata.com/influxdb/releases/influxdb_1.3.5_amd64.deb
sudo dpkg -i influxdb_1.3.5_amd64.deb
```
## 启动 InfluxDB:
```text
sudo /etc/init.d/influxdb start
Setting ulimit -n 65536
Starting the process influxdb [ OK ]
influxdb process was started [ OK ]
```
启动后打开 web 管理界面 http://192.168.1.1:8083/ 默认用户名和密码是 root 和 root. InfluxDB 的 Web 管理界面端口是 8083,HTTP API 监听端口是 8086,如果需要更改这些默认设定,修改 InfluxDB 的配置文件重启就可以了。
在刚安装好的 InfluxDB 上创建一个名为 collectd 的数据库,可以用命令行创建,也可以用 Web 管理界面操作:
```shell
curl "http://192.168.2.183:8086/db?u=root&p=root" -d "{\"name\": \"collectd\"}"
```
## 安装 collectd
```shell
sudo apt-get install collectd
```
配置 collectd 为客户端,收集到数据后直接发给 InfluxDB:
`/etc/collectd/collectd.conf`
```text
...
LoadPlugin network
...
<Plugin network>
Server "192.168.2.183" "25826"
</Plugin>
...
```
## 重启 collectd:
```shell
sudo /etc/init.d/collectd restart
```
InfluxDB 现在自带一个 collectd 插件来获取 collectd 客户端发来的数据,以前可没这么方便哦,0.8.4 版本以前只能通过 influxdb-collectd-proxy 这样的第三方程序来连接 collectd 和 InfluxDB. 如果你检查一下服务器上打开的端口就会发现 influxdb 插件启动了一个 25826 端口,如果发现 InfluxDB 数据库里没有(收集到)数据,务必检查这个 25826 端口是否正常启动了:
```shell
sudo netstat -tupln
```
InfluxDB 自带的 collectd 插件默认是关闭的,需要手动配置打开 enabled = true,并填上 database = “collectd” 这一行,这里的 “collectd” 就是我们上面创建的那个数据库,更改配置后记得重启 InfluxDB:
- `/opt/influxdb/current/config.toml`
- `/opt/influxdb/shared/config.toml`
现在 InfluxDB 已经准备好接受和处理 collectd 传来的数据了。用命令行或者 Web 管理界面验证一下数据库里是否有数据:
```shell
curl -G 'http://192.168.2.183:8086/db/collectd/series?u=root&p=root&q=list+series&pretty=true'
```
## 安装 Grafana
下载 grafana 后解压发到 web 服务器上就可用。这里省去配置 Nginx/Apache 之类的麻烦,直接用最简单的 Web 服务器 python -m SimpleHTTPServer 驱动:
```text
$ wget http://grafanarel.s3.amazonaws.com/grafana-1.9.1.tar.gz
$ tar xzvf grafana-1.9.1.tar.gz
$ cd grafana-1.9.1.tar.gz
$ cp config.sample.js config.js
$ vi config.js
...
// InfluxDB example setup (the InfluxDB databases specified need to exist)
datasources: {
influxdb: {
type: 'influxdb',
url: "http://192.168.2.183:8086/db/collectd",
username: 'root',
password: 'root',
},
...
},
...
$ sudo python -m SimpleHTTPServer
```
用浏览器访问 Grafana,这里的默认端口是 8000。
# Troubleshooting
下面有多个网友评论提到修改配置文件后端口 25826 也无法起来的问题,和 influxdb 启动时候使用的是哪个配置文件有关,用 ps aux | grep influxdb 可以看到当前 influxdb 使用的是哪个配置文件:
```text
$ sudo vi /opt/influxdb/current/config.toml
$ sudo vi /opt/influxdb/shared/config.toml
$ ps aux | grep influxdb
influxdb 668 19.1 8.1 2655964 82336 ? Sl Mar31 6375:52 /usr/bin/influxdb -pidfile /opt/influxdb/shared/influxdb.pid -config /opt/influxdb/shared/config.toml
...
```
两个配置文件 `/opt/influxdb/current/config.toml` 和 `/opt/influxdb/shared/config.toml` 的确很坑爹~
|
JavaScript
|
UTF-8
| 667
| 2.90625
| 3
|
[] |
no_license
|
var randomBetween = require('./randomBetween');
module.exports = function(canvas, opt) {
var ctx = canvas.getContext('2d');
for(var i = 0; i < 8; i++) {
ctx.beginPath();
ctx.moveTo(randomBetween(-100, opt.width + 100), randomBetween(-100, opt.height + 100));
ctx.bezierCurveTo(randomBetween(-100, opt.height + 100), randomBetween(-100, opt.height + 100), randomBetween(-100, opt.width + 100), randomBetween(-100, opt.height + 100), randomBetween(-100, opt.width + 100), randomBetween(-100, opt.height + 100));
ctx.fillStyle = ctx.strokeStyle = '#939598';
ctx.lineWidth = randomBetween(2, 5);
ctx.stroke();
}
return canvas;
};
|
Ruby
|
UTF-8
| 1,185
| 3.234375
| 3
|
[
"Unlicense",
"LicenseRef-scancode-public-domain"
] |
permissive
|
module Jsus
#
# Packager is a plain simple class accepting several source files
# and joining their contents.
#
# It uses Container for storage which means it automatically sorts sources.
#
class Packager
# Container with source files
attr_accessor :container
#
# Inits packager with the given sources.
#
# @param [Container, Array] sources source files
# @api public
def initialize(sources)
@sources = case sources
when Array
Container.new(*sources)
else
sources
end
end
# @return [Jsus::Container] container with source files
# @api public
def sources
@sources
end
# Concatenates all the sources' contents into a single string.
# If given a filename, outputs into a file.
#
# @param [String, nil] output_file output file name
# @return [String] concatenated source files
# @api public
def pack(output_file = nil)
result = sources.map {|s| s.source }.join("\n")
if output_file
FileUtils.mkdir_p(File.dirname(output_file))
File.open(output_file, "w") {|f| f << result }
end
result
end
end
end
|
TypeScript
|
UTF-8
| 1,844
| 2.578125
| 3
|
[
"CC0-1.0"
] |
permissive
|
/* eslint-disable import/prefer-default-export, import/no-cycle */
import {
BackboneElement,
ElementDefinition,
FhirList,
IStructureDefinitionSnapshot,
FhirType
} from "../internal";
@FhirType("StructureDefinitionSnapshot", "BackboneElement")
export class StructureDefinitionSnapshot extends BackboneElement {
static readonly baseType: string = "FHIR.BackboneElement";
static readonly namespace: string = "FHIR";
static readonly typeName: string = "StructureDefinition.Snapshot";
static readonly primaryCodePath: string | null = null;
@FhirList("ElementDefinition")
public element?: Array<ElementDefinition>;
public static parse(
json: IStructureDefinitionSnapshot,
providedInstance: StructureDefinitionSnapshot = new StructureDefinitionSnapshot()
): StructureDefinitionSnapshot {
const newInstance: StructureDefinitionSnapshot = BackboneElement.parse(json, providedInstance);
if (json.element !== undefined) {
newInstance.element = json.element.map((x) => ElementDefinition.parse(x));
}
return newInstance;
}
public static isStructureDefinitionSnapshot(input?: unknown): input is StructureDefinitionSnapshot {
const castInput = input as StructureDefinitionSnapshot;
return !!input && castInput.getTypeName && castInput.getTypeName() === "StructureDefinitionSnapshot";
}
public toJSON(): IStructureDefinitionSnapshot {
const result: IStructureDefinitionSnapshot = super.toJSON();
if (this.element) {
result.element = this.element.map((x) => x.toJSON());
}
return result;
}
public clone(): StructureDefinitionSnapshot {
return StructureDefinitionSnapshot.parse(this.toJSON());
}
public getTypeName(): string {
return "StructureDefinitionSnapshot";
}
}
/* eslint-enable import/prefer-default-export, import/no-cycle */
|
Python
|
UTF-8
| 525
| 3.890625
| 4
|
[] |
no_license
|
# repeat last item in short list to equalize to lists
short = [x for x in range(8)]
llong = [y for y in range(12)]
"""
for i in range(len(short), len(llong)):
short.append(short[-1])
print short
print llong
"""
def equalize(one_list, two_list):
if len(one_list) > len(two_list):
short = two_list
llong = one_list
else:
short = one_list
llong = two_list
for i in range(len(short), len(llong)):
short.append(short[-1])
equalize(short, llong)
print short
print llong
|
Java
|
UTF-8
| 1,609
| 3.46875
| 3
|
[] |
no_license
|
package algorithms.search;
import java.util.PriorityQueue;
public class BreadthFirstSearch extends ASearchingAlgorithm{
/**
* searching in specific problem according to bfs algorithm
* @param s problem we want to solve
* @return goal state of the problem
*/
@Override
public AState search(ISearchable s) throws Exception {
if (s == null){
throw new Exception("ISearchable should not be null");
}
initialize(s);
AState current = s.getStartState();
openList.add(current); // add start state to the queue
s.setVisited(current);
while (!openList.isEmpty()) {
AState popped = popOpenList(); // pop the first state in the queue
AState.setOrder(AState.getOrder() + 1);
if (popped.samePosition(s.getGoalState()))
return popped; // there is no need to continue
for (AState state : s.getAllSuccessors(popped)) {
if (!s.isVisited(state)) {
state.setCameFrom(popped);
updateCost(state);
openList.add(state);
s.setVisited(state);
}
}
}
return null;
}
/**
* update cost of state to 0
* @param state the state we want to update
*/
protected void updateCost(AState state){
state.setCost(AState.getOrder() + 1);
}
/**
* algorithm name
* @return breadth first search
*/
@Override
public String getName() {
return "BreadthFirstSearch";
}
}
|
Markdown
|
UTF-8
| 3,626
| 2.703125
| 3
|
[] |
no_license
|
登录 [短信控制台](https://console.cloud.tencent.com/sms),在左侧导航栏选择**统计分析**>**国际/港澳台短信**,您可以查看指定时间段内的国际/港澳台发送详情、下发记录以及失败分析等。单击各页面的**导出数据**可下载对应数据表。
## 数据总览
在**数据总览**页面,您可以指定应用或模板精确筛选查看今天、昨天、最近7天、最近30天或指定时间段的短信发送详情。趋势图与数据表均支持从请求量、成功量、计费条数和成功率多个维度统计数据。

- **请求量**:即短信提交总量,指业务侧提交的短信条数,包括提交成功、提交失败。
- **成功量**:即短信提交成功量,指发送状态为“成功提交”的短信条数。
- **计费条数**:对于提交成功的短信
- 如果为国际纯英文,单条短信长度不超过160字时,按照1条短信计费;超过160字即为长短信时,按153字/条分隔成多条计费(例如,短信长度为320字,则按照153字/153字/14字分隔成3条计费)。
- 如果是非纯英文,单条短信长度不超过70字时,按照1条短信计费;超过70字即为长短信时,按67字/条分隔成多条计费(例如,短信长度为150字,则按照67字/67字/16字分隔成3条计费)。
## 短信记录
在**短信记录**页面,您可以指定手机号、应用或模板精确筛选查看单个手机号在指定时间段的短信发送记录和回复记录。
- 发送记录数据表支持从手机号、发送内容、字数 | 拆分条数、短信类型和发送状态等多个维度统计数据。发送成功的国际/港澳台记录**备注**栏会记录用户接听状态。发送失败的国际/港澳台记录无发起时间、接听时间和结束时间信息,**备注**栏会记录失败原因。

- 回复记录数据表支持从手机号、回复内容、回复时间以及状态等多个维度统计数据。

## 失败分析
在**失败分析**页面,您可以指定应用筛选查看今天、昨天、最近7天、最近30天或指定时间段的短信发送失败详情和所占比例。
数据表支持从错误码、失败原因、失败数量和所占比例多个维度统计数据。

## 国家(地区)统计
在**国家(地区)统计**页面,您可以指定应用筛选查看今天、昨天、最近7天、最近30天或指定时间段的短信回执详情和回执失败分析。
- 短信回执详情数据表支持从请求量、成功量、发送成功率、计费条数、 请求量占比等多个维度统计数据。
- 回执失败分析数据表支持从失败原因、失败数量以及所占比例维度统计数据。

## 点击统计
在**点击统计**页面,输入短链接名称/短链接名称后,您可以筛选查看今天、昨天、最近7天、最近30天或指定时间段的点击数据。
数据表支持从短信发送人数、短链接点击人数和短链接点击率多个维度统计数据。

如有任何疑问,请联系 [腾讯云短信小助手](https://tccc.qcloud.com/web/im/index.html#/chat?webAppId=8fa15978f85cb41f7e2ea36920cb3ae1&title=Sms),将有专人为您解答。
|
C++
|
UTF-8
| 898
| 3.03125
| 3
|
[] |
no_license
|
#include<iostream>
#include "list.h"
using namespace std;
int main(void)
{
/* List<int> l1;
l1.push_front(5);
l1.push_front(4);
l1.push_front(3);
l1.push_front(2);
l1.push_front(1);
l1.push_back(1);
l1.push_back(2);
l1.push_back(3);
l1.push_back(4);
l1.push_back(5);
cout<<l1.front()<<endl;
cout<<l1.back()<<endl;
cout<<l1.empty()<<endl;
cout<<l1.pop_front()<<endl;
cout<<l1.pop_front()<<endl;
cout<<l1.pop_front()<<endl;
cout<<l1.pop_front()<<endl;
cout<<l1.pop_front()<<endl;
cout<<l1.pop_back()<<endl;
cout<<l1.pop_back()<<endl;
cout<<l1.pop_back()<<endl;
cout<<l1.pop_back()<<endl;
cout<<l1.pop_back()<<endl;
cout<<l1.empty()<<endl;*/
List<string> l1;
l1.push_front("123");
l1.push_front("234");
l1.push_front("345");
cout<<l1.size()<<endl;
cout<<l1.pop_back()<<endl;
cout<<l1.pop_back()<<endl;
cout<<l1.pop_back()<<endl;
cout<<l1.size()<<endl;
return 0;
}
|
Ruby
|
UTF-8
| 988
| 3.171875
| 3
|
[] |
no_license
|
module NumberCorrect
extend self
def number_correct
@turns.count do |turn|
turn.correct?
end
end
end
module NumberCorrectByCategory
extend self
def number_correct_by_category(category_to_count_correct)
@category_to_count_correct = category_to_count_correct
@category_cards_seen = turns.select do |turn|
turn.card.category == @category_to_count_correct
end
@category_cards_seen.count do |turn|
turn.correct?
end
end
end
module PercentCorrectByCategory
def percent_correct_by_category(catagory_percent_check)
@catagory_percent_check = catagory_percent_check
@category_turn_deck = Deck.new(@turns)
@category_percent_correct = @category_turn_deck.cards_in_category(@catagory_percent_check)
@category_correct = @category_percent_correct.count do |turn|
turn.correct?
end
@category_total = @category_turn_deck.count
@category_percent_correct = (@category_correct / @category_total) * 100
end
end
|
C++
|
UTF-8
| 785
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
const int outputPin = 11;
const int sensePin = 2;
const int slotsPerRev = 20;
const long updatePeriod = 1000L; // ms
long lastUpdateTime = 0;
long pulseCount = 0;
float rpm = 0;
void setup()
{
pinMode(outputPin, OUTPUT);
Serial.begin(9600);
Serial.println("Enter speed 0 to 255");
attachInterrupt(digitalPinToInterrupt(sensePin), incPulseCount, RISING);
}
void loop()
{
if (Serial.available())
{
int setSpeed = Serial.parseInt();
analogWrite(outputPin, setSpeed);
}
updateRPM();
}
void incPulseCount()
{
pulseCount ++;
}
void updateRPM()
{
long now = millis();
if (now > lastUpdateTime + updatePeriod)
{
lastUpdateTime = now;
rpm = float(pulseCount) * 60000.0 / (20.0 * updatePeriod);
pulseCount = 0;
Serial.println(rpm);
}
}
|
C#
|
UTF-8
| 1,691
| 2.875
| 3
|
[
"MIT"
] |
permissive
|
using System;
namespace asardotnetasync {
public enum EAsarException {
ASAR_FILE_CANT_FIND,
ASAR_FILE_CANT_READ,
ASAR_INVALID_DESCRIPTOR,
ASAR_INVALID_FILE_SIZE
};
public class AsarException : Exception {
private readonly EAsarException _asarException;
private readonly string _asarMessage;
public AsarException(EAsarException ex) : this(ex, "") { }
public AsarException(EAsarException ex, string message) {
_asarException = ex;
if (message.Length > 0) {
_asarMessage = message;
return;
}
_asarMessage = GetMessage(ex);
}
private string GetMessage(EAsarException ex) {
switch (ex) {
case EAsarException.ASAR_FILE_CANT_FIND:
return "Error: The specified file couldn't be found.";
case EAsarException.ASAR_FILE_CANT_READ:
return "Error: File can't be read.";
case EAsarException.ASAR_INVALID_DESCRIPTOR:
return "Error: File's header size is not defined on 4 or 8 bytes.";
case EAsarException.ASAR_INVALID_FILE_SIZE:
return "Error: Data table size shorter than the size specified in in the header.";
default:
return "Error: Unhandled exception !";
}
}
public EAsarException ExceptionCode => _asarException;
public string ExceptionMessage => _asarMessage;
public override string ToString() {
return $"(Code {ExceptionCode}) {ExceptionMessage}";
}
}
}
|
Java
|
UTF-8
| 4,605
| 2.796875
| 3
|
[] |
no_license
|
package java_swing_study.ch11;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.border.EmptyBorder;
import java_swing_study.ch11.exam.Student;
import java_swing_study.ch11.exam.StudentPanel;
@SuppressWarnings("serial")
public class StudentTableEx extends JFrame implements ActionListener {
private JPanel contentPane;
private StudentPanel pStudent;
private JPanel pList;
private JPanel pBtns;
private ArrayList<Student> stds;
private JButton btnAdd;
private JButton btnCancel;
private int updateIdx;
private StudentTblPanel pStdTbl;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
StudentTableEx frame = new StudentTableEx();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public StudentTableEx() {
stds = new ArrayList<Student>();
stds.add(new Student(1, "서현진", 80, 90, 70));
stds.add(new Student(2, "이성경", 90, 90, 40));
stds.add(new Student(3, "이유영", 50, 50, 60));
initialize();
pStdTbl.loadData(stds);
}
private void initialize() {
setTitle("학생 관리");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 515, 478);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
pStudent = new StudentPanel();
contentPane.add(pStudent, BorderLayout.NORTH);
pList = new JPanel();
contentPane.add(pList, BorderLayout.CENTER);
pList.setLayout(new BorderLayout(0, 0));
pStdTbl = new StudentTblPanel();
//바로가기 메뉴 달기
pStdTbl.setPopupMenu(createPopupMenu());
pList.add(pStdTbl, BorderLayout.CENTER);
pBtns = new JPanel();
contentPane.add(pBtns, BorderLayout.SOUTH);
btnAdd = new JButton("추가");
btnAdd.addActionListener(this);
pBtns.add(btnAdd);
btnCancel = new JButton("취소");
btnCancel.addActionListener(this);
pBtns.add(btnCancel);
loadData();
}
private void loadData() {
}
private Object[][] getRows() {
Object[][] rows = new Object[stds.size()][];
for(int i=0; i<rows.length; i++) {
rows[i] = toArray(stds.get(i));
}
return rows;
}
private Object[] toArray(Student std) {
return new Object[] {std.getStdNo(), std.getStdName(), std.getKor(), std.getEng(), std.getMath(), std.total(), std.avg()};
}
private String[] getColumnNames() {
return new String[] {"학생번호", "학생명", "국어", "영어", "수학", "총점", "평균"};
}
private JPopupMenu createPopupMenu() {
JPopupMenu popMenu = new JPopupMenu();
JMenuItem updateItem = new JMenuItem("수정");
updateItem.addActionListener(myPopMenuListener);
popMenu.add(updateItem);
JMenuItem deleteItem = new JMenuItem("삭제");
deleteItem.addActionListener(myPopMenuListener);
popMenu.add(deleteItem);
return popMenu;
}
ActionListener myPopMenuListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("수정")) {
Student upStd = pStdTbl.getSelectedItem();
updateIdx = pStdTbl.getSelectedRowIdx();
pStudent.setItem(upStd);
btnAdd.setText("수정");
pStdTbl.clearSelection();
}
if (e.getActionCommand().equals("삭제")) {
try {
pStdTbl.removeRow();
}catch(RuntimeException e1) {
JOptionPane.showMessageDialog(null, e1.getMessage());
}
}
}
};
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnCancel) {
btnCancelActionPerformed(e);
}
if (e.getSource() == btnAdd) {
if (e.getActionCommand().equals("추가")) {
btnAddActionPerformed(e);
}else {
btnUpdateActionPerformed(e);
}
}
}
private void btnUpdateActionPerformed(ActionEvent e) {
Student updateStd = pStudent.getItem();
stds.set(stds.indexOf(updateStd), updateStd);//Database적용
pStdTbl.updateRow(updateStd, updateIdx);
btnAdd.setText("추가");
pStudent.clearTf();
}
protected void btnAddActionPerformed(ActionEvent e) {
Student student = pStudent.getItem();
stds.add(student); //Database에 insert
pStdTbl.addItem(student);
pStudent.clearTf();
}
protected void btnCancelActionPerformed(ActionEvent e) {
pStudent.clearTf();
}
}
|
C++
|
UTF-8
| 4,544
| 3.40625
| 3
|
[
"Apache-2.0"
] |
permissive
|
#include "Stdafx.hpp"
/* ----------------------------------------------------------------------
* Author: Julian
* Date: 31 January 2014
* Description: Centers the origin of a circle shape
* ----------------------------------------------------------------------
*/
void centerOrigin(sf::CircleShape& circleShape)
{
// Center the origin of a circle shape
sf::FloatRect bounds = circleShape.getLocalBounds();
circleShape.setOrigin(float(int(bounds.width / 2.0f)), float(int(bounds.height / 2.0f)));
}
void centerOrigin(sf::RectangleShape& rectangleShape)
{
// Center the origin of a circle shape
sf::FloatRect bounds = rectangleShape.getLocalBounds();
rectangleShape.setOrigin(float(int(bounds.width / 2.0f)), float(int(bounds.height / 2.0f)));
}
/* ----------------------------------------------------------------------
* Author: Julian
* Date: 19 January 2014
* Description: Centers the origin of a sprite
* ----------------------------------------------------------------------
*/
void centerOrigin(sf::Sprite& sprite)
{
// Center the origin of a sprite
sf::FloatRect bounds = sprite.getLocalBounds();
sprite.setOrigin(float(int(bounds.width / 2.0f)), float(int(bounds.height / 2.0f)));
}
/* ----------------------------------------------------------------------
* Author: Julian
* Date: 19 January 2014
* Description: Centers the origin of a text
* ----------------------------------------------------------------------
*/
void centerOrigin(sf::Text& text)
{
// Center the origin of a text
sf::FloatRect bounds = text.getLocalBounds();
text.setOrigin(float(int(bounds.width / 2.0f)), float(int(bounds.height / 2.0f)));
}
/* ----------------------------------------------------------------------
* Author: Julian
* Date: 1 February
* Description: Calculates the dot product of two vectors
* ----------------------------------------------------------------------
*/
float dotProduct(const sf::Vector2f& vector1, const sf::Vector2f& vector2)
{
// Return the dot product
return vector1.x * vector2.x + vector1.y * vector2.y;
}
/* ----------------------------------------------------------------------
* Author: Julian
* Date: 2 February
* Description: Calculates the sum of the vector
* ----------------------------------------------------------------------
*/
float magnitude(const sf::Vector2f& vector)
{
// Return the sum of the vector
return sqrt(vector.x * vector.x + vector.y * vector.y);
}
/* ----------------------------------------------------------------------
* Author: Julian
* Date: 1 February
* Description: Normalizes the vector
* ----------------------------------------------------------------------
*/
sf::Vector2f normalize(const sf::Vector2f& vector)
{
// Normalize the vector
float sum = magnitude(vector);
return sf::Vector2f(vector.x / sum, vector.y / sum);
}
/* ----------------------------------------------------------------------
* Author: Julian
* Date: 28 March
* Description: Returns tru if the sprite is within the camera
* ----------------------------------------------------------------------
*/
bool isOnScreen(const sf::Sprite& sprite, const sf::View& camera)
{
// Calculate the position of the camera
float camPosX = camera.getCenter().x - camera.getSize().x / 2.0f;
float camPosY = camera.getCenter().y - camera.getSize().y / 2.0f;
// Return true if the sprite is on the view of the camera
return sprite.getPosition().x + sprite.getLocalBounds().width > camPosX && sprite.getPosition().x < camPosX + camera.getSize().x &&
sprite.getPosition().y + sprite.getLocalBounds().height > camPosY && sprite.getPosition().y < camPosY + camera.getSize().y;
}
float randomFloat(float min, float max)
{
return min + static_cast<float>(rand()) / (static_cast<float>(RAND_MAX / (max - min + 1.0f)));
}
int randomInteger(int min, int max)
{
return min + rand() / (RAND_MAX / (max - min + 1));
}
float distance(const sf::Vector2f first, const sf::Vector2f second)
{
float x = second.x - first.x;
float y = second.y - first.y;
return sqrtf(x * x + y * y);
}
std::string wrap(std::string text, size_t line_length)
{
std::istringstream words(text);
std::ostringstream wrapped;
std::string word;
if (words >> word) {
wrapped << word;
size_t space_left = line_length - word.length();
while (words >> word) {
if (space_left < word.length() + 1) {
wrapped << '\n' << word;
space_left = line_length - word.length();
}
else {
wrapped << ' ' << word;
space_left -= word.length() + 1;
}
}
}
return wrapped.str();
}
|
Java
|
UTF-8
| 1,344
| 2.78125
| 3
|
[] |
no_license
|
package com.mamahao.hr.common.enums;
import org.springframework.util.StringUtils;
/**
* 组织架构状态枚举
* Created by banchun on 2016/7/13 0013.
*/
public enum SysOrgEnums {
NORMAL(0,"正常"),
DELETE(1,"删除"),
PAUSE(2,"暂停"),
OTHER(3,"其他");
/**
* 代号
*/
private int code;
/**
* 解释
*/
private String mean;
SysOrgEnums(int code, String mean) {
this.code = code;
this.mean = mean;
}
public static SysOrgEnums toEnum(int code) {
for (int k = 0; k < values().length; k++) {
if (values()[k].getCode() == code) {
return values()[k];
}
}
return null;
}
public static SysOrgEnums toEnum(String mean) {
if (StringUtils.isEmpty(mean)) {
return null;
}
mean = mean.toUpperCase();
for (int k = 0; k < values().length; k++) {
if (values()[k].getMean().equals(mean)) {
return values()[k];
}
}
return null;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMean() {
return mean;
}
public void setMean(String mean) {
this.mean = mean;
}
}
|
C
|
UTF-8
| 420
| 3.8125
| 4
|
[] |
no_license
|
#include <stdio.h>
int ala(int a, int b)
{
int mul = 0;
while (a > 0) { // while(a)
if (a % 2) // if((a&0x1)==1)
mul += b;
a /= 2; //a>>=1;
b *= 2; //b<<=1;
}
return mul;
}
int get_gcd(int a, int b)
{
int temp;
while (a) {
if (b > a) {
temp = a;
a = b;
b = temp;
}
a = a - b;
}
return b;
}
void main() {
printf("multiply: %d\n", ala(27, 65));
printf("gcd: %d\n", get_gcd(220, 30));
}
|
Java
|
UTF-8
| 1,006
| 1.84375
| 2
|
[] |
no_license
|
package com.jumia.test.jumia.controller;
import com.jumia.test.jumia.dto.LoginDetails;
import com.jumia.test.jumia.entity.Client;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/client")
@CrossOrigin("*")
public interface ClientController {
@PostMapping
ResponseEntity<Client> create(@RequestBody Client client);
@PutMapping("/{id}")
ResponseEntity<Client> update(@PathVariable Long id, @RequestBody Client client);
@GetMapping("/{id}")
ResponseEntity<Client> findById(@PathVariable Long id);
@GetMapping
ResponseEntity<List<Client>> findAll();
@DeleteMapping("/{id}")
ResponseEntity<String> delete(@PathVariable Long id);
@PostMapping("/login")
ResponseEntity<Client> login(@RequestBody LoginDetails loginDetails);
@GetMapping("/search-by-email/{email}")
ResponseEntity<List<Client>> searchByEmail(@PathVariable String email);
}
|
Java
|
UTF-8
| 3,188
| 2.3125
| 2
|
[] |
no_license
|
package com.feidao.platform.service.custom.medicine.icebox.gridservice;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.feidao.platform.common.dbtemplate.db.template.IDBTemplate;
import com.feidao.platform.common.dbtemplate.db.template.util.CreateDBTemplateUtil;
import com.feidao.platform.service.custom.base.icebox.gridservice.AbstractCustomFuncService;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
/**
* 医药商城市药监局数据抽取自定义服务
*
* @author hanpanfei 2016.01.08
*/
public class CustomFuncBusinessOrganizationService extends AbstractCustomFuncService {
private static final Logger LOGGER = LoggerFactory.getLogger(CustomFuncBusinessOrganizationService.class);
List<DBObject> resultlist = new ArrayList<DBObject>();
private String operate = null;
@Override
public String execute(BasicDBObject dataParam) throws Exception {
initForFind(dataParam);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("数据查询自定义服务开始" + dataParam);
}
try {
resultlist = queryData();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("业务resultlist=====" + resultlist+"----------"+resultlist.size());
}
} catch (Exception e) {
return MedGenerateOperation.returnFormatter(0, "传入参数有误");
}
return findResultFormat(customRealCondition, resultlist, resultlist.size());
}
// 抽取数据
private List<DBObject> queryData() throws Exception {
IDBTemplate medicineTemplate = CreateDBTemplateUtil.createDBTemplate(spaceId, systemId);
Connection conn = medicineTemplate.getConnForRDBMS();
List<DBObject> resultList = new ArrayList<DBObject>();
try {
Statement statement = conn.createStatement();
conn.setAutoCommit(false);
String sql =sqlString();
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("业务sql=====" + sql);
}
ResultSet rs = statement.executeQuery(sql);
while (rs.next()) {
resultList.add(CustomFuncBusinessOrganizationService.rs2BasicDBObject(rs));
}
} catch (Exception e) {
conn.rollback();
} finally {
conn.close();
medicineTemplate.close();
}
return resultList;
}
//sql语句拼接
private String sqlString() {
String sql = null;
operate = customRealCondition.getString("operate");
if ("corgbusi".equals(operate)) {
sql = "select busno,orgname from c_org_busi";
}
return sql;
}
//遍历数据集合
private static BasicDBObject rs2BasicDBObject(ResultSet rs) throws Exception {
BasicDBObject result = new BasicDBObject();
ResultSetMetaData rsmd = rs.getMetaData();
int count = rsmd.getColumnCount();
for (int i = 1; i <= count; i++) {
String key = rsmd.getColumnLabel(i);
Object value = rs.getObject(i);
result.put(key.toLowerCase(), value);
}
return result;
}
}
|
C
|
UTF-8
| 638
| 4.25
| 4
|
[] |
no_license
|
/* write a program to find out if the area of a rectangle is greater than it's perimeter from length=5 and breadth=4 */
#include<stdio.h>
int main()
{
int length, breadth,area , perimeter;
printf("Enter the length and breadth of rectangle: ");
scanf("%d %d",&length, &breadth);
area= length * breadth;
perimeter= (2*(length + breadth));
if(area>perimeter)
printf("Area is greater than perimeter");
else
{
if(area<perimeter)
printf("Area is lesser than perimeter");
else
printf("Area is equal to perimeter");
}
return 0;
}
|
Java
|
UTF-8
| 478
| 2.046875
| 2
|
[
"Apache-2.0"
] |
permissive
|
package ru.job4j.forum.repository;
import org.springframework.data.jpa.repository.EntityGraph;
import org.springframework.data.repository.CrudRepository;
import ru.job4j.forum.model.Post;
import java.util.Collection;
import java.util.Optional;
public interface PostDataRepository extends CrudRepository<Post, Integer> {
@EntityGraph(Post.POST_ALL_FIELDS)
Collection<Post> findAll();
@EntityGraph(Post.POST_ALL_FIELDS)
Optional<Post> findById(Integer id);
}
|
Java
|
UTF-8
| 2,701
| 2.140625
| 2
|
[
"Apache-2.0"
] |
permissive
|
// Copyright 2020 Mavenir
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.xgvela.model;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyDescription;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
/**
* Mavenir Event Format
* <p>
*
*
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"event"
})
public class MEF implements Serializable
{
/**
* the root level of the common event format
*
*/
@JsonProperty("event")
@JsonPropertyDescription("the root level of the common event format")
private Event event;
@JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
private final static long serialVersionUID = 8176205186062925124L;
/**
* No args constructor for use in serialization
*
*/
public MEF() {
}
/**
*
* @param event
*/
public MEF(Event event) {
super();
this.event = event;
}
/**
* the root level of the common event format
*
*/
@JsonProperty("event")
public Event getEvent() {
return event;
}
/**
* the root level of the common event format
*
*/
@JsonProperty("event")
public void setEvent(Event event) {
this.event = event;
}
public MEF withEvent(Event event) {
this.event = event;
return this;
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
@JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
public MEF withAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
return this;
}
}
|
Python
|
UTF-8
| 38,831
| 3.140625
| 3
|
[] |
no_license
|
#!/usr/bin/python -d
# vim: ts=4 sw=4 et ft=python
"""
Transform a .orig file into into a .tex file.
Note to maintainers:
This program gets a rating above 9.5 out of 10 from pylint;
please keep it that way.
Most of the complaints still raised by pylint are related to the fact that
the code uses a structured programming style, not an object-oriented style.
I chose the structured programming style because e.g. outputting a slide
or a section heading updates several local state variables, and any methods
for doing such printing would have to be passed the current values of these
state variables, and would also have to return their possibly updated values.
All this parameter passing would obscure the flow of data and infuence
between the various parts of the relevant loops (in e.g. print_notes)
by placing it behind an abstraction barrier.
"""
import copy
import getopt
import os
import sys
class Talk:
"""
This structure contains all the information we have about the talk
from configuration files.
"""
def __init__(self, basename):
"""
Read the talk configuration files, and return a structure
giving their contents.
"""
self.basename = basename
self.title = \
self.read_conf_file("title", "UNKNOWN TITLE")
self.date = \
self.read_conf_file("date", "UNKNOWN DATE")
self.institute = \
self.read_conf_file("institute", "UNKNOWN INSTITUTE")
self.author = \
self.read_conf_file("author", "UNKNOWN AUTHOR")
self.author_long = \
self.read_conf_file("author_long", "UNKNOWN AUTHOR")
self.organization = \
self.read_conf_file("organization", "The University of Melbourne")
self.logos = \
self.read_whole_file("logos", "")
def __str__(self):
""" Print the talk parameters. """
desc = ""
desc = desc + "Title: %s\n" % self.title
desc = desc + "Institute: %s\n" % self.institute
desc = desc + "Date: %s\n" % self.date
desc = desc + "Author: %s\n" % self.author
desc = desc + "Author long: %s\n" % self.author_long
desc = desc + "Organization: %s\n" % self.organization
return desc
def read_conf_file(self, name, default):
return read_conf_file(os.path.join(self.basename, name), default)
def read_whole_file(self, name, default):
return read_whole_file(os.path.join(self.basename, name), default)
class Beamer:
"""
This structure contains all the beamer parameters we have
from configuration files.
"""
def __init__(self, basename):
"""
Read the beamer configuration files, and return a structure
giving their contents.
"""
self.basename = basename
self.beamer_options = \
self.read_conf_file("beamer_options", "")
self.beamer_theme = \
self.read_conf_file("beamer_theme", "CambridgeUS")
self.beamer_inner_theme = \
self.read_conf_file("beamer_inner_theme", "default")
self.beamer_outer_theme = \
self.read_conf_file("beamer_outer_theme", "default")
self.beamer_color_theme = \
self.read_conf_file("beamer_color_theme", "dolphin")
self.beamer_font_theme = \
self.read_conf_file("beamer_font_theme", "structurebold")
def __str__(self):
""" Print the beamer parameters. """
desc = ""
desc = desc + "Options: %s\n" % self.beamer_options
desc = desc + "Theme: %s\n" % self.beamer_theme
desc = desc + "Inner theme: %s\n" % self.beamer_inner_theme
desc = desc + "Outer theme: %s\n" % self.beamer_outer_theme
desc = desc + "Color theme: %s\n" % self.beamer_color_theme
desc = desc + "Font theme: %s\n" % self.beamer_font_theme
return desc
def read_conf_file(self, name, default):
return read_conf_file(os.path.join(self.basename, name), default)
class NumLine:
"""
We attach a filename and a linenumber to each line we read in.
This way, we can generate accurate error messages even though
(a) we filter out some lines during the processing of SLIDESONLY
and NOTESONLY directives, and (b) some lines we get from other files
we read when handling INCLUDE directives.
"""
def __init__(self, filename, line_number, line):
""" Create a numbered line. """
self.file = filename
self.number = line_number
self.line = line
def __str__(self):
""" Print the details of a numbered line. """
return "%s, %s: %s" % (self.file, self.number, self.line)
class Section:
""" A section title. """
def __init__(self, section_number, section_name):
""" Create a section title. """
self.sect_section_number = section_number
self.sect_section_name = section_name
def __str__(self):
""" Print the details of a section title. """
return "SECTION %d: %s\n" \
% (self.sect_section_number, self.sect_section_name)
class Subsection:
""" A subsection title. """
def __init__(self, section_number, subsection_number, subsection_name):
""" Create a section title. """
self.subsect_section_number = section_number
self.subsect_subsection_number = subsection_number
self.subsect_subsection_name = subsection_name
def __str__(self):
""" Print the details of a subsection title. """
return "SUBSECTION %d.%d %s\n" \
% (self.subsect_section_number, self.subsect_subsection_number, \
self.subsect_subsection_name)
class Slide:
"""
An ordinary, quiz or demo slide, shown by the slide_kind field being
SLIDE, QUIZ and DEMO respectively.
"""
def __init__(self, kind, section_number, subsection_number, title, \
options, columns, lines, notes):
""" Create a slide. """
self.slide_kind = kind
self.slide_section_number = section_number
self.slide_subsection_number = subsection_number
self.slide_title = title
self.slide_options = options
self.slide_columns = columns
self.slide_lines = lines
self.slide_notes = notes
def __str__(self):
""" Print the details of a slide. """
option_str = self.slide_options
if self.slide_columns != 2:
if option_str == "":
option_str = "ONECOLUMN"
else:
option_str = option_str + " ONECOLUMN"
if option_str != "":
option_str = " (%s)" % option_str
head = "%s in %d.%d: %s%s\n" % (self.slide_kind, \
self.slide_section_number, self.slide_subsection_number, \
self.slide_title, option_str)
lines = "LINES:\n" + "\n".join(self.slide_lines) + "\n"
notes = "NOTES:\n" + "\n".join(self.slide_notes) + "\n"
if self.slide_notes == []:
desc = head + lines
else:
desc = head + lines + notes
return desc
def slide_prefix(self):
"""
Return the prefix (if any) we should put on the slide's title.
"""
if self.slide_kind == "SLIDE":
prefix = ""
elif self.slide_kind == "QUIZ":
prefix = "QUIZ: "
elif self.slide_kind == "DEMO":
prefix = "DEMO: "
else:
prefix = "UNKNOWN SLIDE TYPE: "
return prefix
class Item:
"""
We parse the input .orig file into a list of items. There are three types
of items: section titles, subsection titles, and slides, shown by the kind
field being SECTION, SUBSECTION and SLIDE respectively.
The types of the data fields is Section, Subsection and Slide respectively.
"""
def __init__(self, kind, data):
""" Create an item. """
self.kind = kind
self.data = data
def __str__(self):
""" Print the details of an item. """
return str(self.data)
###############################################################################
def usage(msg):
""" Print the usage message. """
print >> sys.stderr, msg
print >> sys.stderr, \
"usage: transform [-adnq] [-tN] beamer basename"
def main():
"""
Transform the .orig file referred to by the basename argument
into a .tex file.
"""
# DEBUG print >> sys.stderr, sys.argv
status = 0
try:
(opts, args) = getopt.gnu_getopt(sys.argv[1:], "abindqr:t:")
except getopt.GetoptError:
usage("unknown option")
sys.exit(2)
bold_slide_titles = False
include_notes = True
ignored_kinds = []
instructor_version = False
tab_replacement = " " # four spaces
for (opt, arg) in opts:
if opt == "-a":
x = 0
elif opt == "-b":
bold_slide_titles = True
# DEBUG print "setting bold_slide_titles"
elif opt == "-i":
instructor_version = True
# DEBUG print "setting instructor_version"
elif opt == "-n":
include_notes = False
# DEBUG print "setting include_notes"
elif opt == "-d":
ignored_kinds = ignored_kinds + ["DEMO"]
# DEBUG print "ignoring demos"
elif opt == "-q":
ignored_kinds = ignored_kinds + ["QUIZ"]
# DEBUG print "ignoring quizes"
elif opt == "-t":
tab_replacement = " " * int(arg)
# DEBUG print "% using %d-space tabs" % arg
else:
usage("unknown option")
sys.exit(2)
# DEBUG print >> sys.stderr, args
if len(args) == 2:
[target, basename] = args
if target == "beamer":
target_select = ["SLIDESONLY", "BEAMERONLY"]
pic_prefix = "pb_"
else:
usage("unknown target")
sys.exit(2)
if instructor_version:
instructor_select = ["INSTRUCTORONLY"]
else:
instructor_select = []
select = target_select + instructor_select
origname = basename + ".orig"
(items, msgs, errors) = \
parse_slide_file(origname, tab_replacement, select)
if errors > 0:
for msg in msgs:
print >> sys.stderr, msg
status = 1
else:
talk = Talk(basename)
items = filter_items(target, ignored_kinds, include_notes, \
pic_prefix, items)
if target == "beamer":
beamer = Beamer(basename)
status = print_beamer(talk, beamer, items)
else:
usage("unknown target")
sys.exit(2)
else:
usage("incorrect number of arguments")
status = 1
sys.exit(status)
###############################################################################
def try_open_file(filename):
"""
Try to open the named file, and return a (fp, success) pair. If successful,
success will be True and fp will be valid. If unsuccessful, success will be
False and fp will NOT be valid.
"""
try:
try_fp = open(filename)
success = True
except IOError:
try_fp = sys.stdin
success = False
return (try_fp, success)
def print_use_packages(target):
"""
Print the \usepackage directives needed by the .tex file we are generating.
Include lecture_common and lecture_<target> if they exist, and include
the contents of the packages list file from the talk directory.
"""
package_name = "lecture_common"
(pack_fp, success) = try_open_file("styles/" + package_name + ".sty")
if success:
print "\\usepackage{%s}" % package_name
pack_fp.close()
package_name = "lecture_" + target
(pack_fp, success) = try_open_file("styles/" + package_name + ".sty")
if success:
print "\\usepackage{%s}" % package_name
pack_fp.close()
(pack_fp, success) = try_open_file("talk/packages")
if success:
package_lines = pack_fp.readlines()
for package_line in package_lines:
package_line = package_line[:-1]
if len(package_line) > 0 and package_line[0] != "%":
print package_line
pack_fp.close()
def read_conf_file(filename, default):
"""
Read the named configuration file if it exists. Filter out any lines that
start with #, and return the remaining contents as a string. If the file
does not exist, return the supplied default contents.
"""
(conf_fp, success) = try_open_file(filename)
if success:
lines = conf_fp.readlines()
conf_fp.close()
for line in lines:
if len(line) > 1 and line[0] != "#":
return line[:-1]
return default
def read_whole_file(filename, default):
"""
Read the named file if it exists. return its contents as a string.
If the file does not exist, return the supplied default contents.
"""
(fp, success) = try_open_file(filename)
if success:
contents = fp.read()
fp.close()
return contents
return default
###############################################################################
def get_numbered_lines(filename, select, tab_replacement):
"""
Read in the named file. Process INCLUDE lines. Filter out lines controlled
by BEAMERONLY, SEMINARONLY, SLIDESONLY, NOTESONLY and/or INSTRUCTORONLY
if the starting control word is not in select.
Return the tuple (numbered_lines, msgs, errors). Numbered_lines will be
a representation of the data read from the file. If there are any malformed
INCLUDE Lines or mismatched ONLY/ENDONLY lines, msgs will include an error
messages for each one, and error will tell you have many such errors
there have been. Otherwise, msgs will be the empty list and errors
will be 0.
"""
file_fp = open(filename)
raw_lines = file_fp.readlines()
file_fp.close()
line_number = 0
numbered_lines = []
for raw_line in raw_lines:
raw_line = raw_line[:-1]
line_number = line_number + 1
numbered_line = NumLine(filename, line_number, raw_line)
numbered_lines = numbered_lines + [numbered_line]
incl_msgs = []
incl_errors = 0
incl_numbered_lines = []
for numbered_line in numbered_lines:
words = numbered_line.line.split()
len_words = len(words)
if len_words > 0 and words[0] == "INCLUDE":
if len_words > 1:
incl_filename = words[len_words - 1]
words = words[1:-1]
# We have already handled the first word (INCLUDE)
# and the last word (the filename).
len_words = len_words - 2
# Process all the words between the INCLUDE and the filename,
# which may ask for extra processing of the included lines.
unindent = 0;
cur_word = 0
while cur_word < len_words:
if words[cur_word] == "UNINDENT":
if cur_word + 1 < len_words:
unindent = int(words[cur_word + 1])
cur_word = cur_word + 2
else:
incl_errors = incl_errors + 1
incl_msg = "%s, %d: UNINDENT without number" % \
(numbered_line.file, numbered_line.number)
incl_msgs = incl_msgs + [incl_msg]
else:
incl_errors = incl_errors + 1
incl_msg = \
"%s, %d: %s is not an option for INCLUDEs" % \
(numbered_line.file, numbered_line.number, \
words[cur_word])
incl_msgs = incl_msgs + [incl_msg]
# We go on even if we found and reported some problems.
main_sed_cmd_1 = "'s/\t/%s/g'" % tab_replacement
main_sed_cmd_2 = "'/HIDE_START/,/HIDE_END/d'"
main_sed_cmd = "sed -e %s -e %s %s" % \
(main_sed_cmd_1, main_sed_cmd_2, incl_filename)
if unindent == 0:
incl_cmd = main_sed_cmd
else:
unindent_str = "." * unindent
unindent_cmd = "sed -e 's/^%s//'" % unindent_str
incl_cmd = "%s | %s" % (main_sed_cmd, unindent_cmd)
incl_fp = os.popen(incl_cmd)
incl_lines = incl_fp.readlines()
incl_fp.close()
incl_line_number = 0
for incl_line in incl_lines:
incl_line = incl_line[:-1]
incl_line_number = incl_line_number + 1
incl_numbered_line = \
NumLine(incl_filename, incl_line_number, incl_line)
incl_numbered_lines = \
incl_numbered_lines + [incl_numbered_line]
else:
incl_errors = incl_errors + 1
incl_msg = "%s, %d: INCLUDE without filename" % \
(numbered_line.file, numbered_line.number)
incl_msgs = incl_msgs + [incl_msg]
cur_word = 2;
unindent = 0;
while cur_word < len_words:
if words[cur_word] == "UNINDENT":
if cur_word + 1 < len_words:
unindent = words[cur_word + 1]
cur_word = cur_word + 2
else:
incl_errors = incl_errors + 1
incl_msg = "%s, %d: bad INCLUDE" % \
(numbered_line.file, numbered_line.number)
incl_msgs = incl_msgs + [incl_msg]
else:
incl_numbered_lines = incl_numbered_lines + [numbered_line]
(final_numbered_lines, select_msgs, select_errors) = \
filter_nested_selects(incl_numbered_lines, select)
all_msgs = incl_msgs + select_msgs
all_errors = incl_errors + select_errors
return (final_numbered_lines, all_msgs, all_errors)
def filter_nested_selects(numbered_lines, select):
"""
Filter out lines controlled by BEAMERONLY, SEMINARONLY, SLIDESONLY,
NOTESONLY and/or INSTRUCTORONLY if the starting control word is not
in select.
Return the tuple (numbered_lines, msgs, errors). Numbered_lines will be
a representation of the data read from the file. If there are any malformed
INCLUDE Lines or mismatched ONLY/ENDONLY lines, msgs will include an error
messages for each one, and error will tell you have many such errors
there have been. Otherwise, msgs will be the empty list and errors
will be 0.
"""
begin_onlys = \
["BEAMERONLY", "SEMINARONLY", "SLIDESONLY", "NOTESONLY",
"INSTRUCTORONLY"]
msgs = []
errors = 0
final_lines = []
num_numbered_lines = len(numbered_lines)
line_index = 0
while line_index < num_numbered_lines:
numbered_line = numbered_lines[line_index]
line = numbered_line.line
if not line in begin_onlys:
final_lines = final_lines + [numbered_line]
line_index = line_index + 1
else:
scope_lines = []
begin_line = line
begin_file_name = numbered_line.file
begin_line_number = numbered_line.number
end_line = "END" + line
line_index = line_index + 1
in_scope = True
while line_index < num_numbered_lines and in_scope:
numbered_line = numbered_lines[line_index]
line = numbered_line.line
if line != end_line:
scope_lines = scope_lines + [numbered_line]
else:
in_scope = False
line_index = line_index + 1
if in_scope:
errors = errors + 1
msg = "%s, %d: %s without %s" % \
(begin_file_name, begin_line_number, begin_line, end_line)
msgs = msgs + [msg]
(filtered_scope_lines, scope_msgs, scope_errors) = \
filter_nested_selects(scope_lines, select)
msgs = msgs + scope_msgs
errors = errors + scope_errors
if begin_line in select:
final_lines = final_lines + filtered_scope_lines
return (final_lines, msgs, errors)
def parse_slide_file(filename, tab_replacement, select):
"""
Read in the named file. Filter out slides-only lines if select != SLIDES,
and filter out notes-only lines if select != NOTES.
Return the tuple (items, msgs, errors). Items is a list of items, where
each item is a section title, a subsection title, or a slide of any of
three types (ordinary slide, quiz or demo). Msgs will be a list of error
and/or warning messages. Error will be a count of the number of errors.
(It is possible for error to be 0 even if msgs is not the empty list,
if msgs contains warnings.)
There are several kinds of errors that this code looks for. They are
all about malformed input.
"""
next_section_number = 1
begin_slide_words = ["SLIDE", "QUIZ", "DEMO"]
end_slide_words = ["ENDSLIDE", "ENDQUIZ", "ENDDEMO"]
next_slide_words = begin_slide_words + end_slide_words + \
["SECTION", "SUBSECTION"]
items = []
(numbered_lines, msgs, errors) = \
get_numbered_lines(filename, select, tab_replacement)
cur_section_number = -1
cur_section_name = ""
cur_subsection_number = 0
cur_subsection_name = ""
num_lines = len(numbered_lines)
cur_line_number = 0
cur_line_number = \
skip_blank_lines(numbered_lines, num_lines, cur_line_number)
while cur_line_number < num_lines:
have_error = False
line = numbered_lines[cur_line_number].line
words = line.split()
if len(words) == 0:
# This shouldn't happen, due to skip_blank_lines.
cmd = ""
else:
cmd = words[0]
# print "cur %d, num_lines %d" % (cur_line_number, num_lines)
# print words
if cmd == "SECTION":
if len(words) < 3:
have_error = True
msg = "%s, %d: bad SECTION" % \
(filename, numbered_lines[cur_line_number].number)
msgs = msgs + [msg]
if not have_error:
new_section_number = int(words[1])
new_section_number_ok = False
if cur_section_number == -1:
new_section_number_ok = True
elif new_section_number == cur_section_number + 1:
new_section_number_ok = True
if not new_section_number_ok:
have_error = True
msg = \
"%s, %d: SECTION %d followed by SECTION %d" % \
(filename, numbered_lines[cur_line_number].number,
cur_section_number, new_section_number)
msgs = msgs + [msg]
cur_section_number = new_section_number
cur_section_name = " ".join(words[2:])
cur_subsection_number = int(0)
cur_subsection_name = ""
sect = Section(cur_section_number, cur_section_name)
item = Item("SECTION", sect)
elif cmd == "SUBSECTION":
if len(words) < 2:
have_error = True
msg = "%s, %d: bad SUBSECTION" % (filename, cur_line_number)
msgs = msgs + [msg]
if not have_error:
cur_subsection_number = cur_subsection_number + 1
cur_subsection_name = " ".join(words[1:])
subsect = Subsection(cur_section_number, \
cur_subsection_number, cur_subsection_name)
item = Item("SUBSECTION", subsect)
elif cmd in begin_slide_words:
have_error = False
slide_columns = 2
slide_options = []
cur_word = 1
num_words = len(words)
while cur_word < num_words:
if words[cur_word] == "ONECOLUMN":
slide_columns = 1
cur_word = cur_word + 1
elif words[cur_word] == "OPTION":
slide_options = slide_options + [words[cur_word + 1]]
cur_word = cur_word + 2
else:
break
slide_title = " ".join(words[cur_word:])
if slide_title == "":
have_error = True
msg = "%s, %d: bad %s" % (filename, cur_line_number, cmd)
msgs = msgs + [msg]
if not have_error:
end_word = "END" + cmd
slide_lines = []
slide_notes = []
seen_note = False
while True:
next_line_number = cur_line_number + 1
if next_line_number >= num_lines:
break
line = numbered_lines[next_line_number].line
line_words = line.split()
if len(line_words) == 0:
first_word = ""
else:
first_word = line_words[0]
if first_word in next_slide_words:
if first_word in end_slide_words:
cur_line_number = next_line_number
if first_word != end_word:
# Don't set have_error; the item is still
# valid.
msg = "%s, %d: %s ended with %s" % \
(filename, cur_line_number, \
cmd, first_word)
msgs = msgs + [msg]
break
if first_word == "NOTE" and len(line_words) == 1:
seen_note = True
else:
if seen_note:
slide_notes = slide_notes + [line]
else:
slide_lines = slide_lines + [line]
cur_line_number = next_line_number
slide = Slide(cmd, cur_section_number, cur_subsection_number, \
slide_title, slide_options, slide_columns, \
slide_lines, slide_notes)
item = Item("SLIDE", slide)
else:
# Comment lines and blank lines have already been ignored
# by skip_blank_lines.
have_error = True
msg = "%s, %d: orphan line <%s>" % (filename, cur_line_number, line)
msgs = msgs + [msg]
if have_error:
errors = errors + 1
else:
items = items + [item]
cur_line_number = cur_line_number + 1
cur_line_number = \
skip_blank_lines(numbered_lines, num_lines, cur_line_number)
return (items, msgs, errors)
###############################################################################
def filter_items(target, ignored_kinds, include_notes, pic_prefix, items):
"""
Remove items that ignored slide types, remove notes from slides
if they are not needed, and modify the contents of the slides
if the needed form of the content differs between targets.
"""
if target != "notes":
include_notes = False
filtered_items = []
for item in items:
if item.kind == "SECTION":
filtered_items = filtered_items + [item]
elif item.kind == "SUBSECTION":
filtered_items = filtered_items + [item]
elif item.kind == "SLIDE":
slide = item.data
if not slide.slide_kind in ignored_kinds:
(slide.slide_lines, slides_pause) = \
rewrite_and_detect_pause(pic_prefix, slide.slide_lines)
(slide.slide_notes, notes_pause) = \
rewrite_and_detect_pause(pic_prefix, slide.slide_notes)
if not include_notes:
slide.slide_notes = []
notes_pause = False
item.data = slide
if notes_pause:
# Pauses are never useful inside notes, regardless of
# the target. We could generate an error message here.
slide.slide_notes = filter_out_pause(slide.slide_notes)
item.data = slide
if slides_pause:
if target == "beamer":
slide.slide_lines = beamerify_pause(slide.slide_lines)
item.data = slide
filtered_items = filtered_items + [item]
elif target == "seminar":
expanded_items = expand_out_pause(item)
filtered_items = filtered_items + expanded_items
elif target == "notes":
slide.slide_lines = filter_out_pause(slide.slide_lines)
item.data = slide
filtered_items = filtered_items + [item]
else:
filtered_items = filtered_items + [item]
return filtered_items
def beamerify_pause(old_lines):
""" Replace PAUSE lines with \pause lines. """
new_lines = []
for old_line in old_lines:
if old_line == "PAUSE":
new_lines = new_lines + ["\pause"]
else:
new_lines = new_lines + [old_line]
return new_lines
def filter_out_pause(old_lines):
""" Filter out PAUSE lines. """
new_lines = []
for old_line in old_lines:
if old_line != "PAUSE":
new_lines = new_lines + [old_line]
return new_lines
def expand_out_pause(item):
"""
Given a slide item with N PAUSE lines, which has a structure like this:
line group 1
PAUSE
line group 2
PAUSE
line group 3
return a list of N+1 slide items, structured like this:
slide 1:
line group 1
<blank line>
slide 2:
line group 1
<blank line>
line group 2
slide 3:
line group 1
<blank line>
line group 2
<blank line>
line group 3
Delete the notes lines from all of these slides except the last.
"""
slide = item.data
old_lines = slide.slide_lines
before_lines = []
after_lines = []
before = True
for old_line in old_lines:
if old_line == "PAUSE":
before = False
after_lines = [""]
else:
if before:
before_lines = before_lines + [old_line]
else:
after_lines = after_lines + [old_line]
if before:
# There is no PAUSE line.
return [item]
first_slide = slide
later_slide = copy.copy(slide)
# First, we have a slide with the lines before the PAUSE. We delete any
# notes on the slide, since we will keep these in the last slide.
first_slide.slide_lines = before_lines
first_slide.slide_notes = []
first_item = Item(item.kind, first_slide)
# Then, we have a slide with the lines before and after the PAUSE,
# but not the pause line itself. We keep any notes.
later_slide.slide_lines = before_lines + after_lines
later_item = Item(item.kind, later_slide)
# We process the later slide recursively. If there are any more PAUSE
# lines, they will be processed, and later_item will be replaced by several
# items; otherwise, the recursive call will return [later_item].
return [first_item] + expand_out_pause(later_item)
def rewrite_and_detect_pause(pic_prefix, old_lines):
"""
Process old_lines. Replace any references to epsfboxes to refer to a
target-specific version of the postscript file by adding the given prefix
to their filenames. Also detect whether the lines contain any occurrences
of PAUSE. The return value is a pair (new_lines, contains_pause).
"""
contains_pause = False
new_lines = []
for old_line in old_lines:
if old_line[0:9] == "\\epsfbox{":
new_line = "%s%s%s" % ( old_line[0:9], pic_prefix, old_line[9:] )
else:
new_line = old_line
if new_line == "PAUSE":
contains_pause = True
new_lines = new_lines + [new_line]
return (new_lines, contains_pause)
###############################################################################
def print_beamer(talk, beamer, items):
"""
Print out the items as a .tex file using the beamer package.
"""
if beamer.beamer_options == "":
beamer.beamer_options = ",t"
else:
beamer.beamer_options = ",t," + beamer.beamer_options
print "\\documentclass[t%s]{beamer}" % beamer.beamer_options
print_use_packages("beamer")
print "\\mode<presentation>"
print "\\usetheme{%s}" % beamer.beamer_theme
print "\\usecolortheme{%s}" % beamer.beamer_color_theme
print "\\usefonttheme{%s}" % beamer.beamer_font_theme
print "\\useinnertheme{%s}" % beamer.beamer_inner_theme
print "\\useoutertheme{%s}" % beamer.beamer_outer_theme
# print "\\usepackage[english]{babel}"
print ""
# The author and institute are obviously fakes; they are set up
# to insert them into the footline.
author = talk.author
author_long = talk.author_long
title = talk.title
institute = talk.institute
organization = talk.organization
logos = talk.logos.split("\n")
(logos, _) = rewrite_and_detect_pause("pb_", logos)
logos = "\n".join(logos)
date = talk.date
unknown_items = []
print "\\title{%s}" % title
print "\\author{%s}" % author
print "\\institute{%s}" % "UoM \& NICTA"
# organization.split("\\\\")[0].strip()
print "\\date{%s}" % date
print "\\begin{document}"
print ""
for item in items:
if item.kind == "SECTION":
sect = item.data
print "\\section{%s}\n" % sect.sect_section_name
print "\\begin{frame}"
print "\\frametitle{}\n"
print "\\begin{center}"
# print "{\\small %s}\\\\[5mm]" % subj.institute
# print "{\\bf {\\large %s} \\\\ %s}\\\\[5mm]" % \
# (subj.subject_number, subj.subject_name)
# print "\\begin{minipage}{80mm}"
# print "\\end{minipage}"
print "\\vspace{20mm}"
print "{\\Large\\bf %s}\\\\[8mm]" % talk.title
print "{\\Large %s}\\\\[1mm]" % author_long
print "{%s}\n" % organization
if logos != "":
print "{%s}\\\\[10mm]\n" % logos
else:
print "\vspace{20mm}\n"
print "%s\\\\[1mm]" % talk.institute
print "%s\\\\" % talk.date
print "\\end{center}"
print "\\end{frame}\n"
elif item.kind == "SUBSECTION":
subsect = item.data
print "\\subsection{%s}" % subsect.subsect_subsection_name
elif item.kind == "SLIDE":
slide = item.data
prefix = slide.slide_prefix()
options = ",".join(slide.slide_options)
if options == "":
options = "fragile"
else:
options = "fragile," + options
print "\n\\begin{frame}[%s]" % options
print "\\frametitle{%s%s}" % (prefix, slide.slide_title)
print_lines(slide.slide_lines, 0, 4)
print "\\end{frame}\n"
else:
unknown_items = unknown_items + [item]
print "\\end{document}"
if unknown_items == []:
status = 0
else:
status = 1
print >> sys.stderr, "transform: internal error (unknown items)"
return status
###############################################################################
def skip_blank_lines(numbered_lines, num_lines, cur_line_number):
"""
Given numbered_lines, a list of num_lines NumLines, in which the current
line given by cur_line_number, return the number of the next nonblank,
non-comment line.
"""
while cur_line_number < num_lines:
line = numbered_lines[cur_line_number].line
words = line.split()
if len(words) != 0 and line[0] != "%":
return cur_line_number
cur_line_number = cur_line_number + 1
return cur_line_number
def print_lines(lines, blank_vspace, begin_verb_space):
"""
Print out the given lines, and make them look good. We do two things to
make them look good:
- We ensure that blocks of nonblank lines are separated by a consistent
amount of white space. If blank_vspace != 0, this will be blank_vspace
millimetres; otherwise, it will be one latex blank line's worth.
- If the lines begin with verbatim, we subtract begin_verb_space
millimetres of vertical space. We need this for targets that insert
redundant vertical space before verbatim lines, as a counteraction.
"""
num_lines = len(lines)
cur_line_number = 0
in_verbatim = False
last_space = False
printed_stuff = False
while cur_line_number < num_lines:
line = lines[cur_line_number]
if line == "\\begin{verbatim}" and begin_verb_space != 0:
if not printed_stuff:
print "\\vspace{-%dmm}" % begin_verb_space
if line == "":
if in_verbatim:
print line
elif not last_space:
if blank_vspace != 0:
print "\\par"
print "\\vspace{%dmm}" % blank_vspace
else:
print line
# Do not print duplicate blank lines outside verbatim.
else:
printed_stuff = True
print line
if line == "\\begin{verbatim}":
in_verbatim = True
elif line == "\\end{verbatim}":
in_verbatim = False
if line == "":
last_space = True
elif in_verbatim or line[0] != "%":
last_space = False
cur_line_number = cur_line_number + 1
###############################################################################
main()
|
C
|
UTF-8
| 337
| 2.5625
| 3
|
[] |
no_license
|
/* Monte Carlo simulation of pi*/
#include <stdio.h>
#include <omp.h>
unsigned int seed = 1; /* random number seed */
const unsigned int rand_max = 32768;
double rannum()
{
#pragma omp threadprivate(seed)
unsigned int rv;
seed = seed * 1103515245 + 12345;
rv = ((unsigned)(seed/65536) % rand_max);
return (double)rv/rand_max;
}
|
Java
|
UTF-8
| 481
| 3.421875
| 3
|
[] |
no_license
|
package collection;
import java.util.ArrayList;
import java.util.Iterator;
public class list {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
list.add("6");
Iterator it=list.iterator();
while(it.hasNext()) {
String str=(String)it.next();
if(str.equals("1")|| str.equals("2")) it.remove();
System.out.println(list);
}
}
}
|
Markdown
|
UTF-8
| 1,606
| 3.03125
| 3
|
[] |
no_license
|
# Emerton Q&A Test
### Description
A program that counts unique words from an English text file, treating hyphen and apostrophe as part of the word.
The program must output the ten most frequent words and mention the number of occurrences.
The expected output is (using `Temptest.txt` file as input`: \
and (514) \
the (513) \
i (446) \
to (324) \
a (310) \
of (295) \
my (288) \
you (211) \
that (188) \
this (185)
### Environment
This program been tested on **Windows 10** and **Ubuntu 18.04 LTS** operating systems.
- The running time environment are python 3.9.2 on Windows 10, Python 3.6.2 on Ubuntu.
- The used libraries with Python runtime environment: itertools, re, argparse, os, unittest. all standard libraries, so it should run without need to install them.
### Run the program
From the CLi run the command and provide the path to:
- input file. e.g. `./here/the/path/to/Tempest.txt`.
- output file. e.g. `./here/is/the/path/to/result.txt`.
The path should be correct thus the directories and file existed and have permission to read and write to.
Example on **Linux**:
```terminal
python3 main.py --input ./Tempest.txt --ouput result.txt
```
Or you can sue the code below
```terminal
python3 main.py -i ./Tempest.txt -o result.txt
```
for running the test cases
```terminal
python3 -m unittest
```
<br>
Example on **Windows 10**
```terminal
python main.py --input ./Tempest.txt --output result.txt
```
Or you can use the code below
```terminal
python main.py -i ./Tempest.txt -o result.txt
```
for running the test cases
```terminal
python -m unittest
```
#### Author: Sqoor
|
Java
|
UTF-8
| 7,905
| 2.046875
| 2
|
[] |
no_license
|
package lu.circl.mispbump.activities;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.constraintlayout.widget.ConstraintLayout;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.material.textfield.TextInputLayout;
import java.util.Objects;
import lu.circl.mispbump.R;
import lu.circl.mispbump.auxiliary.DialogManager;
import lu.circl.mispbump.auxiliary.MispRestClient;
import lu.circl.mispbump.auxiliary.PreferenceManager;
import lu.circl.mispbump.models.restModels.Organisation;
import lu.circl.mispbump.models.restModels.Role;
import lu.circl.mispbump.models.restModels.User;
public class LoginActivity extends AppCompatActivity {
private PreferenceManager preferenceManager;
private ConstraintLayout constraintLayout;
private TextInputLayout serverAuthkey;
private TextInputLayout serverUrl;
private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
preferenceManager = PreferenceManager.getInstance(this);
getWindow().setStatusBarColor(getColor(R.color.colorPrimary));
initializeViews();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_login, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.menu_login_help) {
DialogManager.loginHelpDialog(LoginActivity.this);
return true;
}
return super.onOptionsItemSelected(item);
}
private void initializeViews() {
constraintLayout = findViewById(R.id.rootLayout);
Toolbar myToolbar = findViewById(R.id.appbar);
setSupportActionBar(myToolbar);
ActionBar ab = getSupportActionBar();
if (ab != null) {
ab.setDisplayHomeAsUpEnabled(false);
ab.setDisplayShowTitleEnabled(false);
}
Button downloadInfoButton = findViewById(R.id.login_download_button);
downloadInfoButton.setOnClickListener(onLogin);
serverUrl = findViewById(R.id.login_server_url);
serverAuthkey = findViewById(R.id.login_automation_key);
progressBar = findViewById(R.id.login_progressbar);
}
/**
* Called when the user clicks on the login button.
*/
private View.OnClickListener onLogin = new View.OnClickListener() {
@Override
public void onClick(View v) {
final String url = Objects.requireNonNull(serverUrl.getEditText()).getText().toString();
final String authkey = Objects.requireNonNull(serverAuthkey.getEditText()).getText().toString();
boolean error = false;
serverUrl.setError(null);
serverAuthkey.setError(null);
if (!isValidUrl(url)) {
error = true;
serverUrl.setError("Invalid Server URL");
}
if (!isValidAutomationKey(authkey)) {
error = true;
serverAuthkey.setError("Invalid automation key");
}
if (error) {
return;
}
final MispRestClient mispRestClient = MispRestClient.getInstance(url, authkey);
// display progress bar
progressBar.setVisibility(View.VISIBLE);
// get my user information and the organisation associated with my user
mispRestClient.isAvailable(new MispRestClient.AvailableCallback() {
@Override
public void available() {
mispRestClient.getRoles(new MispRestClient.AllRolesCallback() {
@Override
public void success(final Role[] roles) {
preferenceManager.setRoles(roles);
mispRestClient.getMyUser(new MispRestClient.UserCallback() {
@Override
public void success(final User user) {
preferenceManager.setMyUser(user);
for (Role role : roles) {
if (role.getId().equals(user.getRoleId())) {
if (!role.getPermAdmin()) {
progressBar.setVisibility(View.GONE);
Snackbar.make(constraintLayout, "No admin is associated with this authkey.", Snackbar.LENGTH_LONG).show();
return;
}
}
}
mispRestClient.getOrganisation(user.getRoleId(), new MispRestClient.OrganisationCallback() {
@Override
public void success(Organisation organisation) {
preferenceManager.setMyOrganisation(organisation);
preferenceManager.setUserCredentials(url, authkey);
progressBar.setVisibility(View.GONE);
Intent home = new Intent(getApplicationContext(), HomeActivity.class);
startActivity(home);
finish();
}
@Override
public void failure(String error) {
progressBar.setVisibility(View.GONE);
Snackbar.make(constraintLayout, error, Snackbar.LENGTH_LONG).show();
}
});
}
@Override
public void failure(String error) {
progressBar.setVisibility(View.GONE);
Snackbar.make(constraintLayout, error, Snackbar.LENGTH_LONG).show();
}
});
}
@Override
public void failure(String error) {
progressBar.setVisibility(View.GONE);
Snackbar.make(constraintLayout, error, Snackbar.LENGTH_LONG).show();
}
});
}
@Override
public void unavailable(String error) {
progressBar.setVisibility(View.GONE);
Snackbar.make(constraintLayout, error, Snackbar.LENGTH_LONG).show();
}
});
}
};
/**
* @param url url to check
* @return true if valid else false
*/
private boolean isValidUrl(String url) {
Uri uri = Uri.parse(url);
if (uri == null) {
return false;
}
return uri.getScheme() != null;
}
/**
* @param automationKey the key to check
* @return true if not empty else false
*/
private boolean isValidAutomationKey(String automationKey) {
return !automationKey.isEmpty();
}
}
|
Java
|
UTF-8
| 11,181
| 1.914063
| 2
|
[] |
no_license
|
package com.example.searchApplication;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.method.ScrollingMovementMethod;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* A simple {@link Fragment} subclass.
* Activities that contain this fragment must implement the
* {@link VenueFragment.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {@link VenueFragment#newInstance} factory method to
* create an instance of this fragment.
*/
public class VenueFragment extends Fragment implements OnMapReadyCallback {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public TextView venueNameTxtView;
public TextView venueAddrTxtView;
public TextView venueCityTxtView;
public TextView phoneNoTxtView;
public TextView openHTxtView;
public TextView gRuleTxtView;
public TextView gRuleLabel;
public TextView cRuleTxtView;
public String latx;
public String longx;
private OnFragmentInteractionListener mListener;
GoogleMap mGoogleMap;
MapView mMapView;
public VenueFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment VenueFragment.
*/
// TODO: Rename and change types and number of parameters
public static VenueFragment newInstance(String param1, String param2) {
VenueFragment fragment = new VenueFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_venue, container, false);
Bundle b = getActivity().getIntent().getExtras();
String Array = b.getString("Response");
venueNameTxtView = view.findViewById(R.id.textView37);
venueAddrTxtView = view.findViewById(R.id.textView38);
venueCityTxtView = view.findViewById(R.id.textView39);
phoneNoTxtView = view.findViewById(R.id.textView40);
openHTxtView = view.findViewById(R.id.textView41);
gRuleTxtView = view.findViewById(R.id.textView42);
gRuleTxtView.setMovementMethod(ScrollingMovementMethod.getInstance());
cRuleTxtView = view.findViewById(R.id.textView43);
cRuleTxtView.setMovementMethod(ScrollingMovementMethod.getInstance());
gRuleLabel = view.findViewById(R.id.textView35);
mMapView = (MapView) view.findViewById(R.id.map);
if(mMapView!=null)
{
mMapView.onCreate(null);
mMapView.onResume();
mMapView.getMapAsync(this);
}
// nameTxtView = view.findViewById(R.id.textView26);
// followerTxtView = view.findViewById(R.id.textView27);
// popularityTxtView = view.findViewById(R.id.textView28);
// checkAtTxtView = view.findViewById(R.id.textView29);
JSONObject embedded = null;
try {
embedded = (JSONObject) new JSONObject(Array).get("_embedded");
JSONArray venue = (JSONArray) embedded.get("venues");
String vname = venue.getJSONObject(0).get("name").toString();
makeVenueCall(ApplicationConstants.searchVenueURL
+ "?venueName=" + vname);
} catch (JSONException e)
{
e.printStackTrace();
}
return view;
}
private void makeVenueCall(String url) {
ApiCall.make(getContext(), url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//parsing logic, please change it as per your requirement
try {
JSONObject responseObjectOuter = new JSONObject(response);
JSONObject venueObj = (JSONObject) responseObjectOuter.get("_embedded");
JSONArray venuesArr = (JSONArray) venueObj.get("venues");
String venueN = venuesArr.getJSONObject(0).get("name").toString();
venueNameTxtView.setText(venueN);
JSONObject address = (JSONObject) venuesArr.getJSONObject(0).get("address");
String line = address.get("line1").toString();
venueAddrTxtView.setText(line);
JSONObject city = (JSONObject) venuesArr.getJSONObject(0).get("city");
String cityname = city.get("name").toString();
JSONObject state = (JSONObject) venuesArr.getJSONObject(0).get("state");
String statename = state.get("name").toString();
String cityFinal = cityname + "," + statename;
venueCityTxtView.setText(cityFinal);
JSONObject boxOffice = (JSONObject) venuesArr.getJSONObject(0).get("boxOfficeInfo");
String phone = boxOffice.get("phoneNumberDetail").toString();
phoneNoTxtView.setText(phone);
String openHours = boxOffice.get("openHoursDetail").toString();
openHTxtView.setText(openHours);
JSONObject gInfo = (JSONObject) venuesArr.getJSONObject(0).get("generalInfo");
String cRule = gInfo.get("childRule").toString();
cRuleTxtView.setText(cRule);
if(venuesArr.getJSONObject(0).has("generalRule"))
{
String gRule = gInfo.get("generalRule").toString();
gRuleTxtView.setText(gRule);
}
else
{
gRuleTxtView.setVisibility(View.GONE);
gRuleLabel.setVisibility(View.GONE);
}
JSONObject location = (JSONObject) venuesArr.getJSONObject(0).get("location");
latx = location.get("latitude").toString();
longx = location.get("longitude").toString();
onMapReady(mGoogleMap);
// JSONObject followers = (JSONObject) items.getJSONObject(0).get("followers");
// int fnumber = (int) followers.get("total");
// followerTxtView.setText(fnumber);
// String popularity = items.getJSONObject(0).get("popularity").toString();
// popularityTxtView.setText(popularity);
// JSONObject externalUrls = (JSONObject) items.getJSONObject(0).get("external_urls");
// String spotify = externalUrls.get("spotify").toString();
// checkAtTxtView.setText(spotify);
// JSONObject responseObject = responseObjectOuter.getJSONObject("_embedded");
// JSONArray array = responseObject.getJSONArray("events");
// List<String> stringList = new ArrayList<>();
// Intent intent = new Intent(getContext(), TabbedActivity.class);
//
// Bundle b = new Bundle();
// intent.putExtras(b);
// startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteractionVenue(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
// if (context instanceof OnFragmentInteractionListener) {
// mListener = (OnFragmentInteractionListener) context;
// } else {
// throw new RuntimeException(context.toString()
// + " must implement OnFragmentInteractionListener");
// }
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public void onMapReady(GoogleMap googleMap) {
MapsInitializer.initialize(getContext());
mGoogleMap = googleMap;
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
if ( !(latx == null) && !(longx ==null)) {
googleMap.addMarker(new MarkerOptions().position(new LatLng(Double.parseDouble(latx), Double.parseDouble(longx))));
CameraPosition mapFill = CameraPosition.builder().target(new LatLng(Double.parseDouble(latx), Double.parseDouble(longx))).zoom(16).bearing(0).tilt(0).build();
googleMap.moveCamera(CameraUpdateFactory.newCameraPosition(mapFill));
}
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteractionVenue(Uri uri);
}
}
|
Python
|
UTF-8
| 4,117
| 2.59375
| 3
|
[] |
no_license
|
import csv
import numpy
import matplotlib.pyplot as plt
from colorsys import hls_to_rgb
import random
fn = 'chitin_conts_four.csv'
tax_fn = 'Taxonomy.csv'
with open(fn, 'rU') as f:
rows = []
for row in csv.reader(f):
rows.append(row)
with open(tax_fn, 'rU') as f:
f_tax = []
for row in csv.reader(f):
f_tax.append(row)
ko, otu, count_cont, perc, ASV = [], [], [], [], []
for a in range(len(rows)):
ko.append(rows[a][0])
otu.append(rows[a][2])
count_cont.append(rows[a][5])
perc.append(rows[a][6])
ASV.append(rows[a][16])
tax = ASV
for a in range(len(f_tax)):
for b in range(len(tax)):
if f_tax[a][0] == tax[b]:
tax[b] = f_tax[a][3]
unique_ko = []
for a in range(len(ko)):
adding = True
for b in range(len(unique_ko)):
if ko[a] == unique_ko[b]:
adding = False
if adding:
unique_ko.append(ko[a])
del unique_ko[0]
unique_tax = []
for a in range(len(tax)):
adding = True
for b in range(len(unique_tax)):
if tax[a] == unique_tax[b]:
adding = False
if adding:
unique_tax.append(tax[a])
print unique_tax
new_otu, new_count_cont, new_perc, new_tax = [], [], [], []
for c in range(len(unique_ko)):
this_otu, this_count_cont, this_perc, this_tax = [], [], [], []
for d in range(len(ko)):
if ko[d] == unique_ko[c]:
this_otu.append(otu[d])
this_count_cont.append(float(count_cont[d])/100)
this_perc.append(perc[d])
this_tax.append(tax[d])
new_otu.append(this_otu)
new_count_cont.append(this_count_cont)
new_perc.append(this_perc)
new_tax.append(this_tax)
def get_distinct_colors(n):
colors = []
for i in numpy.arange(0., 360., 360. / n):
h = i / 360.
l = (50 + numpy.random.rand() * 10) / 100.
s = (90 + numpy.random.rand() * 10) / 100.
colors.append(hls_to_rgb(h, l, s))
random.shuffle(colors)
return colors
"""
ax1 = plt.subplot(111)
plot = new_count_cont
for a in range(len(plot)):
colors = get_distinct_colors(len(plot[a]))
x = a+1.1
ax1.bar([x], [plot[a][0]], color=[colors[0]], label=new_tax[a][0])
for j in xrange(1, len(plot[a])):
ax1.bar([x], [plot[a][j]], color=[colors[j]], bottom=[plot[a][j-1]], label=new_tax[a][j])
ax1.set_yscale('log')
ax1.set_ylabel('Gene copies')
plt.xticks([1.5, 2.5, 3.5, 4.5], unique_ko)
ax1.legend(bbox_to_anchor=(3, 1.03), ncol=3)
plt.savefig(fn[:-4]+'.png', bbox_inches='tight', dpi=600)
"""
"""
with open(fn, 'rU') as f:
rows = []
for row in csv.reader(f):
rows.append(row)
with open(tax_fn, 'rU') as f:
f_tax = []
for row in csv.reader(f):
f_tax.append(row)
asv, kegg, otu, count, abun, cont, tax = [], [], [], [], [], [], []
rest = []
col_names = ['GG OTU', 'KEGG', 'Sample', 'ASV', 'Gene copies', 'Abundance (%)', 'Contribution (%)', 'Phylum', 'Class', 'Order', 'Family', 'Genus', 'Species']
for a in range(len(rows)):
for b in range(len(rows[a])):
if rows[a][b][:3] == 'ASV':
asv.append(rows[a][b])
kegg.append(rows[a][0])
otu.append(rows[a][2])
count.append(rows[a][3])
abun.append(rows[a][4])
cont.append(rows[a][6])
rest.append([rows[a][2], rows[a][0], rows[a][1], rows[a][b], rows[a][3], rows[a][4], rows[a][6]])
for c in range(len(f_tax)):
if rows[a][b] == f_tax[c][0]:
tax.append(f_tax[c][1:])
with open('Chitin_conts_gamma_ASV.csv', 'w') as f:
writer = csv.writer(f)
writer.writerow(col_names)
for a in range(len(rest)):
writer.writerow(rest[a]+tax[a])
new = sorted(zip(asv, rest))
new2 = sorted(zip(asv, tax))
new_rest, new_tax = [], []
for a in range(len(new)):
new_rest.append(new[a][1])
new_tax.append(new2[a][1])
with open('Chitin_conts_gamma_ASV_sorted.csv', 'w') as f:
writer = csv.writer(f)
writer.writerow(col_names)
for a in range(len(new_rest)):
writer.writerow(new_rest[a]+new_tax[a])
"""
|
TypeScript
|
UTF-8
| 953
| 4.03125
| 4
|
[] |
no_license
|
// Helper methods on Figma's Vector type
export function add(v1: Vector, v2: Vector): Vector {
return {x: v1.x + v2.x, y: v1.y + v2.y}
}
export function subtract(v1: Vector, v2: Vector): Vector {
return {x: v1.x - v2.x, y: v1.y - v2.y}
}
export function distance(v1: Vector, v2: Vector): number {
const a = v1.x - v2.x
const b = v1.y - v2.y
return Math.sqrt(a * a + b * b)
}
// Return a vector such that vector v has magnitude of m
// e.g. vector {x: 1, y: 1}, m: 2.5 returns {x: 1.6, y: 1.6}
export function setMagnitude(v: Vector, m: number): Vector {
const mag = magnitude(v)
const m1 = m / mag
return multiply(v, m1)
}
export function multiply(v: Vector, m: number): Vector {
return {x: v.x * m, y: v.y * m}
}
export function normalize(v: Vector): Vector {
const length = magnitude(v)
return {x: v.x / length, y: v.y / length}
}
export function magnitude(v: Vector): number {
return Math.sqrt(v.x * v.x + v.y * v.y)
}
|
JavaScript
|
UTF-8
| 2,713
| 3.015625
| 3
|
[] |
no_license
|
const fs = require('fs');
const path = require('path');
const serveFile = require('./serve-file');
/** @function serveIndex~callback
* @param {string|object} error - any error encountered by
* serveIndex().
*/
/** @module serveIndex
* Serves the provided index.html file or generates
* a dynamic listing of a directory's contents
* @param {string} dirPath - the path to the directory
* @param {http.serverResponse} res - the response object
* @param {serveIndex~callback} callback - the callback to
* invoke once execution finishes
*/
module.exports = function serveAdmin(dirPath, res) {
//calls the serveFile function to serve the index.html file
serveFile(path.join(dirPath, 'admin.html'), res, function(err) {
//if it errors, call serveIndexListing
if(err) serveAdminListing(dirPath, res);
});
}
/** @callback serveIndexListing~callback
* @param {string|object} err - any error that occurred
*/
/** @function serveIndexListing()
* Serves a HTML list of directory contents
* @param {string} directoryPath - the path to the directory
* @param {http.serverResponse} res - the repsonse object
* @param {serveIndexListing~callback} callback - a callback to
* invoke once execution finishes.
*/
function serveAdminListing(dirPath, res) {
//call helper function to create html for index page
var html = generateAdminHTML(dirPath)
//if errors, return
//if(err) return;
// Serve html
// set content type
//
res.setHeader("Content-Type", "text/html");
//set content length
res.setHeader("Content-Length", html.length);
//serve file data
res.end(html);
return;
}
/** @callback generateIndex~callback
* @param {string|object} error - the error (if any)
* @param {string} html - the directory listing as HTML text
*/
/** @function generateIndex
* Generates a HTML page listing the contents
* of a directory.
* @param {string} dirPath - the path to the directory
* @param {generateIndex~callback} callback - a callback to invoke
* once execution completes.
*/
function generateAdminHTML(dirPath) {
//read the directory
var files = fs.readdirSync("public/admin");
// Create Links
var links = files.map(function(file) {
return `<a href="https://absurd-olympic-3000.codio.io/admin/${file}">${file}</a></br>`;
});
// Generate HTML
var html = `
<!DOCTYPE html>
<html>
<head>
<title>Index of Admin</title>
<head>
<body>
<h1>Index of Admin</h1>
<ul>
${links}
<ul>
</body>
<html>
`
return html;
}
|
Java
|
UTF-8
| 1,512
| 2.625
| 3
|
[] |
no_license
|
package com.davidhay.jlassignment.domain.inbound;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.math.BigDecimal;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
public class PriceTest {
@Nested
class InvalidPrices {
void checkInvalid(Price p) {
assertThat(p).isNotNull();
assertFalse(p.hasValidNowPrice());
}
@Test
void testEmptyProduct() {
checkInvalid(new Price());
}
@Test
void testPriceWithEmptyNow() {
Price price = new Price();
Now now = new Now();
price.setNow(now);
checkInvalid(price);
}
@Test
void testPriceWithNegativeNowTo() {
Price price = new Price();
Now now = new Now();
now.setTo(BigDecimal.TEN.negate());
price.setNow(now);
checkInvalid(price);
}
@Test
void testPriceWithZeroNowTo() {
Price price = new Price();
Now now = new Now();
now.setTo(BigDecimal.ZERO);
price.setNow(now);
checkInvalid(price);
}
}
@Nested
class ValidPrice {
void checkValid(Price p) {
assertThat(p).isNotNull();
assertTrue(p.hasValidNowPrice());
}
@Test
void testPriceWithPositiveNowTo() {
Price price = new Price();
Now now = new Now();
now.setTo(BigDecimal.ONE);
price.setNow(now);
checkValid(price);
}
}
}
|
C
|
UTF-8
| 3,240
| 2.671875
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
#include <stdbool.h>
#include <stdlib.h>
#include "uthash.h"
#include <errno.h>
#include "url_router/dict.h"
#define HASH_FIND_NSTR(head, findstr, len, out) \
HASH_FIND(hh, head, findstr, len, out)
#define HASH_ADD_NSTR(head, strfield, len, add) \
HASH_ADD(hh, head, strfield[0], len, add)
struct DictItem {
void *value;
UT_hash_handle hh;
char key[];
};
struct DictIterator {
struct DictItem *el;
};
struct Dict {
struct DictItem *head;
};
struct Dict *dict_new()
{
struct Dict *dict = malloc(sizeof(struct Dict));
if (dict != NULL) {
dict->head = NULL;
}
return dict;
}
void dict_free(struct Dict *dict, void (*fn_free_value)(void *))
{
struct Dict *d = (struct Dict *)dict;
struct DictItem *current, *tmp;
HASH_ITER(hh, d->head, current, tmp)
{
HASH_DEL(d->head, current);
if (fn_free_value != NULL) {
fn_free_value(current->value);
}
free(current);
}
free(d);
}
bool dict_add(struct Dict *dict, const char *key, void *value)
{
return dict_addl(dict, key, strlen(key), value);
}
bool dict_addl(struct Dict *dict, const char *key, int len, void *value)
{
struct Dict *d = (struct Dict *)dict;
struct DictItem *item;
HASH_FIND_NSTR(d->head, key, len, item);
if (item != NULL) {
return false;
}
item = malloc(sizeof(*item) + len + 1);
if (item == NULL) {
return false;
}
memcpy(item->key, key, len);
item->key[len] = 0;
item->value = value;
HASH_ADD_NSTR(d->head, key, len, item);
return true;
}
void *dict_get(struct Dict *dict, const char *key)
{
return dict_getl(dict, key, strlen(key));
}
void *dict_getl(struct Dict *dict, const char *key, int len)
{
struct Dict *d = (struct Dict *)dict;
struct DictItem *item;
HASH_FIND_NSTR(d->head, key, len, item);
if (item != NULL) {
return item->value;
}
return NULL;
}
void *dict_del(struct Dict *dict, const char *key)
{
return dict_dell(dict, key, strlen(key));
}
void *dict_dell(struct Dict *dict, const char *key, int len)
{
struct Dict *d = (struct Dict *)dict;
struct DictItem *item;
HASH_FIND_NSTR(d->head, key, len, item);
if (item != NULL) {
void *data = item->value;
HASH_DEL(d->head, item);
return data;
}
return NULL;
}
struct DictIterator *dict_iter_new(struct Dict *dict)
{
struct DictIterator *it = malloc(sizeof(struct DictIterator));
if (dict->head == NULL) {
return NULL;
}
it->el = dict->head;
return it;
}
int dict_iter_next(struct DictIterator *it, const char **key, void **value)
{
if (it->el == NULL) {
return -1;
}
*key = it->el->hh.key;
*value = it->el->value;
it->el = (it->el)->hh.next;
return 0;
}
int dict_iter_nextl(struct DictIterator *it,
const char **key,
int *keylen,
void **value)
{
if (it->el == NULL) {
return -1;
}
*key = it->el->hh.key;
*keylen = it->el->hh.keylen;
*value = it->el->value;
it->el = (it->el)->hh.next;
return 0;
}
void dict_iter_free(struct DictIterator *it)
{
free(it);
}
|
Shell
|
UTF-8
| 646
| 2.765625
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
#!/bin/bash
# source completion files
for dir in ${ROSWSS_SCRIPTS//:/ }; do
if [ -d "$dir/completion" ]; then
for file in `find -L $dir/completion/ -maxdepth 1 -type f -name "*.sh"`; do
source $file
done
fi
done
# default auto completion
add_completion "clean" "_roswss_clean_complete"
add_completion "install" "_roswss_install_complete"
add_completion "make" "_catkin_pkgs_complete"
add_completion "rosdoc" "_roswss_rosdoc_complete"
add_completion "test" "_roswss_test_complete"
add_completion "ui" "_roswss_ui_complete"
add_completion "uninstall" "_roswss_uninstall_complete"
add_completion "update" "_catkin_pkgs_complete"
|
TypeScript
|
UTF-8
| 5,499
| 2.828125
| 3
|
[] |
no_license
|
import { lerp } from "./util";
interface SoundInfo {
audio?: HTMLAudioElement;
loaded: boolean;
loadPromise?: Promise<void>;
}
enum MuteState {
PLAY_ALL = 0,
MUSIC_OFF = 1,
ALL_OFF = 2,
}
class _Sounds {
audios: {[key: string]: SoundInfo} = {};
curSong?: HTMLAudioElement;
curSongName?: string;
muteState = MuteState.PLAY_ALL;
playbackRate = 1;
/**
* Asynchronously fetches an audio.
*/
loadSound({name, path} : {name: string, path: string}) {
const promise = new Promise<void>((resolve) => {
if (this.audios.hasOwnProperty(name)) {
throw new Error(`Already loaded sound ${name}.`);
}
if (!path.endsWith('/')) {
path = path + '/';
}
const audioPath = `${path}${name}.mp3`;
this.audios[name] = {
loaded: false,
audio: undefined,
loadPromise: promise,
};
const audio = new Audio();
audio.oncanplaythrough = () => {
this.audios[name].audio = audio;
this.audios[name].loaded = true;
resolve();
}
audio.onerror = () => {
throw new Error(`Error loading audio ${name}.`);
}
audio.src = audioPath;
});
return promise;
}
playSound(name: string, {volume = 1}: {volume?: number} = {}) {
if (this.muteState == MuteState.ALL_OFF) {
return;
}
const audio = (this.audios[name].audio?.cloneNode() as HTMLAudioElement);
if (audio == null) {
return;
}
// TODO: Adjust SFX volumes, probably just here.
audio.volume *= volume;
audio.playbackRate = this.playbackRate;
// Disable type checking on these because not typescript doesn't know about them yet.
(audio as any).mozPreservesPitch = false;
(audio as any).webkitPreservesPitch = false;
(audio as any).preservesPitch = false;
audio.play();
}
/** We still run the logic here when muted, so that we can update things when unmuted. */
async setSong(songName: string) {
if (this.curSongName == songName) {
return;
}
const lastSongName = this.curSongName;
const lastSong = this.curSong;
this.curSong?.pause();
this.curSong = undefined;
this.curSongName = undefined;
const audioInfo = this.audios[songName];
if (audioInfo == null) {
// Setting an invalid song name is a way to stop audio from playing.
return;
}
// Ensure the song is loaded
await audioInfo.loadPromise;
const audio = (audioInfo.audio?.cloneNode() as HTMLAudioElement);
if (audio == null) {
return;
}
audio.volume = 0.5;
audio.loop = true;
// Disable type checking on these because not typescript doesn't know about them yet.
(audio as any).mozPreservesPitch = false;
(audio as any).webkitPreservesPitch = false;
(audio as any).preservesPitch = false;
if (lastSong != null) {
audio.playbackRate = lastSong.playbackRate;
if (lastSongName?.slice(0, 4) == songName.slice(0, 4)) {
audio.currentTime = lastSong.currentTime;
}
}
if (this.muteState == MuteState.PLAY_ALL) {
audio.play();
}
this.curSong = audio;
this.curSongName = songName;
}
updatePlaybackRate(desiredRate:number, dt: number) {
const updateAmt = 1 - Math.exp(-10 * dt);
this.playbackRate = lerp(this.playbackRate, desiredRate, updateAmt);
if (this.curSong != null) {
this.curSong.playbackRate = this.playbackRate;
}
}
loadMuteState() {
const storedMuteString = window.sessionStorage.getItem('mute') ?? "";
// Quick thing to make local dev default to music off.
if (storedMuteString == '' && window.location.href.includes('localhost')) {
console.log('Disabling music for local development');
this.muteState = MuteState.MUSIC_OFF;
return;
}
let muteState = parseInt(storedMuteString);
if (muteState != MuteState.PLAY_ALL &&
muteState != MuteState.MUSIC_OFF &&
muteState != MuteState.ALL_OFF) {
muteState = MuteState.PLAY_ALL;
}
this.muteState = muteState;
}
toggleMute() {
switch (this.muteState) {
case MuteState.PLAY_ALL:
this.muteState = MuteState.MUSIC_OFF;
break;
case MuteState.MUSIC_OFF:
this.muteState = MuteState.ALL_OFF;
break;
case MuteState.ALL_OFF:
default:
this.muteState = MuteState.PLAY_ALL;
break;
}
window.sessionStorage.setItem('mute', this.muteState.toString());
this.updateSoundMutedness();
}
updateSoundMutedness() {
switch (this.muteState) {
case MuteState.PLAY_ALL:
this.curSong?.play();
break;
case MuteState.MUSIC_OFF:
case MuteState.ALL_OFF:
this.curSong?.pause();
break;
}
}
}
export const Sounds = new _Sounds();
|
Java
|
UTF-8
| 172
| 1.859375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package nlp.symbolSampler;
import algebra.Vector;
import nlp.utils.Simplex;
public interface SymbolSampler {
String nextSymbol(Vector simplex, Simplex symTable);
}
|
JavaScript
|
UTF-8
| 769
| 2.875
| 3
|
[
"MIT"
] |
permissive
|
/* global chrome */
const TOKEN_NAME = 'pt_personal_token';
/**
* Saves options to chrome.storage
*/
function saveOptions() {
const token = document.getElementById('token').value;
chrome.storage.sync.set({
[TOKEN_NAME]: token
}, () => {
const status = document.getElementById('status');
status.textContent = 'Options saved.';
setTimeout(() => {
status.textContent = '';
}, 750);
});
}
/**
* Restores previously saved token
*/
function restoreOptions() {
chrome.storage.sync.get({
[TOKEN_NAME]: ''
}, item => {
document.getElementById('token').value = item[TOKEN_NAME];
});
}
document.addEventListener('DOMContentLoaded', restoreOptions);
document.getElementById('save').addEventListener('click', saveOptions);
|
Markdown
|
UTF-8
| 3,308
| 3.046875
| 3
|
[
"MIT"
] |
permissive
|
---
layout: post
title: 移动端实现1px
excerpt: 移动端实现1px像素线
categories: [教程, 移动端, css]
tags: [教程, 移动端, css]
modified: 2017-11-03
comments: true
---
## 问题描述
很多时候我们在css中写了1px,但是放到手机上看后,往往觉得会变粗很多,这都是2倍屏(dpr=2)、3倍屏(dpr=3)在捣鬼!所以导致css中的1px不等于移动设备的1px。
在window对象中有一个devicePixelRatio属性,他可以反应css中的像素与设备的像素比。devicePixelRatio的官方的定义为:设备物理像素和设备独立像素的比例,也就是 devicePixelRatio = 物理像素 / 独立像素。
常见的iphone4/iphone5/iphone6的devicePixelRatio=2,iphone6 plus的为3。具体的数据大家可以在chrome的console面板输入window.devicePixelRatio查看

## 解决方案
### 1.1/window.devicePixelRatio
{% highlight css %}
div {
border: 1px solid #000
}
@media (-webkit-min-device-pixel-ratio: 2) {
div {
border: 0.5px solid red
}
}
@media (-webkit-min-device-pixel-ratio: 3) {
div {
border: 0.3333px solid blue
}
}
{% endhighlight %}
so easy!妈妈再也不用担心1px的问题~
但是!!!安卓和iOS8以下设备无法识别。so sad。。。
### 2.使用渐变
{% highlight css %}
div {
background:
linear-gradient(#000, #000) top / 100% 1px no-repeat,
linear-gradient(#000, #000) right / 1px 100% no-repeat,
linear-gradient(#000, #000) bottom / 100% 1px no-repeat,
linear-gradient(#000, #000) left / 1px 100% no-repeat
}
{% endhighlight %}
但是这个如果边框有圆角的话就没办法实现啦
### 3.box shadow 模拟
{% highlight css %}
div {
box-shadow: inset 0px 0px 0px 1px #000; /*模拟下边框*/
}
{% endhighlight %}
但是box shadow 最佳效果是模拟一条边框,4条边框的话粗细会不一样哦
### 4.viewport + rem(推荐)
在`devicePixelRatio = 2`时,输出viewport:
{% highlight html %}
<meta name="viewport" content="initial-scale=0.5, maximum-scale=0.5, minimum-scale=0.5, user-scalable=no">
{% endhighlight %}
在`devicePixelRatio = 3`时,输出viewport:
{% highlight html %}
<meta name="viewport" content="initial-scale=0.3333333333333333, maximum-scale=0.3333333333333333, minimum-scale=0.3333333333333333, user-scalable=no">
{% endhighlight %}
这种方式就能和之前那样愉快的设置1px啦~可以引用淘宝的flexible.js文件,参考[这里](https://github.com/amfe/article/issues/17)
### 5.伪类 + transform
{% highlight css %}
.scale-1px{
position: relative;
border: 0;
}
.scale-1px:after{
content: '';
position: absolute;
top: 0;
left: 0;
border: 1px solid #000;
-webkit-box-sizing: border-box;
box-sizing: border-box;
width: 200%;
height: 200%;
-webkit-transform: scale(0.5);
transform: scale(0.5);
-webkit-transform-origin: left top;
transform-origin: left top;
}
{% endhighlight %}
这个方式如果 scale-1px 所在的容器含有浮动,4条边框就会出现不一样粗的问题,具体原因不清楚。。。所以如果要用这个方法,就尽量不要用浮动啦~~~
差不多完结啦~撒花❀~
|
Java
|
UTF-8
| 6,179
| 2.171875
| 2
|
[] |
no_license
|
package com.example.workhours;
import java.util.ArrayList;
import java.util.List;
import android.app.ActionBar;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import com.example.workhours.dao.UserDAO;
import com.example.workhours.dao.UserDAOImpl;
import com.example.workhours.entities.Notifier;
import com.example.workhours.entities.User;
import com.example.workhours.fragments.ProfileFragment;
import com.example.workhours.fragments.ProfileFragmentDetails;
import com.example.workhours.util.DetailsAdapter;
import com.example.workhours.util.InputValidator;
public class ProfileActivity extends FragmentActivity {
private UserDAO dao;
private TextView due;
private EditText employer_email_value, hourly_wage_value;
private ListView listView;
private Switch sw;
private String emp_email;
private Double hour_wage;
private User user;
private boolean updatedDetails;
private SeekBar dueDateSelector;
public static int dateDue;
public static String payment_M;
private DetailsAdapter adapter;
private List<User> users;
private FragmentManager frag;
private FragmentTransaction trans;
private ProfileFragment profile;
private ProfileFragmentDetails profile_d;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
frag = getSupportFragmentManager();
getFields();
dao = new UserDAOImpl(this);
dao.open();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String user_email = prefs.getString("email", null);
user = dao.getUser(user_email);
users = new ArrayList<User>(6);
users.add(user);
//BUGGY
users.add(null);
users.add(null);
users.add(null);
users.add(null);
users.add(null);
adapter = new DetailsAdapter(this, R.layout.details_layout, users);
listView = (ListView) findViewById(R.id.listView_details);
listView.setAdapter(adapter);
if(user != null)
fillForm();
}
public void changeDetails(View v) {
showChangeDetails();
updatedDetails = false;
}
/**
* Hides the fragment containing the user details
* and brings up the fragment for changing the details
* */
private void showChangeDetails() {
trans = frag.beginTransaction();
trans.hide(profile_d);
employer_email_value.setText(user.getEmployerEmail());
String s = Double.toString(user.getHourlyWage());
hourly_wage_value.setText(s);
hour_wage = 0.0;
dueDateSelector.setProgress(user.getScheduleDue());
due.setText("Day of the month: " + Integer.toString(user.getScheduleDue()));
dateDue = user.getScheduleDue();
if(user.getPerPay().equals("weekly")) {
sw.setChecked(true);
} else if (user.getPerPay().equals("monthly")) {
sw.setChecked(false);
}
trans.show(profile);
trans.commit();
}
public void saveDetails(View v) {
if(dateDue == 0) {
Toast.makeText(this, "Due date can't be 0", Toast.LENGTH_SHORT).show();
updatedDetails = false;
}
else if(dateDue != user.getScheduleDue()) {
user.setDueDate(dateDue);
dao.updateUser(user);
updatedDetails = true;
}
if(!payment_M.equals(user.getPerPay())) {
user.setPerPay(payment_M);
dao.updateUser(user);
updatedDetails = true;
}
try {
hour_wage = Double.parseDouble(hourly_wage_value.getText()
.toString());
if(user.getHourlyWage() != hour_wage) {
user.setHourlyWage(hour_wage);
dao.updateUser(user);
updatedDetails = true;
}
} catch (Exception e) {
Toast.makeText(this, "Invalid value", Toast.LENGTH_LONG).show();
updatedDetails = false;
}
emp_email = employer_email_value.getText().toString();
if (emp_email.matches("")) {
} else if (InputValidator.email(emp_email) == false) {
Toast.makeText(this, "Email not valid", Toast.LENGTH_SHORT).show();
updatedDetails = false;
} else {
if(!user.getEmployerEmail().equals(emp_email)) {
user.setEmployerEmail(emp_email);
dao.updateUser(user);
updatedDetails = true;
}
}
if (updatedDetails == true) {
showDetails();
/**
* Non of the details have been modified
* */
} else if(user.getEmployerEmail().equals(emp_email) && user.getHourlyWage() == hour_wage
&& user.getScheduleDue() == dateDue && user.getPerPay().equals(payment_M)) {
showDetails();
} else{
showChangeDetails();
}
Notifier n = new Notifier(getApplicationContext(), null, user);
n.dueDateNotify();
}
public void cancelUpdate(View v) {
showDetails();
}
private void showDetails() {
fillForm();
trans = frag.beginTransaction();
trans.hide(profile);
trans.commit();
}
private void fillForm() {
users.remove(0);
users.add(0, user);
DetailsAdapter.user = users;
adapter.notifyDataSetChanged();
trans = frag.beginTransaction();
trans.hide(profile);
trans.show(profile_d);
trans.commit();
}
private void getFields() {
employer_email_value = (EditText) findViewById(R.id.change_employer_email);
hourly_wage_value = (EditText) findViewById(R.id.change_hourly_wage);
profile = (ProfileFragment) frag.findFragmentById(R.id.profile);
profile_d = (ProfileFragmentDetails) frag.findFragmentById(R.id.profile_details);
dueDateSelector = (SeekBar) findViewById(R.id.due_day);
sw = (Switch) findViewById(R.id.payment_mode);
due = (TextView) findViewById(R.id.due_date_displayer);
}
@Override
protected void onResume() {
dao.open();
super.onResume();
}
@Override
protected void onPause() {
dao.close();
super.onPause();
}
}
|
Python
|
UTF-8
| 8,169
| 2.9375
| 3
|
[
"MIT"
] |
permissive
|
import math
import time
class LossStatistics:
"""
Accumulator for loss staistics. Modified from OpenNMT
"""
def __init__(self, loss=0.0, n_tokens=0, n_batch=0, forward_time=0.0, loss_compute_time=0.0, backward_time=0.0):
assert type(loss) is float or type(loss) is int
assert type(n_tokens) is int
self.loss = loss
if math.isnan(loss):
raise ValueError("Loss is NaN")
self.n_tokens = n_tokens
self.n_batch = n_batch
self.forward_time = forward_time
self.loss_compute_time = loss_compute_time
self.backward_time = backward_time
def update(self, stat, update_n_src_words=False):
"""
Update statistics by suming values with another `LossStatistics` object
Args:
stat: another statistic object
"""
self.loss += stat.loss
if math.isnan(stat.loss):
raise ValueError("Loss is NaN")
self.n_tokens += stat.n_tokens
self.n_batch += stat.n_batch
self.forward_time += stat.forward_time
self.loss_compute_time += stat.loss_compute_time
self.backward_time += stat.backward_time
def xent(self):
""" compute normalized cross entropy """
assert self.n_tokens > 0, "n_tokens must be larger than 0"
return self.loss / self.n_tokens
def ppl(self):
""" compute normalized perplexity """
assert self.n_tokens > 0, "n_tokens must be larger than 0"
return math.exp(min(self.loss / self.n_tokens, 100))
def total_time(self):
return self.forward_time, self.loss_compute_time, self.backward_time
def clear(self):
self.loss = 0.0
self.n_tokens = 0
self.n_batch = 0
self.forward_time = 0.0
self.loss_compute_time = 0.0
self.backward_time = 0.0
class RewardStatistics:
"""
Accumulator for reward staistics.
"""
def __init__(self, final_reward=0.0, pg_loss=0.0, n_batch=0, sample_time=0, q_estimate_compute_time=0, backward_time=0):
self.final_reward = final_reward
self.pg_loss = pg_loss
if math.isnan(pg_loss):
raise ValueError("Policy gradient loss is NaN")
self.n_batch = n_batch
self.sample_time = sample_time
self.q_estimate_compute_time = q_estimate_compute_time
self.backward_time = backward_time
def update(self, stat):
self.final_reward += stat.final_reward
if math.isnan(stat.pg_loss):
raise ValueError("Policy gradient loss is NaN")
self.pg_loss += stat.pg_loss
self.n_batch += stat.n_batch
self.sample_time += stat.sample_time
self.q_estimate_compute_time += stat.q_estimate_compute_time
self.backward_time += stat.backward_time
def reward(self):
assert self.n_batch > 0, "n_batch must be positive"
return self.final_reward / self.n_batch
def loss(self):
assert self.n_batch > 0, "n_batch must be positive"
return self.pg_loss / self.n_batch
def total_time(self):
return self.sample_time, self.q_estimate_compute_time, self.backward_time
def clear(self):
self.final_reward = 0.0
self.pg_loss = 0.0
self.n_batch = 0.0
self.sample_time = 0.0
self.q_estimate_compute_time = 0.0
self.backward_time = 0.0
class LagrangianStatistics:
def __init__(self, lagrangian_loss=0.0, lagrangian_grad_norm=0.0, violate_amount=0, n_batch=0):
self.lagrangian_loss = lagrangian_loss
if math.isnan(lagrangian_loss):
raise ValueError("Loss is NaN")
self.lagrangian_grad_norm = lagrangian_grad_norm
self.violate_amount = violate_amount
self.n_batch = n_batch
def update(self, stat):
self.lagrangian_loss += stat.lagrangian_loss
self.n_batch += stat.n_batch
self.lagrangian_grad_norm += stat.lagrangian_grad_norm
self.violate_amount += stat.violate_amount
def clear(self):
self.lagrangian_loss = 0.0
self.lagrangian_grad_norm = 0.0
self.n_batch = 0
self.violate_amount = 0
def loss(self):
assert self.n_batch > 0, "n_batch must be positive"
return self.lagrangian_loss / self.n_batch
def grad_norm(self):
assert self.n_batch > 0, "n_batch must be positive"
return self.lagrangian_grad_norm / self.n_batch
def violate_amt(self):
assert self.n_batch > 0, "n_batch must be positive"
return self.violate_amount / self.n_batch
class JointLossStatistics:
"""
Accumulator for loss staistics. Modified from OpenNMT
"""
def __init__(self, joint_loss=0.0, generation_loss=0.0, enc_classification_loss=0.0, dec_classification_loss=0.0, inconsist_loss=0.0, n_iterations=0, n_tokens=0, forward_time=0.0, loss_compute_time=0.0, backward_time=0.0):
assert type(joint_loss) is float or type(joint_loss) is int
assert type(n_iterations) is int
self._joint_loss = joint_loss
if math.isnan(joint_loss):
raise ValueError("Loss is NaN")
self._generation_loss = generation_loss
self._enc_classification_loss = enc_classification_loss
self._dec_classification_loss = dec_classification_loss
self._inconsist_loss = inconsist_loss
self._n_iterations = n_iterations
self._n_tokens = n_tokens
self._forward_time = forward_time
self._loss_compute_time = loss_compute_time
self._backward_time = backward_time
def update(self, stat):
"""
Update statistics by suming values with another `LossStatistics` object
Args:
stat: another statistic object
"""
self._joint_loss += stat._joint_loss
self._generation_loss += stat._generation_loss
self._enc_classification_loss += stat._enc_classification_loss
self._dec_classification_loss += stat._dec_classification_loss
self._inconsist_loss += stat._inconsist_loss
if math.isnan(stat._joint_loss):
raise ValueError("Loss is NaN")
self._n_iterations += stat._n_iterations
self._n_tokens += stat._n_tokens
self._forward_time += stat._forward_time
self._loss_compute_time += stat._loss_compute_time
self._backward_time += stat._backward_time
def generation_loss(self):
""" compute normalized cross entropy """
assert self._n_tokens > 0, "n_tokens must be larger than 0"
return self._generation_loss / self._n_tokens
def ppl(self):
""" compute normalized perplexity """
assert self._n_tokens > 0, "n_tokens must be larger than 0"
return math.exp(min(self._generation_loss / self._n_tokens, 100))
def joint_loss(self):
assert self._n_iterations > 0, "n_tokens must be larger than 0"
return self._joint_loss / self._n_iterations
def classification_loss(self):
assert self._n_iterations > 0, "n_tokens must be larger than 0"
return (self._enc_classification_loss + self._dec_classification_loss) / self._n_iterations
def enc_classification_loss(self):
assert self._n_iterations > 0, "n_tokens must be larger than 0"
return self._enc_classification_loss / self._n_iterations
def dec_classification_loss(self):
assert self._n_iterations > 0, "n_tokens must be larger than 0"
return self._dec_classification_loss / self._n_iterations
def inconsist_loss(self):
assert self._n_iterations > 0, "n_tokens must be larger than 0"
return self._inconsist_loss / self._n_iterations
def total_time(self):
return self._forward_time, self._loss_compute_time, self._backward_time
def clear(self):
self._joint_loss = 0.0
self._generation_loss = 0.0
self._enc_classification_loss = 0.0
self._dec_classification_loss = 0.0
self._inconsist_loss = 0.0
self._n_iterations = 0
self._n_tokens = 0
self._forward_time = 0.0
self._loss_compute_time = 0.0
self._backward_time = 0.0
|
C
|
UTF-8
| 14,175
| 2.78125
| 3
|
[] |
no_license
|
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <tchar.h>
#include "faxutil.h"
DWORD SetLTRWindowLayout(HWND hWnd);
DWORD SetLTREditBox(HWND hEdit);
///////////////////////////////////////////////////////////////////////////////////////
// Function:
// IsRTLUILanguage
//
// Purpose:
// Determine User Default UI Language layout
//
// Return Value:
// TRUE if the User Default UI Language has Right-to-Left layout
// FALSE otherwise
///////////////////////////////////////////////////////////////////////////////////////
BOOL
IsRTLUILanguage()
{
#if(WINVER >= 0x0500)
LANGID langID; // language identifier for the current user language
WORD primLangID; // primary language identifier
DEBUG_FUNCTION_NAME(TEXT("IsRTLUILanguage"));
langID = GetUserDefaultUILanguage();
if(langID == 0)
{
DebugPrintEx(DEBUG_ERR,TEXT("GetUserDefaultUILanguage failed."));
return TRUE;
}
primLangID = PRIMARYLANGID(langID);
if(LANG_ARABIC == primLangID ||
LANG_HEBREW == primLangID)
{
//
// If the UI Language is Arabic or Hebrew the layout is Right-to-Left
//
return TRUE;
}
#endif /* WINVER >= 0x0500 */
return FALSE;
}
///////////////////////////////////////////////////////////////////////////////////////
// Function:
// IsWindowRTL
//
// Purpose:
// Determine if the window has RTL layout
//
// Params:
// hWnd - window handle
// Return Value:
// TRUE if the window has RTL layout
// FALSE otherwise
///////////////////////////////////////////////////////////////////////////////////////
BOOL
IsWindowRTL(
HWND hWnd
)
{
BOOL bRes = FALSE;
#if(WINVER >= 0x0500)
LONG_PTR style;
style = GetWindowLongPtr(hWnd, GWL_EXSTYLE);
if(WS_EX_LAYOUTRTL == (style & WS_EX_LAYOUTRTL))
{
bRes = TRUE;
}
#endif /* WINVER >= 0x0500 */
return bRes;
}
///////////////////////////////////////////////////////////////////////////////////////
// Function:
// SetLTRControlLayout
//
// Purpose:
// Set left-to-right layout for a dialog control
// if the user default UI has RTL layout
//
// Params:
// hDlg - Dialog handle
// dwCtrlID - control ID
//
// Return Value:
// standard error code
///////////////////////////////////////////////////////////////////////////////////////
DWORD
SetLTRControlLayout(
HWND hDlg,
DWORD dwCtrlID
)
{
DWORD dwRes = ERROR_SUCCESS;
#if(WINVER >= 0x0500)
HWND hCtrl;
DEBUG_FUNCTION_NAME(TEXT("SetLTRControlLayout"));
if(!hDlg || !dwCtrlID)
{
Assert(FALSE);
return ERROR_INVALID_PARAMETER;
}
if(!IsWindowRTL(hDlg))
{
//
// The dialog is not RTL
// So, no need to revert control
//
return dwRes;
}
//
// Get Control box handle
//
hCtrl = GetDlgItem(hDlg, dwCtrlID);
if(!hCtrl)
{
dwRes = GetLastError();
DebugPrintEx(DEBUG_ERR,TEXT("GetDlgItem failed with %ld."),dwRes);
return dwRes;
}
dwRes = SetLTRWindowLayout(hCtrl);
if(ERROR_SUCCESS != dwRes)
{
DebugPrintEx(DEBUG_ERR,TEXT("SetLTRWindowLayout failed with %ld."),dwRes);
}
#endif /* WINVER >= 0x0500 */
return dwRes;
} // SetLTRControlLayout
///////////////////////////////////////////////////////////////////////////////////////
// Function:
// SetLTREditDirection
//
// Purpose:
// Set left aligment for an dialog edit box
// if the user default UI has RTL layout
//
// Params:
// hDlg - Dialog handle
// dwEditID - Edit box control ID
//
// Return Value:
// standard error code
///////////////////////////////////////////////////////////////////////////////////////
DWORD
SetLTREditDirection(
HWND hDlg,
DWORD dwEditID
)
{
DWORD dwRes = ERROR_SUCCESS;
#if(WINVER >= 0x0500)
HWND hCtrl;
DEBUG_FUNCTION_NAME(TEXT("SetLtrEditDirection"));
if(!hDlg || !dwEditID)
{
Assert(FALSE);
return ERROR_INVALID_PARAMETER;
}
if(!IsWindowRTL(hDlg))
{
//
// The dialog is not RTL
// So, no need to revert control
//
return dwRes;
}
//
// Get Edit box handle
//
hCtrl = GetDlgItem(hDlg, dwEditID);
if(!hCtrl)
{
dwRes = GetLastError();
DebugPrintEx(DEBUG_ERR,TEXT("GetDlgItem failed with %ld."),dwRes);
return dwRes;
}
dwRes = SetLTREditBox(hCtrl);
if(ERROR_SUCCESS != dwRes)
{
DebugPrintEx(DEBUG_ERR,TEXT("SetLTREditBox failed with %ld."),dwRes);
}
#endif /* WINVER >= 0x0500 */
return dwRes;
} // SetLTREditDirection
//////////////////////////////////////////////////////////////////////////////////////
// Function:
// SetLTRWindowLayout
//
// Purpose:
// Set left-to-right layout for a window
// if the user default UI has RTL layout
//
// Params:
// hWnd - Window handle
//
// Return Value:
// standard error code
//////////////////////////////////////////////////////////////////////////////////////
DWORD
SetLTRWindowLayout(
HWND hWnd
)
{
DWORD dwRes = ERROR_SUCCESS;
#if(WINVER >= 0x0500)
LONG_PTR style;
DEBUG_FUNCTION_NAME(TEXT("SetLTRWindowLayout"));
if(!hWnd)
{
Assert(FALSE);
return ERROR_INVALID_PARAMETER;
}
//
// Remove RTL and add LTR to ExStyle
//
style = GetWindowLongPtr(hWnd, GWL_EXSTYLE);
style &= ~(WS_EX_LAYOUTRTL | WS_EX_RIGHT | WS_EX_RTLREADING);
style |= WS_EX_LEFT | WS_EX_LTRREADING;
SetWindowLongPtr(hWnd, GWL_EXSTYLE, style);
//
// Refresh the window
//
if(!SetWindowPos(hWnd, 0, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED))
{
dwRes = GetLastError();
DebugPrintEx(DEBUG_ERR,TEXT("SetWindowPos failed with %ld."),dwRes);
}
#endif /* WINVER >= 0x0500 */
return dwRes;
} // SetLTRWindowLayout
//////////////////////////////////////////////////////////////////////////////////////
// Function:
// SetLTREditBox
//
// Purpose:
// Set left aligment for an dialog edit box
// if the user default UI has RTL layout
//
// Params:
// hEdit - edit box handle
//
// Return Value:
// standard error code
//////////////////////////////////////////////////////////////////////////////////////
DWORD
SetLTREditBox(
HWND hEdit
)
{
DWORD dwRes = ERROR_SUCCESS;
#if(WINVER >= 0x0500)
LONG_PTR style;
DEBUG_FUNCTION_NAME(TEXT("SetLTREditBox"));
if(!hEdit)
{
Assert(FALSE);
return ERROR_INVALID_PARAMETER;
}
//
// Remove RTL and add LTR to Style
//
style = GetWindowLongPtr(hEdit, GWL_STYLE);
style &= ~ES_RIGHT;
style |= ES_LEFT;
SetWindowLongPtr(hEdit, GWL_STYLE, style);
dwRes = SetLTRWindowLayout(hEdit);
if(ERROR_SUCCESS != dwRes)
{
DebugPrintEx(DEBUG_ERR,TEXT("SetLTRWindowLayout failed with %ld."),dwRes);
}
#endif /* WINVER >= 0x0500 */
return dwRes;
} // SetLTREditBox
//////////////////////////////////////////////////////////////////////////////////////
// Function:
// SetLTRComboBox
//
// Purpose:
// Set left aligment for an dialog combo box
// if the user default UI has RTL layout
//
// Params:
// hDlg - Dialog handle
// dwCtrlID - combo box control ID
//
// Return Value:
// standard error code
//////////////////////////////////////////////////////////////////////////////////////
DWORD
SetLTRComboBox(
HWND hDlg,
DWORD dwCtrlID
)
{
DWORD dwRes = ERROR_SUCCESS;
#if(WINVER >= 0x0500)
HWND hCtrl;
COMBOBOXINFO comboBoxInfo = {0};
DEBUG_FUNCTION_NAME(TEXT("SetLTRComboBox"));
if(!hDlg || !dwCtrlID)
{
Assert(FALSE);
return ERROR_INVALID_PARAMETER;
}
if(!IsWindowRTL(hDlg))
{
//
// The dialog is not RTL
// So, no need to revert control
//
return dwRes;
}
//
// Get combo box handle
//
hCtrl = GetDlgItem(hDlg, dwCtrlID);
if(!hCtrl)
{
dwRes = GetLastError();
DebugPrintEx(DEBUG_ERR,TEXT("GetDlgItem failed with %ld."),dwRes);
return dwRes;
}
comboBoxInfo.cbSize = sizeof(comboBoxInfo);
if(GetComboBoxInfo(hCtrl, &comboBoxInfo))
{
SetLTREditBox(comboBoxInfo.hwndItem);
SetLTRWindowLayout(comboBoxInfo.hwndCombo);
SetLTRWindowLayout(comboBoxInfo.hwndList);
}
else
{
dwRes = GetLastError();
DebugPrintEx(DEBUG_ERR,TEXT("GetComboBoxInfo failed with %ld."),dwRes);
return dwRes;
}
#endif /* WINVER >= 0x0500 */
return dwRes;
} // SetLTRComboBox
///////////////////////////////////////////////////////////////////////////////////////
// Function:
// StrHasRTLChar
//
// Purpose:
// Determine if the string has RTL characters
//
// Params:
// pStr - string to analize
//
// Return Value:
// TRUE if the string has RTL characters
// FALSE otherwise
///////////////////////////////////////////////////////////////////////////////////////
BOOL
StrHasRTLChar(
LCID Locale,
LPCTSTR pStr
)
{
BOOL bRTL = FALSE;
DWORD dw;
WORD* pwStrData = NULL;
DWORD dwStrLen = 0;
DEBUG_FUNCTION_NAME(TEXT("StrHasRTLChar"));
if(!pStr)
{
DebugPrintEx(DEBUG_ERR, TEXT("pStr is NULL"));
return bRTL;
}
dwStrLen = _tcslen(pStr);
pwStrData = (WORD*)MemAlloc(sizeof(WORD) * dwStrLen);
if(!pwStrData)
{
DebugPrintEx(DEBUG_ERR, TEXT("MemAlloc"));
return bRTL;
}
if (!GetStringTypeEx(Locale,
CT_CTYPE2,
pStr,
dwStrLen,
pwStrData))
{
DebugPrintEx(DEBUG_ERR, TEXT("GetStringTypeEx() failed : %ld"), GetLastError());
goto exit;
}
//
// Looking for a character with RIGHT_TO_LEFT orientation
//
for (dw=0; dw < dwStrLen; ++dw)
{
if (C2_RIGHTTOLEFT == pwStrData[dw])
{
bRTL = TRUE;
break;
}
}
exit:
MemFree(pwStrData);
return bRTL;
} // StrHasRTLChar
///////////////////////////////////////////////////////////////////////////////////////
// Function:
// AlignedMessageBox
//
// Purpose:
// Display message box with correct reading order and alignment
//
// Params:
// pStr - string to analize
//
// Return Value:
// MessageBox() return value
//
///////////////////////////////////////////////////////////////////////////////////////
int
AlignedMessageBox(
HWND hWnd, // handle to owner window
LPCTSTR lpText, // text in message box
LPCTSTR lpCaption, // message box title
UINT uType // message box style
)
{
int nRes = 0;
if(IsRTLUILanguage())
{
uType |= MB_RTLREADING | MB_RIGHT;
}
nRes = MessageBox(hWnd, lpText, lpCaption, uType);
return nRes;
}
///////////////////////////////////////////////////////////////////////////////////////
// Function:
// FaxTimeFormat
//
// Purpose:
// Format time string with correct reading order
//
// Params:
// see GetTimeFormat() parameters
//
// Return Value:
// GetTimeFormat() return value
//
///////////////////////////////////////////////////////////////////////////////////////
int
FaxTimeFormat(
LCID Locale, // locale
DWORD dwFlags, // options
CONST SYSTEMTIME *lpTime, // time
LPCTSTR lpFormat, // time format string
LPTSTR lpTimeStr, // formatted string buffer
int cchTime // size of string buffer
)
{
int nRes = 0;
TCHAR szTime[MAX_PATH];
nRes = GetTimeFormat(Locale, dwFlags, lpTime, lpFormat, szTime, min(cchTime, MAX_PATH));
if(0 == nRes)
{
return nRes;
}
if(0 == cchTime)
{
return ++nRes;
}
if(IsRTLLanguageInstalled())
{
if(StrHasRTLChar(Locale, szTime))
{
_sntprintf(lpTimeStr, cchTime, TEXT("%c%s"), UNICODE_RLM, szTime);
}
else
{
_sntprintf(lpTimeStr, cchTime, TEXT("%c%s"), UNICODE_LRM, szTime);
}
}
else
{
_tcsncpy(lpTimeStr, szTime, cchTime);
}
return nRes;
} // FaxTimeFormat
///////////////////////////////////////////////////////////////////////////////////////
// Function:
// IsRTLLanguageInstalled
//
// Purpose:
// Determine if RTL Language Group is Installed
//
// Return Value:
// TRUE if RTL Language Group is Installed
// FALSE otherwise
///////////////////////////////////////////////////////////////////////////////////////
BOOL
IsRTLLanguageInstalled()
{
#if(WINVER >= 0x0500)
if(IsValidLanguageGroup(LGRPID_ARABIC, LGRPID_INSTALLED) ||
IsValidLanguageGroup(LGRPID_HEBREW, LGRPID_INSTALLED))
{
return TRUE;
}
else
{
return FALSE;
}
#endif /* WINVER >= 0x0500 */
return FALSE;
} // IsRTLLanguageInstalled
|
C#
|
UTF-8
| 321
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
namespace Monad
{
/// <summary>
/// Used to append/combine the current object and the one provided.
/// This is used to support the operator+ overload on the monad types
/// </summary>
/// <typeparam name="T"></typeparam>
public interface IAppendable<T>
{
T Append(T rhs);
}
}
|
Ruby
|
UTF-8
| 1,782
| 3.078125
| 3
|
[] |
no_license
|
# frozen_string_literal: true
require 'byebug'
class Teller
class InaccurateMoneyError < StandardError; end
class IncompleteMoneyError < StandardError; end
class FloatDenominationError < StandardError; end
attr_accessor :denomination, :money, :money_left, :combinations, :result
def self.make_change(opts)
new(opts).send(:call)
end
def initialize(opts)
self.denomination = opts.fetch(:denomination, [1])
self.money = opts.fetch(:money, 1)
self.money_left = money
self.combinations = [nil] * (money + 1)
self.result = []
check_inaccurate_money
check_denominations
end
private
def call(**_opts)
combinations_array
results_array
result
end
def combinations_array
work = [[0, 0]]
while combinations[money].nil? && !work.empty?
base, starting_index = work.shift
starting_index.upto(denomination.size - 1) do |index|
coin = denomination[index]
total = base + coin
next unless total <= money && combinations[total].nil?
combinations[total] = base
work << [total, index]
end
end
end
def results_array
check_incomplete_money
while money_left.positive?
array1 = combinations[money_left]
result << money_left - array1
self.money_left = array1
end
end
def check_incomplete_money
return unless combinations[money].nil?
raise(
IncompleteMoneyError,
'Total must be a multiple of smaller denomination'
)
end
def check_inaccurate_money
return if money.positive?
raise(InaccurateMoneyError, 'Money cannot be less that 0')
end
def check_denominations
return unless (denomination.any? && denomination.min < 1) || (money < 1)
raise(FloatDenominationError)
end
end
|
Python
|
UTF-8
| 6,163
| 2.96875
| 3
|
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 16 11:50:53 2014
@author: colin4567
"""
import numpy as np
import pandas as pd
import datetime
from config import Config
from backtest import Backtest
from data import HistoricCSVDataHandler
from data import MySQLDataHandler
from event import FinishEvent
from event import SignalEvent
from execution import SimulatedExecutionHandler
from portfolio import Portfolio
from strategy import Strategy
class MovingAverageCrossStrategy(Strategy):
"""
Default window is 34/144
"""
def __init__(self, conf,bars, events, timerEvents, short_window=34, long_window=144):
"""
Initializes the buy and hold strategy
Parameters:
bars - DataHandler object that provides bar info
events - Event queue object
short/long windows - moving average lookbacks
"""
self.conf = conf
self.bars = bars
#self.symbol_list = self.conf.symbol_list
self.events = events
self.timerEvents = timerEvents
self.short_window = short_window
self.long_window = long_window
#set to true if a symbol if in the market
self.bought = self._calculate_initial_bought()
def _calculate_initial_bought(self):
"""
Adds keys to the bought dictionary for all symbols and sets them to 'OUT'
"""
bought = {}
for s in self.conf.symbol_list:
bought[s] = 'OUT'
return bought
def calculate_signals(self, event):
"""
calculate_signals is the implementation of abstract method
Generates a new SignalEvent object and places it on the
Event queue, and updates the bought attribute.
Parameters:
event - a MarketEvent object
To Do:
strength needs to be applied to all positions when a new symbol comes on, not just to new position
"""
if event.type == 'MARKET':
for symbol in self.bars.latest_symbol_list:
bars = self.bars.get_latest_bars_values(symbol, "adj_close", N=self.long_window)
"""
bars is 'numpy.ndarray', look like
[18.0241 17.9855 17.6026 17.4895 17.5229 17.4239 17.4625 17.9251 17.654
......
25.4753 25.7491 25.9727 26.8646 27.1948 26.8723 27.1987 27.082 27.5508]
"""
# dt start from 2010-01-05 , which is conf.start_date
dt = self.bars.get_latest_bar_datetime(symbol)
if (dt >= self.conf.end_date):
self.events.put(FinishEvent())
elif bars is not None and bars != []:
#bars end at 'current date', now calculate the SMA
short_sma = np.mean(bars[-self.short_window:])
long_sma = np.mean(bars[-self.long_window:])
sig_dir = ""
strength = 1.0 / len(self.bars.latest_symbol_list) #this is where you set percentage of capital - how can I easily rescale previous positions when new symbol becomes eligable
strategy_id = 1
if short_sma > long_sma and self.bought[symbol] == 'OUT':
#short_sma > long_sma is LONG trigger
sig_dir = 'LONG'
#SignalEvent set event.type to 'SIGNAL', then
#backtest process it
signal = SignalEvent(strategy_id, symbol, dt, sig_dir, strength)
self.events.put(signal)
self.bought[symbol] = 'LONG' ## change state
elif short_sma < long_sma and self.bought[symbol] == 'LONG':
#short_sma < long_sma is EXIT trigger
sig_dir = 'EXIT'
signal = SignalEvent(strategy_id, symbol, dt, sig_dir, strength)
self.events.put(signal)
self.bought[symbol] = 'OUT' ## change state
if __name__ == '__main__':
import os
##symbol_list = ['ba', 'noc', 'lmt', 'nwsa', 'goog', 'alle', 'navi']
#symbol_list = ['AAPL']
#broken = ['nwsa', 'goog', 'alle', 'navi']
#symbols = pd.read_csv("C:/Users/colin4567/Dropbox/EventTradingEngine/getData/testData/sp500ticks.csv"); symbol_list = symbols['tickers'].tolist()
#initial_capital = 1000000.0 #1m
#start_date = datetime.datetime(2010,1,1,0,0,0)
#end_date = datetime.datetime(2015,12,31,0,0,0) ##start <5 years> end
#test_date = datetime.datetime(2015,1,1,0,0,0) ##test_last year
#heartbeat = 0.0
#data_feed = 2 # 1 is csv, 2 is MySQL
conf = Config()
for asymbol in conf.whole_list:
conf.symbol_list = []
conf.symbol_list.append(asymbol)
if conf.data_feed == 1:
if os.path.isdir(conf.csv_dir):
csv_dir = os.path.normpath(conf.csv_dir)
else:
raise SystemExit("No csv dir found ")
backtest = Backtest(conf,
HistoricCSVDataHandler,
SimulatedExecutionHandler,
Portfolio,
MovingAverageCrossStrategy)
backtest.simulate_trading() ## trigger the backtest
elif conf.data_feed == 2:
backtest = Backtest(conf,
MySQLDataHandler,
SimulatedExecutionHandler,
Portfolio,
MovingAverageCrossStrategy)
backtest.simulate_trading() ## trigger the backtest
#end of for whole_list
|
C++
|
UTF-8
| 3,547
| 3.84375
| 4
|
[] |
no_license
|
#include <iostream>
#include <string>
/*
通常业务代码中会有这样的结构:
if (i == 1) {
handler1.handle(req);
} else if (i == 2) {
handler2.handle(req);
} ...
这样的处理流程不仅显得臃肿,而且耦合度高。
可以使用责任链模式来处理,如果不满足则向下传递.
*/
class Level {
public:
Level(int l) : _l(l) {}
Level() : _l(0) {}
bool operator>(const Level& level) {
if (this->_l >= level._l) {
return true;
}
return false;
}
bool above(Level* level) {
if (this->_l >= level->_l) {
return true;
}
return false;
}
private:
int _l;
};
class Request {
public:
Request(Level* level) : _level(level) {}
Level* getLevel() {
return _level;
}
private:
Level* _level;
};
class Response {
public:
Response(const std::string& msg) : _msg(msg) {}
Response(){}
void setMsg(const std::string& msg) {
this->_msg = msg;
}
std::string getMsg() {
return _msg;
}
private:
std::string _msg;
};
class IHandler {
public:
Response handleRequest(Request* req) {
Response resp;
if (*(this->getHandlerLevel()) > *(req->getLevel())) {
resp = this->handle(req);
} else {
if (this->_nextHandler != NULL) {
resp = this->_nextHandler->handleRequest(req);
} else {
std::cerr << "No handler found!" << std::endl;
}
}
return resp;
}
void setNextHandler(IHandler* handler) {
this->_nextHandler = handler;
}
protected:
virtual Level* getHandlerLevel() = 0;
public:
virtual Response handle(Request* req) = 0;
private:
IHandler* _nextHandler;
};
class Handler1 : public IHandler {
public:
Response handle(Request* req) {
std::cout << "Handler 1 handled." << std::endl;
return Response("1 handles.");
}
protected:
Level* getHandlerLevel() {
return new Level(1);
}
};
class Handler2 : public IHandler {
public:
Response handle(Request* req) {
std::cout << "Handler 2 handled." << std::endl;
return Response("2 handles.");
}
protected:
Level* getHandlerLevel() {
return new Level(2);
}
};
class Handler3 : public IHandler {
public:
Response handle(Request* req) {
std::cout << "Handler 3 handled." << std::endl;
return Response("3 handles.");
}
protected:
Level* getHandlerLevel() {
return new Level(3);
}
};
int main()
{
Handler1 *handler1 = new Handler1;
Handler2 *handler2 = new Handler2;
Handler3 *handler3 = new Handler3;
handler1->setNextHandler(handler2);
handler2->setNextHandler(handler3);
Response response = handler1->handleRequest(new Request(new Level(1)));
response = handler1->handleRequest(new Request(new Level(2)));
response = handler1->handleRequest(new Request(new Level(3)));
return 0;
}
|
JavaScript
|
UTF-8
| 506
| 2.5625
| 3
|
[] |
no_license
|
import { useState } from 'react'
const useAsyncFn = (asyncFn) => {
const [state, setState] = useState({
loading: true,
error: null,
data: null
})
const executeFn = (...args) => {
return asyncFn(...args)
.then(data => {
setState({ ...state, loading: false, data })
return data
})
.catch(error => {
setState({ ...state, loading: false, error })
return error
})
}
return { ...state, executeFn }
}
export default useAsyncFn
|
Java
|
UTF-8
| 654
| 3.703125
| 4
|
[] |
no_license
|
//3. Реализовать метод, который посчитает среднее арифметическое по возрасту студентов (метод возращает средний арифметический возраст студентов)
import java.util.ArrayList;
import java.util.List;
public class Average {
public static void average(List<Student> studList) {
int arrayListSum = 0;
for (int i = 0; i < studList.size(); i++) {
arrayListSum += studList.get(i).getAge();
}
int resultAver = arrayListSum / studList.size();
System.out.println(resultAver);
}
}
|
C++
|
UTF-8
| 11,605
| 2.75
| 3
|
[
"Apache-2.0"
] |
permissive
|
//
// XML.m
// iCAD
//
// Created by Josh Anderson on 5/11/11.
// Copyright 2011 Novatek Inc. All rights reserved.
//
#include "XML.h"
#include <iostream>
#include <fstream>
char *Beggining;
int Total;
XMLAttribute::XMLAttribute()
{
Name = "";
Value = "";
}
XMLAttribute::XMLAttribute(XMLAttribute *Attribute)
{
Name = Attribute->Name;
Value = Attribute->Value;
}
XMLAttribute::XMLAttribute(char *&utf8String)
{
char *Pos = utf8String;
char *Start;
SkipWhiteSpace(Pos);
Start = Pos;
if(!*Pos)
return;
GoToChar(Pos, '=');
if(!*Pos)
return;
*Pos = 0;
Name = string(Start);
Pos += 2;
Start = Pos;
GoToChar(Pos, '\"');
if(!*Pos)
return;
*Pos = 0;
Value = string(Start);
utf8String = Pos+1;
}
void XMLAttribute::WriteXMLAttrbute(std::ofstream &output)
{
output << " " << Name << "=\"" << Value << "\"";
}
string XMLAttribute::ToString()
{
string Return = "";
Return = Name + "=\"" + Value + "\"";
return Return;
}
XMLNode::XMLNode()
{
Parent = NULL;
Name = "";
Value = "";
}
XMLNode::XMLNode(XMLNode *Node)
{
if(Node)
{
if(Node->Name != "")
Name = Node->Name;
if(Node->Value != "")
Value = Node->Value;
XMLAttribute *Attribute;
for(int i = 0; i < Node->Attributes.size(); i++)
{
Attribute = new XMLAttribute(Node->Attributes[i]);
Attributes.push_back(Attribute);
}
XMLNode *Current;
for(int i = 0; i < Node->Children.size(); i++)
{
Current = new XMLNode(Node->Children[i]);
Current->Parent = this;
Children.push_back(Current);
}
}
else
{
Parent = NULL;
Name = "";
Value = "";
}
}
XMLNode::XMLNode(char *&utf8String, XMLNode *NewParent)
{
char *Pos = utf8String;
char *Start = Pos;
XMLAttribute *NewAttribute;
SkipWhiteSpace(Pos);
if(*Pos != '<')
return;
Parent = NewParent;
Pos++;
if(*Pos == '?')
{
Pos++;
Start = Pos;
GetToWhiteSpace(Pos);
if(!*Pos)
return;
*Pos = 0;
Name = string(Start);
Pos++;
while(*Pos && *Pos != '?')
{
NewAttribute = new XMLAttribute(Pos);
Attributes.push_back(NewAttribute);
while(IsWhiteSpace(*Pos))
Pos++;
}
Pos += 2;
utf8String = Pos;
}
else if(*Pos == '!')
{
while(*Pos)
{
if(*Pos == '-')
if(*(Pos+1) == '-')
if(*(Pos+2) == '>')
{
Pos += 3;
break;
}
Pos++;
}
utf8String = Pos;
return;
}
else
{
bool IsEndTag = false;
if(*Pos == '/')
IsEndTag = true;
Start = Pos;
GetToWhiteSpace(Pos, '>');
if(!*Pos)
return;
bool CloseTag = false;
if(*Pos == '>')
CloseTag = true;
*Pos = 0;
Name = string(Start);
if(IsEndTag)
{
utf8String = Pos+1;
return;
}
Pos++;
while(*Pos && !CloseTag && *Pos != '>' && *Pos != '/')
{
NewAttribute = new XMLAttribute(Pos);
Attributes.push_back(NewAttribute);
SkipWhiteSpace(Pos);
}
if(!*Pos)
return;
if(*Pos == '/')
{
utf8String = Pos+2;
return;
}
if(!CloseTag)
Pos++;
SkipWhiteSpace(Pos);
if(!*Pos)
return;
if(*Pos != '<')
{
Start = Pos;
GoToChar(Pos, '<');
if(!*Pos)
return;
*Pos = 0;
Value = string(Start);
*Pos = '<';
}
XMLNode *CurrentNode = new XMLNode(Pos, this);
while(CurrentNode && CurrentNode->Name != "" && (string("/") + Name) != CurrentNode->Name)
{
Children.push_back(CurrentNode);
CurrentNode = new XMLNode(Pos, this);
}
if(CurrentNode)
delete CurrentNode;
}
SkipWhiteSpace(Pos);
utf8String = Pos;
}
XMLNode::~XMLNode()
{
for(int i = 0 ; i < Children.size(); i++)
delete Children[i];
for(int i = 0; i < Attributes.size(); i++)
delete Attributes[i];
}
void XMLNode::WriteXMLNode(std::ofstream &output)
{
int Depth = GetNodeDepth();
for(int i = 0; i < Depth; i++)
output << "\t";
output << "<";
if(Name == "xml")
output << "?";
output << Name;
for(int i = 0; i < Attributes.size(); i++)
Attributes[i]->WriteXMLAttrbute(output);
if(Value != "" || Children.size())
{
if(Name == "xml")
output << "?";
output << ">";
if(Value != "")
output << Value;
if(Children.size())
{
for(int i = 0; i < Children.size(); i++)
{
output << "\n";
Children[i]->WriteXMLNode(output);
}
output << "\n";
for(int i = 0; i < Depth; i++)
output << "\t";
output << "</";
output << Name;
output << ">";
}
else
{
output << "</";
output << Name;
output << ">";
}
}
else
{
if(Name == "xml")
output << "?";
else
output << "/";
output << ">";
}
}
int XMLNode::GetNodeDepth()
{
int Return = 0;
if(Parent)
Return += 1 + Parent->GetNodeDepth();
return Return;
}
std::vector<XMLNode *> XMLNode::GetXMLNodes(string gName, string AName, string AValue)
{
std::vector<XMLNode *>Nodes;
if(gName ==Name)
{
if(AName != "")
{
int i;
for(i = 0; i < Attributes.size(); i++)
{
if(ToLowerString(Attributes[i]->Name) == ToLowerString(AName))
break;
}
if(i < Attributes.size())
{
if(AValue != "")
{
if(ToLowerString(AValue) == ToLowerString(Attributes[i]->Value))
Nodes.push_back(this);
}
else
Nodes.push_back(this);
}
}
else
Nodes.push_back(this);
}
std::vector<XMLNode *>Temp;
for(int i = 0; i < Children.size(); i++)
{
Temp = Children[i]->GetXMLNodes(gName, AName, AValue);
for(int j = 0; j < Temp.size(); j++)
Nodes.push_back(Temp[j]);
}
return Nodes;
}
XMLNode *XMLNode::GetXMLNode(string gName, string AName, string AValue)
{
if(gName == "")
{
for(int i = 0; i < Attributes.size(); i++)
{
if(ToLowerString(Attributes[i]->Name) == ToLowerString(AName))
{
if(AValue != "")
{
if(ToLowerString(Attributes[i]->Value) == ToLowerString(AValue))
return this;
}
else
return this;
}
}
for(int i = 0; i < Children.size(); i++)
{
XMLNode *Return = Children[i]->GetXMLNode(gName, AName, AValue);
if(Return != NULL)
return Return;
}
}
else
{
if(gName == Name)
{
if(AName != "")
{
for(int i = 0; i < Attributes.size(); i++)
{
if(ToLowerString(Attributes[i]->Name) == ToLowerString(AName))
{
if(AValue != "")
{
if(ToLowerString(Attributes[i]->Value) == ToLowerString(AValue))
return this;
}
else
return this;
}
}
}
else
return this;
}
for(int i = 0; i < Children.size(); i++)
{
XMLNode *Return = Children[i]->GetXMLNode(gName, AName, AValue);
if(Return != NULL)
return Return;
}
}
return NULL;
}
std::vector<XMLNode *> XMLNode::GetXMLNodesWithValue(string Value, string nName, string AName, string AValue)
{
std::vector<XMLNode *> Return = GetXMLNodes(nName, AName, AValue);
for(int i = 0; i < Return.size(); i++)
{
if(Return[i]->Value != Value)
{
Return.erase(Return.begin()+i,Return.begin()+i);
i--;
}
}
return Return;
}
XMLNode * XMLNode::GetXMLNodeWithValue(string Value, string nName, string AName, string AValue)
{
std::vector<XMLNode *> List = GetXMLNodes(nName, AName, AValue);
for(int i = 0; i < List.size(); i++)
if(List[i]->Value == Value)
return List[i];
return NULL;
}
XMLAttribute *XMLNode::GetAttribute(string AName)
{
for(int i = 0; i < Attributes.size(); i++)
{
if(ToLowerString(Attributes[i]->Name) == ToLowerString(AName))
return Attributes[i];
}
return NULL;
}
string XMLNode::GetAttributeValue(string AName)
{
for(int i = 0; i < Attributes.size(); i++)
{
if(ToLowerString(Attributes[i]->Name) == ToLowerString(AName))
return Attributes[i]->Value;
}
return NULL;
}
string XMLNode::ToString()
{
string Return = "";
int Depth = GetNodeDepth();
for(int i = 0; i < Depth; i++)
Return += "\t";
Return += "<";
if(Name == "xml")
Return += "?";
Return += Name;
for(int i = 0; i < Attributes.size(); i++)
Return += " " + Attributes[i]->ToString();
if(Value != "" || Children.size())
{
Return += ">";
if(Value != "")
Return += Value;
for(int i = 0; i < Children.size(); i++)
Return += "\n" + Children[i]->ToString();
if(Children.size())
Return += "\n";
for(int i = 0; i < Depth; i++)
Return += "\t";
Return += "</" + Name + ">";
}
else
{
if(Name == "xml")
Return += "?>";
else
Return += "/>";
}
return Return;
}
string XMLNode::ToString(string *String, bool isRoot)
{
XMLNode *xmlParent = Parent;
if(isRoot)
Parent = NULL;
string Return = ToString();
Parent = xmlParent;
if(String != NULL)
*String = Return;
return Return;
}
unsigned int XMLNode::Count()
{
return Children.size();
}
XML::XML()
{
}
XML::XML(std::vector<XMLNode *> Nodes)
{
XMLNode *Current;
for(int i = 0; i < Nodes.size(); i++)
{
Current = new XMLNode(Nodes[i]);
Roots.push_back(Current);
}
}
XML::~XML()
{
for(int i = 0; i < Roots.size(); i++)
delete Roots[i];
}
void XML::LoadXMLFile(string filePath)
{
std::ifstream input;
input.open(filePath.c_str());
if(!input.is_open())
return;
input.seekg(0,std::ios::end);
unsigned long long Size = input.tellg();
input.close();
input.open(filePath.c_str());
char *Buffer = new char[Size+1];
Beggining = Buffer;
input.read(Buffer, Size);
Buffer[Size] = 0;
input.close();
char *Pos = Buffer;
XMLNode *xmlVerison = new XMLNode(Pos, NULL);
if(xmlVerison && xmlVerison->Name != "")
Roots.push_back(xmlVerison);
XMLNode *CurrentNode;
CurrentNode = new XMLNode(Pos, NULL);
if(CurrentNode && CurrentNode->Name != "")
Roots.push_back(CurrentNode);
delete[] Buffer;
}
void XML::WriteXMLFile(string filePath)
{
std::ofstream output;
output.open(filePath.c_str());
for(int i = 0; i < Roots.size(); i++)
{
Roots[i]->WriteXMLNode(output);
if(i < Roots.size()-1)
output << "\n";
}
output.close();
}
std::vector<XMLNode *> XML::GetXMLNodes(string Name, string AName, string Value)
{
std::vector<XMLNode *>Nodes;
std::vector<XMLNode *>Temp;
for(int i = 0; i < Roots.size(); i++)
{
Temp = Roots[i]->GetXMLNodes(Name, AName, Value);
for(int j = 0; j < Temp.size(); j++)
Nodes.push_back(Temp[j]);
}
return Nodes;
}
XMLNode *XML::GetXMLNode(string Name, string AName, string Value)
{
XMLNode *Return = NULL;
for(int i = 0; i < Roots.size(); i++)
{
Return = Roots[i]->GetXMLNode(Name, AName, Value);
if(Return != NULL)
return Return;
}
return NULL;
}
unsigned int XML::Count()
{
return Roots.size();
}
void SkipWhiteSpace(char *&Pos)
{
while(*Pos && IsWhiteSpace(*Pos))
Pos++;
}
void GetToWhiteSpace(char *&Pos, char Delim)
{
while(*Pos && !IsWhiteSpace(*Pos) && *Pos != Delim)
Pos++;
}
void GoToChar(char *&Pos, char Delim)
{
while(*Pos && *Pos != Delim)
Pos++;
}
bool IsWhiteSpace(char Pos)
{
if(Pos == ' ' || Pos == '\n' || Pos == '\r' || Pos == '\t')
return true;
return false;
}
string ToLowerString(string &Source)
{
return string(strlwr((char*)Source.c_str()));
}
int _httoi(const TCHAR *value)
{
struct CHexMap
{
TCHAR chr;
int value;
};
const int HexMapL = 16;
CHexMap HexMap[HexMapL] =
{
{'0', 0}, {'1', 1},
{'2', 2}, {'3', 3},
{'4', 4}, {'5', 5},
{'6', 6}, {'7', 7},
{'8', 8}, {'9', 9},
{'A', 10}, {'B', 11},
{'C', 12}, {'D', 13},
{'E', 14}, {'F', 15}
};
TCHAR *mstr = _tcsupr(_tcsdup(value));
TCHAR *s = mstr;
int result = 0;
if (*s == '0' && *(s + 1) == 'X') s += 2;
bool firsttime = true;
while (*s != '\0')
{
bool found = false;
for (int i = 0; i < HexMapL; i++)
{
if (*s == HexMap[i].chr)
{
if (!firsttime) result <<= 4;
result |= HexMap[i].value;
found = true;
break;
}
}
if (!found) break;
s++;
firsttime = false;
}
free(mstr);
return result;
}
|
C#
|
UTF-8
| 2,000
| 3.21875
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cosmos
{
/// <summary>
/// DLL to be called when informaiton needs to be encrypted or decrypted.
/// </summary>
internal class Encryption
{
/// <summary>
/// Encryptes the passed in string.
/// </summary>
/// <param name="stringToEncrypt">the string that needs to be encrypted</param>
/// <param name="encryptionInformation">the keys for the encryption.</param>
/// <returns>A byte array representation of the encrypted string.</returns>
public static byte[] Encrypt(string stringToEncrypt)
{
return Encrypt(Encoding.ASCII.GetBytes(stringToEncrypt));
}
/// <summary>
/// Encrypts the passed in byte array using the keys from the encryptionInformation
/// </summary>
/// <param name="dataToEncrypt">What needs to be encrypted</param>
/// <param name="encryptionInformation">The keys for the encryption</param>
/// <returns>A byte representation of the encrypted byte array.</returns>
public static byte[] Encrypt(byte[] dataToEncrypt)
{
return EncryptionHelper.SimpleEncrypt(dataToEncrypt, Configuration.CryptographyKey,
Configuration.AuthenticationKey);
}
/// <summary>
/// Decrypts the encrypted data.
/// </summary>
/// <param name="encryptedData">The data to decrypt</param>
/// <param name="encryptionInformation">THe keys used to decrypt the data.</param>
/// <returns>Abyte array representation of the decrypted data</returns>
public static byte[] Decrypt(byte[] encryptedData)
{
return EncryptionHelper.SimpleDecrypt(encryptedData, Configuration.CryptographyKey,
Configuration.AuthenticationKey);
}
}
}
|
Java
|
UTF-8
| 993
| 3.25
| 3
|
[] |
no_license
|
package paquete;
public class Cracker_33941256 implements Cracker {
private int clave = 0;
private int inf = 0; //Establece el limite inferior de las posibles claves
private int sup = 9999; //Establece el limite superior de las posibles claves
public String getNextKey(boolean ultima_clave_se_paso) {
//System.out.println(inf +" "+ sup +" "+ clave);
if(ultima_clave_se_paso == true){ //Atualiza los limites si la clave es menor a la probada
sup = clave;
}
else if(ultima_clave_se_paso == false){ //Atualiza los limites si la clave es mayor a la probada
inf = clave;
}
clave = (inf + sup)/2; //Determina la nueva clave como la mitad del rango posible
System.out.println("Probando la clave: " + clave + "...");
String cadena;
cadena = String.valueOf(clave);
return cadena;
}
public String getStudentName() {
return "Arlettaz, Emiliano";
}
public int getCurrentKey(){
return clave;
}
}
|
Python
|
UTF-8
| 25,784
| 2.765625
| 3
|
[] |
no_license
|
import discord
from discord.ext import commands
import random
import asyncio
import os
import time
command_prefix='p!'
bot = commands.Bot(command_prefix)
game = discord.Game("fighting Neonic")
@bot.event
async def on_ready():
await bot.change_presence(status=discord.Status.online, activity=game)
print('Logged in as')
print(bot.user.name)
print(bot.user.id)
print('------')
@bot.event
async def on_member_join(member):
welcome = bot.get_channel(492571950422556672)
guidelines = bot.get_channel(492571898010664970)
channel = bot.get_channel(492577748003586048)
guild = channel.guild
botUser = guild.get_member(492582158104526861)
raidProtectionRole = discord.utils.get(guild.roles, name='Raid Protection On')
memberRole = discord.utils.get(guild.roles, name='Member')
if raidProtectionRole in botUser.roles:
await channel.send("Welcome to Plasma's Realm, " + member.mention + "! We hope you have a good experience here, and make sure to read " + welcome.mention + " and " + guidelines.mention + "! **Raid protection is on, so the staff will give you the member role, so please stay and be patient!**")
else:
await channel.send("Welcome to Plasma's Realm, " + member.mention + "! We hope you have a good experience here, and make sure to read " + welcome.mention + " and " + guidelines.mention + "!")
await member.add_roles(memberRole)
@bot.event
async def on_member_remove(member):
channel = bot.get_channel(492577748003586048)
await channel.send("Aww, sorry that you had to go, **" + member.name + "**#" + member.discriminator + "! I hope you come back soon!")
bot.remove_command('help')
minigameList = {
"1": "Pass The Bomb",
"2": "Speed Counter"
}
# Minigame Related Variables:
minigameParticipants = []
eliminationOrder = []
minigameRunning = 0
minigamePlaying = 0
choosingMinigame = 0
currentHost = None
roundNumber = 0
# Bomb Minigame Related Variables:
holdingBomb = None
equationAnswer = 0
# Speed Counter Related Variables:
scores = {}
amountOfEmoji = 0
countingEmojiPeriod = 0
async def cancelminigame(guild):
global holdingBomb
global eliminationOrder
global minigameParticipants
global roundNumber
global minigameRunning
global minigamePlaying
global currentHost
minigameRole = discord.utils.get(guild.roles, name='Minigame Participants')
for player in minigameRole.members:
await player.remove_roles(minigameRole)
minigameParticipants = []
minigameRunning = 0
currentHost = None
# Bomb Minigame Functions
async def startNewBombRound(guild):
minigameScreenChannel = bot.get_channel(492771187332481034)
global roundNumber
global minigameParticipants
global holdingBomb
startBomb = random.choice(minigameParticipants)
roundNumber += 1
await minigameScreenChannel.send("**Round " + str(roundNumber) + "**\nFor this round, the bomb will start with " + startBomb.mention + ". Round starts in 5 seconds...")
await asyncio.sleep(5)
await minigameScreenChannel.send("**GO!**")
holdingBomb = startBomb
await sayBomb()
await timer(guild)
async def sayBomb():
global holdingBomb
global equationAnswer
minigameLoungeChannel = bot.get_channel(492771206500712448)
equation1 = random.randint(1, 50)
equation2 = random.randint(1, 50)
equationAnswer = equation1 + equation2
await minigameLoungeChannel.send(holdingBomb.mention + ", to pass the bomb to someone, use the `p!bpass` command followed by the answer to **" + str(equation1) + " + " + str(equation2) + "**, followed by a mention of the player you want to pass it to.")
async def timer(guild):
global holdingBomb
global eliminationOrder
global minigameParticipants
global roundNumber
global minigameRunning
global minigamePlaying
global currentHost
minigameRole = discord.utils.get(guild.roles, name='Minigame Participants')
eliminatedRole = discord.utils.get(guild.roles, name='Eliminated Participants')
await asyncio.sleep(1)
amountOfTime = random.randint(70, 100)
await asyncio.sleep(amountOfTime)
personEliminated = holdingBomb
holdingBomb = None
minigameScreenChannel = bot.get_channel(492771187332481034)
minigameLogChannel = bot.get_channel(494751892874854421)
await minigameScreenChannel.send(":bomb: **The bomb exploded!** :bomb: \n" + personEliminated.mention + " had the bomb last, so they are eliminated!")
minigameParticipants.remove(personEliminated)
await personEliminated.remove_roles(minigameRole)
await personEliminated.add_roles(eliminatedRole)
eliminationOrder = [personEliminated] + eliminationOrder
holdingBomb = None
if len(minigameParticipants) == 1:
winner = minigameParticipants[0]
await minigameScreenChannel.send("**" + winner.mention + " wins __Pass The Bomb!__** Congratulations! :trophy: **Minigame ends in 10 seconds.**")
await asyncio.sleep(10)
for player in minigameRole.members:
await player.remove_roles(minigameRole)
for player in eliminatedRole.members:
await player.remove_roles(eliminatedRole)
logMessage = "**Congratulations to " + winner.mention + " for winning __Pass The Bomb!__\n#1: " + winner.mention + "**"
placing = 2
for player in eliminationOrder:
localMessage = "\n#" + str(placing) + ": " + player.mention
logMessage += localMessage
placing += 1
await minigameLogChannel.send(logMessage)
minigameParticipants = []
eliminationOrder = []
roundNumber = 0
minigameRunning = 0
minigamePlaying = 0
currentHost = None
else:
await minigameScreenChannel.send("**" + str(len(minigameParticipants)) + "** contestants remain! Next round starting in 15 seconds!")
await asyncio.sleep(15)
await startNewBombRound(guild)
# Counter Minigame Functions
async def sendNewEmojiSet(guild):
global amountOfEmoji
global scores
global roundNumber
global countingEmojiPeriod
roundNumber += 1
emojiSet = ["<:BookGreen:495145390560116736>", "<:BookYellow:495145295559000066>", "<:BookBlue:495145294988574720>", "<:BookRed:495145295747743754>"]
emojiBeingUsed = random.choice(emojiSet)
emojiString = ""
minigameScreenChannel = bot.get_channel(492771187332481034)
minigameLoungeChannel = bot.get_channel(492771206500712448)
minigameRole = discord.utils.get(guild.roles, name='Minigame Participants')
for x in range(60):
nextEmoji = random.choice(emojiSet)
if nextEmoji == emojiBeingUsed:
amountOfEmoji += 1
emojiString += nextEmoji
await minigameScreenChannel.send("**Round " + str(roundNumber) + "**\n" + minigameRole.mention + ", the emoji you are counting this time is " + emojiBeingUsed + ". Emojis posted in 5 seconds...")
await asyncio.sleep(5)
countingEmojiPeriod = 1
await minigameScreenChannel.send("**GO!**")
await minigameScreenChannel.send(emojiString)
await minigameScreenChannel.send("Count the amount of " + emojiBeingUsed + " and to submit it, use the `p!answer` command followed by your count. First one to get it correct gets a point!")
@bot.command()
async def ask(ctx):
possibleresponses = [
"Ugh... I'm too tired to answer that.",
"Certainly... not.",
"Go ask someone else.",
"It's so obvious, you should already know!",
"Absolutely, like how NeonicPlasma is dumb!",
"Go take that to a better bot.",
"You don't wanna know.",
"I have literally no idea, and I hope I never do."
]
number = random.randint(0, 7)
responseChosen = possibleresponses[number]
await ctx.send(responseChosen)
@bot.command()
async def serverlinks(ctx):
link1 = 'https://discord.gg/WW9Mzce'
link2 = 'https://discord.gg/JdFBfUS'
link3 = 'https://discord.gg/DDxdSwa'
linkEmbed = embed = discord.Embed(title = "Plasma's Server Links", description = "Here are all of NeonicPlasma's important server links!", color=0x00ff00)
linkEmbed.add_field(name = "Plasma's Realm (the main hub for the bot!)", value = link1)
linkEmbed.add_field(name = "TWOW: Plasma's Race (neonic's twow)", value = link2)
linkEmbed.add_field(name = "The Trials (neonic's camp)", value = link3)
await ctx.send(embed=embed)
@bot.command()
async def help(ctx):
neonicwhy = 'Use this command to see some stupid stuff Neonic has done!'
serverlinks = "Use this command to see Neonic's important servers!"
toggleminigames = 'Use this command to toggle your minigame status!'
ask = "Use this command to ask me a question! Although, you might not like the answer."
linkEmbed = embed = discord.Embed(title = "PlasmaBot Commands", description = "Need help? Here are some commands!", color=0x00ff00)
linkEmbed.add_field(name = "p!neonicwhy", value = neonicwhy)
linkEmbed.add_field(name = "p!serverlinks", value = serverlinks)
linkEmbed.add_field(name = "p!toggleminigames", value = toggleminigames)
linkEmbed.add_field(name = "p!ask", value = ask)
await ctx.send(embed=embed)
@bot.command()
async def neonicwhy(ctx):
possibleresponses = [
'https://cdn.discordapp.com/attachments/492588853207629824/492603991960846347/unknown.png',
'https://cdn.discordapp.com/attachments/492588853207629824/492603798267625483/unknown.png',
'https://cdn.discordapp.com/attachments/492588853207629824/492604697685917706/unknown.png',
'https://cdn.discordapp.com/attachments/492588853207629824/492604506467467264/unknown.png'
]
number = random.randint(0, 3)
responseChosen = possibleresponses[number]
await ctx.send('neonic why ' + responseChosen)
@bot.command()
async def toggleminigames(ctx):
role = discord.utils.get(ctx.message.guild.roles, name='Interested In Minigames!')
user = ctx.message.author
roles = user.roles
if role in roles:
await ctx.send('**You no longer have the Minigame role!** If you want to get it again, use p!toggleminigames.')
await user.remove_roles(role)
else:
await ctx.send('**You now have the Minigame role!** If you want to remove it, use p!toggleminigames.')
await user.add_roles(role)
@bot.command()
async def minigame(ctx, mode):
user = ctx.message.author
userid = user.id
channel = ctx.message.channel
if ctx.message.guild:
minigameRole = discord.utils.get(ctx.message.guild.roles, name='Minigame Participants')
global minigameRunning
global currentHost
global minigameParticipants
global minigamePlaying
global roundNumber
global minigameList
global choosingMinigame
minigameScreenChannel = bot.get_channel(492771187332481034)
minigameLogChannel = bot.get_channel(494751892874854421)
if mode == 'create':
if minigameRunning == 0:
await ctx.send('**A minigame has been created!** \nPeople who would like to play can use the `p!minigame join` command to participate in the minigame!')
minigameRunning = 1
currentHost = user
else:
await ctx.send("A minigame is already happening! Please wait until the minigame has finished.")
elif mode == 'join':
if minigameRunning == 1:
if minigamePlaying == 0:
if user in minigameParticipants:
minigameParticipants.remove(user)
await ctx.send("**You have quit the minigame!** The contestant count is now **" + str(len(minigameParticipants)) + "**. If you would like to rejoin, use the `p!minigame join` command to participate again.")
await user.remove_roles(minigameRole)
else:
minigameParticipants.append(user)
await user.add_roles(minigameRole)
if len(minigameParticipants) > 1:
await ctx.send("**You have joined the minigame!** The contestant count is now **" + str(len(minigameParticipants)) + "**. " + currentHost.mention + " can now use `p!minigame start` to start the minigame! If you would like to quit the minigame, use the `p!minigame join` command to quit.")
else:
await ctx.send("**You have joined the minigame!** The contestant count is now **" + str(len(minigameParticipants)) + "**. If you would like to quit the minigame, use the `p!minigame join` command to quit.")
else:
await ctx.send("You cannot join or quit while a minigame is in progress!")
else:
await ctx.send("**A minigame is not running!** To create one, use the command `p!minigame create`.")
elif mode == 'start':
if user == currentHost:
if len(minigameParticipants) > 1:
if minigamePlaying == 0:
minigamePlaying = 1
listOfMinigameChoices = "**" + currentHost.mention + ", please choose a minigame type!** Use the `p!setminigame` command followed by the number corresponding to your minigame: "
for minigameNum in minigameList:
localString = "\n**" + minigameNum + ":** " + minigameList[minigameNum]
listOfMinigameChoices += localString
choosingMinigame = 1
await ctx.send(listOfMinigameChoices)
else:
await ctx.send("A minigame is already being played!")
else:
await ctx.send("You need at least 2 people to start this minigame!")
elif mode == 'cancel':
if minigameRunning == 1:
if currentHost == user:
if isinstance(ctx.message.channel, discord.TextChannel):
if minigamePlaying == 0:
await ctx.send("Minigame has been cancelled.")
await cancelminigame(ctx.message.guild)
else:
await ctx.send("You cannot cancel the minigame if it has already started!")
else:
await ctx.send("You cannot use this in DMs.")
else:
await ctx.send("You are not the host!")
else:
await ctx.send("There is no minigame going on right now! To start one, use `p!minigame create`.")
else:
await ctx.send('Invalid mode!')
@bot.command()
async def setminigame(ctx, number):
global choosingMinigame
global currentHost
global minigameParticipants
user = ctx.message.author
guild = ctx.message.guild
minigameRole = discord.utils.get(guild.roles, name='Minigame Participants')
minigameLoungeChannel = bot.get_channel(492771206500712448)
if choosingMinigame == 1:
if currentHost == user:
if number == "1":
choosingMinigame = 0
await ctx.send("**__Pass The Bomb__** has been initialized! Minigame starting in 10 seconds. " + minigameRole.mention + ", please head to " + minigameLoungeChannel.mention + ".")
await asyncio.sleep(10)
await startNewBombRound(guild)
elif number == "2":
choosingMinigame = 0
global scores
for player in minigameParticipants:
scores[player.id] = 0
await ctx.send("**__Speed Counter__** has been initialized! Minigame starting in 10 seconds. " + minigameRole.mention + ", please head to " + minigameLoungeChannel.mention + ".")
await asyncio.sleep(10)
await sendNewEmojiSet(guild)
elif number == "3":
choosingMinigame = 0
await ctx.send("**__Rise To The Limit__** has been initialized! Minigame starting in 10 seconds. " + minigameRole.mention + ", please head to " + minigameLoungeChannel.mention + ".")
await asyncio.sleep(10)
else:
await ctx.send("Invalid minigame! Please try again.")
else:
await ctx.send("You cannot use this command!")
@bot.command()
async def bpass(ctx, number):
global minigameRunning
global minigameParticipants
global minigamePlaying
global holdingBomb
global equationAnswer
user = ctx.message.author
if holdingBomb == user:
personPassedTo = ctx.message.mentions[0]
if personPassedTo:
if personPassedTo in minigameParticipants:
integerExists = True
try:
int(number)
except ValueError:
integerExists = False
if integerExists == True:
if int(number) == equationAnswer:
holdingBomb = personPassedTo
await sayBomb()
else:
await ctx.send("**Wrong Answer!** Try again.")
else:
await ctx.send("Make sure the number is an integer, a whole number!")
else:
await ctx.send("This person isn't a contestant. Pass it to someone else.")
else:
await ctx.send("You need to mention the person you are passing it to in your command!")
else:
await ctx.send("You aren't holding the bomb!")
@bot.command()
async def answer(ctx, number):
minigameRole = discord.utils.get(ctx.message.guild.roles, name='Minigame Participants')
user = ctx.message.author
minigameScreenChannel = bot.get_channel(492771187332481034)
minigameLogChannel = bot.get_channel(494751892874854421)
global minigameParticipants
global amountOfEmoji
global countingEmojiPeriod
global scores
global minigameRunning
global minigamePlaying
global roundNumber
global currentHost
global eliminationOrder
if countingEmojiPeriod == 1:
if user in minigameParticipants:
if int(number) == amountOfEmoji:
couningEmojiPeriod = 0
await ctx.send(user.mention + " is correct!")
scores[user.id] += 1
pointCount = scores[user.id]
await minigameScreenChannel.send("**" + user.mention + " got it correct!** The answer was **" + str(amountOfEmoji) + "**. They now have " + str(pointCount) + " points.")
amountOfEmoji = 0
if pointCount < 5:
await minigameScreenChannel.send("Next round in 10 seconds.")
await asyncio.sleep(10)
await sendNewEmojiSet(ctx.message.guild)
else:
await minigameScreenChannel.send("**" + user.mention + " wins __Speed Counter!__** Congratulations! :trophy: **Minigame ends in 10 seconds.**")
await asyncio.sleep(10)
minigameParticipants = []
eliminationOrder = []
roundNumber = 0
minigameRunning = 0
minigamePlaying = 0
currentHost = None
for player in minigameRole.members:
await player.remove_roles(minigameRole)
logString = "**Congratulations to " + user.mention + " for winning __Speed Counter!__ \n#1: " + user.mention + " (5)**"
placing = 2
peopleWithPointCount = 0
for number in range(4, -1, -1):
if number in scores.values():
for key, value in scores.items():
if value == number:
user = ctx.message.guild.get_member(int(key))
localString = ""
peopleWithPointCount += 1
if user:
localString = "\n#" + str(placing) + ": " + user.mention + " (" + str(number) + ")"
else:
localString = "\n#" + str(placing) + ": Cannot Find User" + " (" + str(number) + ")"
logString += localString
placing += peopleWithPointCount
await minigameLogChannel.send(logString)
else:
await ctx.send("You are not participating in this minigame!")
@bot.command()
async def botsend(ctx, message):
author = ctx.message.author
authorRoles = author.roles
staffRole = discord.utils.get(ctx.message.guild.roles, name="Staff")
if staffRole in authorRoles:
channel = ctx.message.channel_mentions[0]
await channel.send(message)
else:
await ctx.send('**You have no permission to use this command!**')
@bot.command()
async def moderate(ctx, mode):
author = ctx.message.author
authorRoles = author.roles
staffRole = discord.utils.get(ctx.message.guild.roles, name="Staff")
if staffRole in authorRoles:
guild = ctx.message.guild
if mode == "toggleraidprotection":
raidProtectionRole = discord.utils.get(ctx.message.guild.roles, name="Raid Protection On")
botUser = guild.get_member(492582158104526861)
if raidProtectionRole in botUser.roles:
await ctx.send("Raid protection has been turned off.")
await botUser.remove_roles(raidProtectionRole)
else:
await ctx.send("Raid protection has been turned on.")
await botUser.add_roles(raidProtectionRole)
elif mode == "warn":
wOne = discord.utils.get(ctx.message.guild.roles, name="wOne")
wTwo = discord.utils.get(ctx.message.guild.roles, name="wTwo")
wThree = discord.utils.get(ctx.message.guild.roles, name="wThree")
wFour = discord.utils.get(ctx.message.guild.roles, name="wFour")
wFive = discord.utils.get(ctx.message.guild.roles, name="wFive")
else:
await ctx.send('**You have no permission to use this command!**')
@bot.command()
async def plasmafight(ctx):
timeWait = 2
player1hp = 150
player2hp = 150
embed = discord.Embed(title = '**Plasma Fight: Player1 vs Player 2!**', description = '', color = 0x00ff00)
embed.add_field(name = 'Player1', value = str(player1hp) + '/150')
embed.add_field(name = 'Player2', value = str(player2hp) + '/150')
msg = await ctx.send("Plasma Fight!", embed = embed)
line1 = ''
line2 = ''
line3 = ''
turn = 1
shotAt = 2
while player1hp != 0 and player2hp != 0:
await asyncio.sleep(timeWait)
damageDealt = random.randint(1, 30)
weaponUsed = ''
action = ''
if damageDealt >= 1 and damageDealt <= 5:
weaponUsed = 'plasma spear'
action = ' stabs'
elif damageDealt >= 6 and damageDealt <= 10:
weaponUsed = 'plasma sword'
action = ' stabs'
elif damageDealt >= 11 and damageDealt <= 15:
weaponUsed = 'plasma pistol'
action = ' shoots'
elif damageDealt >= 16 and damageDealt <= 20:
weaponUsed = 'plasma turret'
action = ' shoots'
elif damageDealt >= 21 and damageDealt <= 25:
weaponUsed = 'plasma grenade'
action = ' blows up'
elif damageDealt >= 26 and damageDealt <= 30:
weaponUsed = 'plasma reactor'
action = ' poisons'
line = "Player" + str(turn) + action + " Player" + str(shotAt) + " with a " + weaponUsed + " and deals " + str(damageDealt) + " damage!"
player1hp = player1hp - 10
line3 = line2
line2 = line1
line1 = line
newembed = discord.Embed(title = '**Plasma Fight: Player1 vs Player 2!**', description = '', color = 0x00ff00)
if line3 == '':
if line2 == '':
newembed.add_field(name = 'a', value = "**" + line1 + "**")
newembed.add_field(name = 'Player1', value = str(player1hp) + '/150')
newembed.add_field(name = 'Player2', value = str(player2hp) + '/150')
else:
newembed.add_field(name = 'a', value = line2)
newembed.add_field(name = 'a', value = "**" + line1 + "**")
newembed.add_field(name = 'Player1', value = str(player1hp) + '/150')
newembed.add_field(name = 'Player2', value = str(player2hp) + '/150')
else:
newembed.add_field(name = 'a', value = line3)
newembed.add_field(name = 'a', value = line2)
newembed.add_field(name = 'a', value = "**" + line1 + "**")
newembed.add_field(name = 'Player1', value = str(player1hp) + '/150')
newembed.add_field(name = 'Player2', value = str(player2hp) + '/150')
await ctx.send(line + "\n" + "hello")
await msg.edit('Plasma Fight!', embed=newembed)
bot.run(os.getenv('TOKEN'))
|
Ruby
|
UTF-8
| 5,395
| 2.84375
| 3
|
[
"MIT"
] |
permissive
|
require 'spec_helper'
require 'jrr/matcher'
require 'jrr/token'
RSpec.describe Jrr::Matcher do
it 'with single category matches token category' do
matcher = described_class.new(:numeric)
token = Jrr::Token.new(:numeric, 5)
expect(matcher).to eq(token)
end
it 'with multiple categories matches any included token category' do
matcher = described_class.new([:comparison_operator, :arithmetic_operator])
numeric = Jrr::Token.new(:numeric, 5)
comparison_operator = Jrr::Token.new(:comparison_operator, :lt)
operator = Jrr::Token.new(:arithmetic_operator, :add)
expect(matcher).to eq(comparison_operator)
expect(matcher).to eq(operator)
expect(matcher).not_to eq(numeric)
end
it 'with single category and value matches token category and value' do
matcher = described_class.new(:arithmetic_operator, :add)
addition = Jrr::Token.new(:arithmetic_operator, :add)
subtraction = Jrr::Token.new(:arithmetic_operator, :subtract)
expect(matcher).to eq(addition)
expect(matcher).not_to eq(subtraction)
end
it 'with multiple values matches any included token value' do
matcher = described_class.new(:arithmetic_operator, [:add, :subtract])
add = Jrr::Token.new(:arithmetic_operator, :add)
sub = Jrr::Token.new(:arithmetic_operator, :subtract)
mul = Jrr::Token.new(:arithmetic_operator, :multiply)
div = Jrr::Token.new(:arithmetic_operator, :divide)
expect(matcher).to eq(add)
expect(matcher).to eq(sub)
expect(matcher).not_to eq(mul)
expect(matcher).not_to eq(div)
end
it 'is invertible' do
matcher = described_class.new(:arithmetic_operator, [:add, :subtract]).invert
add = Jrr::Token.new(:arithmetic_operator, :add)
mul = Jrr::Token.new(:arithmetic_operator, :multiply)
cmp = Jrr::Token.new(:comparison_operator, :lt)
expect(matcher).not_to eq(add)
expect(matcher).to eq(mul)
expect(matcher).to eq(cmp)
end
describe 'combining multiple tokens' do
let(:numeric) { described_class.new(:numeric) }
let(:string) { described_class.new(:string) }
it 'matches either' do
either_matcher = numeric | string
expect(either_matcher).to eq(Jrr::Token.new(:numeric, 5))
expect(either_matcher).to eq(Jrr::Token.new(:string, 'rhubarb'))
end
it 'matches any value' do
value_matcher = described_class.value
expect(value_matcher).to eq(Jrr::Token.new(:numeric, 8))
expect(value_matcher).to eq(Jrr::Token.new(:string, 'apricot'))
expect(value_matcher).to eq(Jrr::Token.new(:boolean, false))
expect(value_matcher).not_to eq(Jrr::Token.new(:function, :round))
expect(value_matcher).not_to eq(Jrr::Token.new(:identifier, :hello))
end
end
describe 'stream matching' do
let(:stream) { token_stream(5, 11, 9, 24, :hello, 8) }
describe 'standard' do
let(:standard) { described_class.new(:numeric) }
it 'matches zero or more occurrences in a token stream' do
matched, substream = standard.match(stream)
expect(matched).to be_truthy
expect(substream.length).to eq 1
expect(substream.map(&:value)).to eq [5]
matched, substream = standard.match(stream, 4)
expect(substream).to be_empty
expect(matched).not_to be_truthy
end
end
describe 'star' do
let(:star) { described_class.new(:numeric).star }
it 'matches zero or more occurrences in a token stream' do
matched, substream = star.match(stream)
expect(matched).to be_truthy
expect(substream.length).to eq 4
expect(substream.map(&:value)).to eq [5, 11, 9, 24]
matched, substream = star.match(stream, 4)
expect(substream).to be_empty
expect(matched).to be_truthy
end
end
describe 'plus' do
let(:plus) { described_class.new(:numeric).plus }
it 'matches one or more occurrences in a token stream' do
matched, substream = plus.match(stream)
expect(matched).to be_truthy
expect(substream.length).to eq 4
expect(substream.map(&:value)).to eq [5, 11, 9, 24]
matched, substream = plus.match(stream, 4)
expect(substream).to be_empty
expect(matched).not_to be_truthy
end
end
describe 'arguments' do
it 'matches comma-separated values' do
stream = token_stream(1, :comma, 2, :comma, true, :comma, 'olive', :comma, :'(')
matched, substream = described_class.arguments.match(stream)
expect(matched).to be_truthy
expect(substream.length).to eq 8
expect(substream.map(&:value)).to eq [1, :comma, 2, :comma, true, :comma, 'olive', :comma]
end
end
end
private
def token_stream(*args)
args.map do |value|
type = type_for(value)
Jrr::Token.new(type, value)
end
end
def type_for(value)
case value
when Numeric
:numeric
when String
:string
when true, false
:boolean
when :add, :subtract, :multiply, :divide, :mod, :pow
:arithmetic_operator
when :open, :close, :comma
:grouping
when :lbracket, :rbracket
:access
when :le, :ge, :ne, :ne, :lt, :gt, :eq
:comparison_operator
when :and, :or
:boolean_operator
when :if, :round, :roundup, :rounddown, :not
:function
else
:identifier
end
end
end
|
TypeScript
|
UTF-8
| 1,109
| 2.625
| 3
|
[
"Apache-2.0"
] |
permissive
|
import tmp from "tmp-promise";
import { loadPlugin } from "./loadPlugin.js";
import { makeProject, MakeProjectArgs } from "./makeProject.js";
import { PluginArgs } from "./Plugin.js";
/**
Arguments passed to the run command.
*/
export type RunArgs = Omit<PluginArgs, "tempDir" | "project"> &
MakeProjectArgs & {
/**
Path to plugin.
*/
plugin?: string;
};
/**
Runs a given generator in the current working directory.
*/
export const run = async (args: RunArgs): Promise<void> => {
// Validate and open output location, set up output functions
const project = await makeProject(args);
// Load the plugin
const plugin = await loadPlugin(args);
// Create a self-cleaning temporary directory
const tempDir = await tmp.dir({
unsafeCleanup: true,
prefix: "yokedox",
});
try {
// Delegate to plugin
await plugin.run({
...args,
project,
tempDir: tempDir.path,
});
} finally {
// This should not be needed according the tmp-promise library README, but
// local testing indicates otherwise.
await tempDir.cleanup();
}
};
|
C++
|
GB18030
| 622
| 3.328125
| 3
|
[] |
no_license
|
//#include<iostream>
//using namespace std;
//#include "ʽ.cpp"
//
//
//int main()
//{
//
// Polynomial A;//ԴһʽA
// A.insert(Monomial(-6, 7));
// A.insert(Monomial(5, 3));
// A.insert(Monomial(3, 0));
// cout << "AΪ";
// A.output();
//
// Polynomial B;//ԴһʽB
// B.insert(Monomial(-7, 6));
// B.insert(Monomial(-5, 3));
// cout << "BΪ";
// B.output();
//
// Polynomial C = A + B;//A+B
// cout << "A+BΪ";
// C.output();
//
// Polynomial D = A - B;//A-B
// cout << "A-BΪ";
// D.output();
// return 0;
//}
//
|
Markdown
|
UTF-8
| 1,255
| 3.1875
| 3
|
[] |
no_license
|
# Wiring
Good wiring is **crucial** to creating a robot that looks and performs like a top-tier robot. If wires are loose and not neatly cinched up next to support structures, it’s very possible they could come loose (meaning motors and sensors won’t work), and can get caught and pulled out when your robot moves.
## What is good wiring?
Here are some tips to ensure your wiring is good:
* Connections to cortex and power expander always have their clip on, so nothing falls out.
* Connections between wires (i.e. motor to motor controller, motor to extension wire) are ziptied, and then taped so they do not come undone.
* When wires are wrapped around moving joints, make sure they are not too tight, and do not get caught in these joints
* Wires are cinched neatly to support beams using zipties so they are not dangling. Wires should not be hanging across the robot: They must be wrapped around supports.
* The extra part of the zipties should be cut off
* When connecting wires (i.e motor to motor controller), make sure the prongs have the same direction (red wire lines up with red wire and blue lines up with blue). Switching direction of prong switches direction of motor, and you want to be sure you know what the direction is.
|
PHP
|
UTF-8
| 614
| 2.609375
| 3
|
[
"Apache-2.0"
] |
permissive
|
<?php
declare(strict_types=1);
namespace SimpleMVC\Controller;
use SimpleMVC\Model\Article as ArticleModel;
use League\Plates\Engine;
use Psr\Http\Message\ServerRequestInterface;
class Article extends AbstractArticle implements ControllerInterface
{
public function execute(ServerRequestInterface $request)
{
$id = intval($request->getAttribute('id'));
if(!empty($id))
{
$data = [
'article' => $this->article->find($id)->toArray(),
'method' => 'POST', // PUT
];
}
else
{
$data = ['method' => 'POST', 'article' => null];
}
echo $this->plates->render('article', $data);
}
}
|
C
|
UTF-8
| 592
| 3.421875
| 3
|
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
FILE* archivo;
const char* nombre = "Archivo.txt";
const char* escribir = "w+";
void EscribirArchivo(char* cadena);
void LeerArchivo();
int main()
{
char* palabra;
scanf(&palabra);
EscribirArchivo(palabra);
LeerArchivo();
return(0);
}
void EscribirArchivo(char* cadena)
{
archivo = fopen(nombre, escribir);
fprintf(archivo, "%s", cadena);
fclose(archivo);
}
void LeerArchivo()
{
int palabra = 0;
archivo = fopen(nombre, "r");
while (1)
{
palabra = fgetc(archivo);
if (feof(archivo))
{
break;
}
printf("%c", palabra);
}
}
|
Markdown
|
UTF-8
| 5,529
| 2.9375
| 3
|
[
"MIT"
] |
permissive
|
{
"title": "The ‘L’ongest Day Yet",
"date": "2018-12-24T09:24:27-06:00",
"draft": "false",
"authors": ["Elise Fetzer"],
"thumbnail": {
"alt": "Sunset from the Cancer Survivors’ Garden in Grant Park",
"position": "center",
"src": "cancer-survivors-garden-sunset",
"type": "jpg"
}
}
“Let’s ride the whole [‘L’][cta] in one day,” they said. “It’ll be fun,” they said.
When Reuben asked me about a month ago if I wanted to ride the whole ‘L’ in a day for this cross-cultural field experience, I thought, “Yeah, that should be interesting.” It sounded like a good way to explore and see the city of Chicago, right?
Well, I didn’t totally know what I was in for (although, Reuben did try to warn me).
The initial estimate for this endeavor was about 7–8 hours based on some web journalist who’d done it. That seems feasible, right? Start at 8 a.m. and be done by 4 p.m., 5 p.m. tops, right?
Ha!
Little did we know …
Well, we encountered our first delay here when it took me approximately 20 minutes to add three sentences to my [blog post][blog] from Sunday’s gathering, among other things. So we actually boarded the first train, which was the Purple Line to Linden around 8:45. Then, when you add in the couple of pit stops for Corban (who did incredibly well throughout this venture!), one extra pit stop for Dramamine (for me), several unexpectedly _long_ waits between trains, and food breaks, you’ll find us still invested about fourteen hours later at 10:45 p.m., which is just about when I got off the Orange Line at Midway.
But, here’s a little more on what actually happened during that time:
Like I said, we started with the Purple Line to Linden. As we got into Evanston and then the edge of Wilmette, you could see where the suburban sprawl started, where the density lightened up a little bit. Everything was clean and upkept overall. This was also true throughout most of the North Side of the city.
The contrast between our rides through the North Side of the city and the South Side of the city was stark.
If you ride the Green Line south or west, you’ll see many vacant lots, many with litter throughout, trash piles in yards, bits of building debris in some of these piles, old train tacks left piled up, and many more buildings that haven’t received as much care and attention as the majority of those on the North Side.
In regards to the vacant lots, many of them were probably not always vacant. In fact, they were probably once people’s homes—homes that were eventually determined to be blighted, an eye sore to the neighborhood. And many of the new apartment buildings that cropped up on occasion were probably there for similar reasons, with the old residents of the worn houses kicked out and forced to find new places to go.
An even starker contrast appears when you compare the side-by-side ghettoization of neighborhoods like Woodlawn to the gentrification of neighborhoods like Hyde Park. And when we got to the west end of the Green Line in Harlem/Lake, you could see a similar abrupt contrast between the neighborhood of Austin and the suburb of Oak Park.
Beyond the neighborhoods along the ‘L’, there were many moments within the train cars that reflected the unique culture that persists in these spaces.
Aboard those trains we met people from backgrounds as diverse as anywhere on our planet, all of us sharing the same space, even if only for a short time. In those times, with all that separates us in others aspect of life, there was something humbling about the opportunity to recognize each other’s humanity.
Sometimes these moments weren’t the most pleasant, such as when a woman was having a loud argument over the phone with her children’s father. On the one hand, it felt awkward to overhear what was in many ways such an intimate conversation. But on the other hand, it was a reminder that each one of the thousands of people we shared a train ride with that day has a life with struggles that we may only be aware of for a brief moment.
There were some really great moments, like when we struck up conversations with some of the people we met, all thanks to Corban—because no one could resist the cute-baby factor.
We met Linda, who was commuting to a line-dancing class on her day off. She normally has a commute, probably at least two hours long to get to her work at a library on the North Side of the city from her home on the South Side.
We also met Antonio and his brothers, who were together for the first time in over ten years because Antonio was visiting from Virginia where he’s lived for about fifteen years.
And there were those experiencing homelessness who were trying to sleep on the train, riding lines back and forth similar to how we were, except they weren’t doing it for “fun” or for a “cross-cultural” experience. This was their way of getting out of the cold, just figuring out how to get by.
Even as our day on the ‘L’ went longer than anticpated, I was reminded that it was my privilege to choose to have this experience. I don’t have to strategize how to find a warm place to sleep. I don’t have to take the ‘L’ as part of a two-plus hour commute to work every day. I didn’t have to be doing anything else during that time. It was my free choice.
So as long as the day was, and while I’ll likely never do it again, it was worth it.
[blog]: /2018/12/communion-gathering-and-prayer-reflection
[cta]: https://www.transitchicago.com/maps/
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.