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,199
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
# taskpaper-document
A robust [Taskpaper](https://www.taskpaper.com/) parser, builder, and serializer with no external dependencies.
Written in pure ES5. Works in node > `0.10.x` and as a browser bundle.
A project design goal is to always have input perfectly match serialized output, even for fuzzy or non-Taskpaper documents.
## Installation
npm install taskpaper-document
### Example: Construct a new Document
```javascript
var TaskpaperDocument = require('taskpaper-document');
var doc = new TaskpaperDocument();
doc.project('A little Project').chain
.task('A first task')
.task('A second task');
doc.serialize();
// A little Project:
// - A first task
// - A second task
```
### Example: Parse an Existing Document
```javascript
var fs = require('fs');
var TaskpaperDocument = require('taskpaper-document');
var fileContents = fs.readFileSync('./assets/example.taskpaper');
var doc = TaskpaperDocument.from(fileContents);
doc.serialize();
```
## Contributing
Tests are written in [tape](https://github.com/substack/tape). Run tests with:
npm test
All patches must pass the rules found in `eslintrc.js`. Manually lint via:
npm run lint
|
C++
|
UTF-8
| 1,795
| 3.28125
| 3
|
[] |
no_license
|
#include "bank_account.h"
#include <iostream>
const int CUSTOMERS = 4;
int main() {
using std::cout;
using std::cin;
using std::endl;
// the next line of code generates a compile error, since one cannot downcast, but you can upcast
BankAcc db = BankAcc("Paul Hogan", 10000, 1000);
// test_view(db);
Abstract_BankAcc * p_customers[CUSTOMERS];
std::string name;
long accNo;
double bal;
char accType;
for (int i = 0; i < CUSTOMERS; i++) {
cout << "Customer name : ";
cin >> name;
cout << "Account Number : ";
cin >> accNo;
cout << "Initial Deposit: ";
cin >> bal;
cout << "\n1 = Bank Account 2 = Bank Account Plus: ";
while (cin >> accType && (accType != '1' && accType != '2'))
cout << "Enter 1 or 2: ";
if (accType == '1')
p_customers[i] = new BankAcc(name, accNo, bal);
else {
double xLimit, xRate;
cout << "Enter upper limit : £";
cin >> xLimit;
cout << "Enter interest rate: ";
cin >> xRate;
p_customers[i] = new BankAccPlus(name, accNo, bal, xLimit, xRate);
}
while (cin.get() != '\n')
continue;
}
cout << endl;
for (int i = 0; i < CUSTOMERS; i++) // free memory
delete p_customers[i];
cout << "Done.\n";
return 0;
}
/*
void testa(BankAcc & rb); // uses rb.showAcc()
void testb(BankAcc * pb); // uses pb->showAcc()
void testc(BankAcc b); // uses b.showAcc()
int main() {
BankAcc x("Peter Koukoulis", 123432, 10000.0);
BankAccPlus y("Paul Simon", 232313, 12345.0);
testa(x); // uses BankAcc::showAcc()
testa(y); // uses BankAccPlus::showAcc()
testb(x); // uses BankAcc::showAcc()
testb(y); // uses BankAccPlus::showAcc()
testc(x); // uses BankAcc::showAcc()
testc(y); // uses BankAcc::showAcc()
return 0;
}
..
..
*/
|
PHP
|
UTF-8
| 4,574
| 2.546875
| 3
|
[] |
no_license
|
<?php
/**
* Created by PhpStorm.
* User: yang
* Date: 2019/4/8
* Time: 下午7:18
*/
require_once __DIR__ . '/MysqlService.php';
require_once __DIR__ . '/RedisService.php';
Class ChatService
{
private $table;
private $ser;
public function __construct($ser)
{
$this->ser = $ser;
$this->table = new Swoole\Table(1024);
$this->table->column('fd', swoole_table::TYPE_INT, 16);
$this->table->column('room_id', swoole_table::TYPE_INT, 16);
$this->table->column('name', swoole_table::TYPE_STRING, 64);
$this->table->column('token', swoole_table::TYPE_STRING, 64);
$this->table->create();
}
public function sendMsg($fd, $data)
{
$user = $this->table->get($fd);
$data = [
'msg_info' => [
'from_id' => $fd,
'from_name' => $user['name'],
'type' => 'user',
'text' => $data['msg'],
],
'type' => 'msg_info',
];
$this->wsSend($data);
return true;
}
public function changeRoom($fd, $data)
{
//更换房间
return true;
}
public function login($fd, $data)
{
$this->joinRoom($fd, $data);
$this->getUserList();
$this->getRoomList();
return true;
}
public function logout($fd)
{
//从房间踢出
$this->leaveRoom($fd);
$this->getUserList();
return true;
}
public function wsSend($data)
{
$ret = [
'code' => 0,
'msg' => 'OK',
'data' => $data,
];
$ret = json_encode($ret);
foreach ($this->ser->connections as $fd) {
$this->ser->push($fd, $ret);
}
return true;
}
public function getUserList()
{
$count = $this->table->count();
echo 'count:' . $count;
$userList = [];
foreach ($this->table as $key => $value) {
$userList[] = $value['name'];
}
$data = [
'user_info' => [
'count' => $count,
'user_list' => $userList,
],
'type' => 'user_info',
];
$this->wsSend($data);
return true;
}
public function getRoomList()
{
go(function (){
$redis = RedisService::getInstance()->getRedis();
$roomList = $redis->request(['hgetall','chat:room:list']);
RedisService::getInstance()->freeRedis($redis);
$data = [
'room_info' => [
'count' => count($roomList),
'room_list' => $roomList,
],
'type' => 'room_info',
];
$this->wsSend($data);
return true;
});
}
public function leaveRoom($fd)
{
$user = $this->table->get($fd);
$this->table->del($fd);
//构建返回数据
$data = [
'msg_info' => [
'from_id' => $fd,
'from_name' => '系统',
'type' => 'system',
'text' => $user['name'] . '离开房间',
],
'type' => 'msg_info',
];
$fds = $this->getRoomUser($user['room_id']);
$this->wsSendSome($fds,$data);
return true;
}
public function joinRoom($fd, $data)
{
$user = [
'fd' => $fd,
'name' => $data['name'],
'token' => $data['token'],
'room_id' => $data['room_id'] ?? 0,
];
$this->table->set($fd, $user);
$data = [
'change_room_info' => [
'from_name' => '系统',
'type' => 'system',
'text' => $data['name'] . '进来了',
],
'type' => 'change_room_info',
];
$fds = $this->getRoomUser($user['room_id']);
$this->wsSendSome($fds,$data);
return true;
}
public function getRoomUser($roomId){
$fds = [];
foreach ($this->table as $key => $row){
if ($roomId == $row['room_id']){
$fds[] = $key;
}
}
return $fds;
}
public function wsSendSome($fds,$data)
{
$ret = [
'code' => 0,
'msg' => 'OK',
'data' => $data,
];
$ret = json_encode($ret);
foreach ($fds as $fd) {
$this->ser->push($fd, $ret);
}
return true;
}
}
|
C++
|
UTF-8
| 1,012
| 2.765625
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
//
// ToneMapping-Ward.h
//
// Created by Jietong Chen on 2019/5/6.
//
#ifndef RAYTRACING_TONEMAPPING_WARD_H
#define RAYTRACING_TONEMAPPING_WARD_H
#include "Shader.h"
namespace RayTracer {
class ToneMapping_Ward : public Shader {
public:
ToneMapping_Ward();
ToneMapping_Ward( const ToneMapping_Ward& other );
ToneMapping_Ward& operator=( const ToneMapping_Ward& other );
float4 DirectShading( float3 lightPosition[],
float4 lightColor[] ) const override;
float4 IndirectShading() const override;
/**
* Use the shader program shade a point.
*
* @return the color of the point
*/
float4 Shading() const override;
/**
* The type of the shader program.
*
* @return the shader type
*/
ShaderType Type() const override;
public:
float4 color;
float scalefactor;
};
}
#endif //RAYTRACING_TONEMAPPING_WARD_H
|
TypeScript
|
UTF-8
| 973
| 3.203125
| 3
|
[
"MIT"
] |
permissive
|
/**
* @description Converts all named imports to require
* @param {string} content Initial file content
* @returns {string} Converted file content
* @example
* import { name1, name2 as n2 } from 'src/my_lib';
* // const { name1, name2: n2 } = require("./src/my_lib");
*/
export function namedImpt(content: string) {
const regexp = /import {.*} from .*/g
const worker = function (match) {
const imported = match
.match(/(?<={.*)(\w.*\w)(?=.*})/g)[0]
.split(", ")
.map(function (module) {
if (/\w+ as \w+/.test(module)) {
let regexp = /(?<module>[\w]+) as (?<key>[\w]+)/
return module.replace(regexp, "$<module>: $<key>")
} else return module
})
const slot = [
/.* from (?<name>.[.\\\w/:]+.);?/,
`const { ${imported.join(", ")} } = require($<name>);`,
]
return [match, match.replace(...slot)]
}
return this.appease(content, regexp, worker)
}
export default { namedImpt }
|
JavaScript
|
UTF-8
| 1,703
| 2.53125
| 3
|
[] |
no_license
|
import React, {Component} from 'react';
import axios from 'axios';
class MailBox extends Component {
constructor() {
super();
this.state = {
mails: []
};
}
async componentDidMount() {
if (this.props.folder) {
const response = await axios.get(`/api/folders/${this.props.folder}`);
this.setState({
mails: response.data.mails
});
}
}
async componentDidUpdate(prevProps) {
if (prevProps.folder !== this.props.folder) {
const response = await axios.get(`/api/folders/${this.props.folder}`);
this.setState({
mails: response.data.mails
});
}
}
getSender(senderEmail) {
const sender = senderEmail.slice(0, senderEmail.indexOf('@'));
return sender[0].toUpperCase() + sender.slice(1);
}
getDate(time) {
return time.slice(0, time.indexOf('T'));
}
render() {
return (
<div className="mailbox">
{
this.props.folder && this.state.mails.length ?
this.state.mails.map(mail => (
<div className="single-mail" key={mail.id}>
<div className="left-mail"></div>
<div className="right-mail">
<div className="sender">{this.getSender(mail.sender)}<span className="date">{this.getDate(mail.createdAt)}</span></div>
<div className="subject">{mail.subject}</div>
<div className="summary">{mail.content}</div>
</div>
</div>
)) :
!this.props.folder ? <div className="message">Select a folder to view mails</div> : <div className="message">This folder is currently empty</div>
}
</div>
)
}
}
export default MailBox
|
JavaScript
|
UTF-8
| 1,787
| 3
| 3
|
[] |
no_license
|
var baseIngr = [];
function setLocalCakeCount() {
"use strict";
// Code borrowed from w3C.
// Check browser support
if (typeof (Storage) !== "undefined") {
// Store
if (window.localStorage.getItem("cakeCount")) {
var localCakeCount;
localCakeCount = document.getElementById("numCakes").value;
window.localStorage.setItem("cakeCount", localCakeCount);
} else {
window.localStorage.setItem("cakeCount", 1);
}
}
}
function updateRecipe() {
"use strict";
var i, numCakes, asideElement, ingrList;
numCakes = document.getElementById("numCakes").value;
if (numCakes < 1 || numCakes > 10) {
numCakes = 1;
document.getElementById("numCakes").value = 1;
}
asideElement = document.getElementsByTagName("aside")[0];
ingrList = asideElement.getElementsByTagName("li");
for (i = 0; i < ingrList.length; i++) {
var tempStr = ingrList[i].textContent;
var tempNumber = parseInt(tempStr.match(/[0-9]+/));
if (typeof (baseIngr[i]) === "undefined") {
baseIngr[i] = tempNumber;
}
tempNumber = baseIngr[i] * numCakes;
tempStr = tempStr.replace(/[0-9]+/, tempNumber);
ingrList[i].textContent = tempStr;
}
setLocalCakeCount();
}
window.oninput = function () {
"use strict";
updateRecipe();
};
window.onload = function () {
"use strict";
// Code borrowed from w3C.
// Check browser support
if (typeof (Storage) !== "undefined") {
// Store
if (window.localStorage.getItem("cakeCount")) {
document.getElementById("numCakes").value = parseInt(window.localStorage.getItem("cakeCount"));
updateRecipe();
}
}
};
|
Java
|
UTF-8
| 787
| 3.015625
| 3
|
[] |
no_license
|
package it.unicam.cs.pa.jlife105718.Model.Printer;
import it.unicam.cs.pa.jlife105718.Model.Position.IPosition;
import java.util.List;
/**
* Interfaccia funzionale responsabile della stampa di un insieme di coordinate dello stesso tipo.
* La creazione di una classe che implementa questa interfaccia è delegata alla PositionFactory.
*/
@FunctionalInterface
public interface IPrintPosition<T extends IPosition> {
/**
* metodo responsabile della visualizzazione sotto forma di stringa di un insieme di coordinate che rappresentano
* la posizione di una cella nella griglia
* @param posizione contiene le coordinate che identificano questa posizione
* @return le coordinate rappresentate come stringhe
*/
List<String> toStringFormat(T posizione);
}
|
C++
|
UTF-8
| 1,058
| 3.609375
| 4
|
[] |
no_license
|
/**
* @input A : Integer array
* @input n1 : Integer array's ( A ) length
* @input B : Integer
*
* @Output Integer array. You need to malloc memory, and fill the length in len1
*/
int *maxone(int *A, int n1, int B, int *len1)
{
int stored;
int i;
int sum = 0;
int limit = B;
int max = 0;
int endIndex;
for (i = 0; i < n1; i++)
{
if (A[i] == 0 && limit == B)
{
stored = i + 1;
}
if (A[i] == 0)
{
limit--;
}
if (limit == -1)
{
if (max < sum)
{
max = sum;
endIndex = i;
}
sum = 0;
i = stored - 1;
limit = B;
}
else
{
sum += 1;
}
}
if (max < sum)
{
max = sum;
endIndex = i;
}
endIndex -= 1;
int *arr = (int *)malloc(sizeof(int) * max);
for (i = max - 1; i >= 0; i--)
{
arr[i] = endIndex--;
}
*len1 = max;
return arr;
}
|
Python
|
UTF-8
| 7,179
| 2.671875
| 3
|
[] |
no_license
|
#!usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Author : zhaoguanhua
@Email : zhaogh@hdsxtech.com
@Time : 2020/4/16 14:18
@File : IMDB_test.py
@Software: PyCharm
"""
import numpy as np
from keras.datasets import imdb
from keras import models
from keras import layers
from keras import regularizers
import matplotlib.pyplot as plt
def vectorize_sequences(sequences,dimension=10000):
results = np.zeros((len(sequences),dimension))
for i,sequence in enumerate(sequences):
results[i,sequence]=1.
return results
def base_model():
model = models.Sequential()
model.add(layers.Dense(16, activation='relu', input_shape=(10000,)))
model.add(layers.Dense(16, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))
model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])
return model
def Smaller_model():
model = models.Sequential()
model.add(layers.Dense(4, activation='relu', input_shape=(10000,)))
model.add(layers.Dense(4, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))
model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])
return model
def L2_model():
model = models.Sequential()
model.add(layers.Dense(16,kernel_regularizer=regularizers.l2(0.001),
activation='relu', input_shape=(10000,)))
model.add(layers.Dense(16,kernel_regularizer=regularizers.l2(0.001),
activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))
model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])
return model
def L1_model():
model = models.Sequential()
model.add(layers.Dense(16,kernel_regularizer=regularizers.l1(0.001),
activation='relu', input_shape=(10000,)))
model.add(layers.Dense(16,kernel_regularizer=regularizers.l1(0.001),
activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))
model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])
return model
def L1_L2_model():
model = models.Sequential()
model.add(layers.Dense(16,kernel_regularizer=regularizers.l1_l2(0.001),
activation='relu', input_shape=(10000,)))
model.add(layers.Dense(16,kernel_regularizer=regularizers.l1_l2(0.001),
activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))
model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])
return model
def Dropout_model():
model = models.Sequential()
model.add(layers.Dense(16, activation='relu', input_shape=(10000,)))
model.add(layers.Dropout(0.5))
model.add(layers.Dense(16, activation='relu'))
model.add(layers.Dropout(0.5))
model.add(layers.Dense(1, activation='sigmoid'))
model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])
return model
(train_data,train_labels),(test_data,test_labels) = imdb.load_data(num_words=10000)
x_train = vectorize_sequences(train_data)
x_test = vectorize_sequences(test_data)
#标签向量化
y_train = np.asarray(train_labels).astype('float32')
y_test = np.asarray(test_labels).astype('float32')
#训练集和验证集
x_val = x_train[:10000]
partial_x_train = x_train[10000:]
y_val = y_train[:10000]
partial_y_train = y_train[10000:]
#***********************************************************************************************************
#基本网络
#定义模型1
model = base_model()
#编译模型
model.compile(optimizer='rmsprop',loss='binary_crossentropy',metrics=['accuracy'])
#训练模型
history = model.fit(partial_x_train,partial_y_train,epochs=20,batch_size=512,validation_data=(x_val,y_val))
history_dict = history.history
loss_values = history_dict['loss']
val_loss_values = history_dict['val_loss']
#***********************************************************************************************************
#测试减少网络规模
#定义模型2
model2=Smaller_model()
#训练模型2
history2 = model2.fit(partial_x_train,partial_y_train,epochs=20,batch_size=512,validation_data=(x_val,y_val))
history_dict2 = history2.history
loss_values2 = history_dict2['loss']
val_loss_values2 = history_dict2['val_loss']
#***********************************************************************************************************
#测试L2权重正则化
#定义模型3
model3 = L2_model()
#训练模型3
history3 = model3.fit(partial_x_train,partial_y_train,epochs=20,batch_size=512,validation_data=(x_val,y_val))
history_dict3 = history3.history
loss_values3 = history_dict3['loss']
val_loss_values3 = history_dict3['val_loss']
#***********************************************************************************************************
#测试L1权重正则化
#定义模型4
model4=L1_model()
#训练模型4
history4 = model4.fit(partial_x_train,partial_y_train,epochs=20,batch_size=512,validation_data=(x_val,y_val))
history_dict4 = history4.history
loss_values4 = history_dict4['loss']
val_loss_values4 = history_dict4['val_loss']
#***********************************************************************************************************
#测试L1_L2权重正则化
#定义模型5
model5=L1_L2_model()
#训练模型4
history5 = model5.fit(partial_x_train,partial_y_train,epochs=20,batch_size=512,validation_data=(x_val,y_val))
history_dict5 = history5.history
loss_values5 = history_dict5['loss']
val_loss_values5 = history_dict5['val_loss']
#***********************************************************************************************************
#测试Dropout
#定义模型6
model6=Dropout_model()
#训练模型4
history6 = model6.fit(partial_x_train,partial_y_train,epochs=20,batch_size=512,validation_data=(x_val,y_val))
history_dict6 = history6.history
loss_values6 = history_dict6['loss']
val_loss_values6 = history_dict6['val_loss']
epochs = range(1,len(loss_values)+1)
#对比几种模型的验证损失
plt.plot(epochs,val_loss_values,'r',label='Original model')
plt.plot(epochs,val_loss_values2,'g',label='Smaller model')
plt.plot(epochs,val_loss_values3,'b',label='L2-regularized model')
plt.plot(epochs,val_loss_values4,'r+',label='L1-regularized model')
plt.plot(epochs,val_loss_values5,'g+',label='L1_L2-regularized model')
plt.plot(epochs,val_loss_values6,'b+',label='Dropout-regularized model')
plt.title('validation loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()
# #绘制训练损失和验证损失
# plt.plot(epochs,loss_values,'r',label='Training loss')
# plt.plot(epochs,val_loss_values,'b',label='Validation loss')
# plt.title('Training and validation loss')
# plt.xlabel('Epochs')
# plt.ylabel('Loss')
# plt.legend()
# plt.show()
# #绘制训练精度和验证精度
# plt.clf()
# acc=history_dict['acc']
# val_acc=history_dict['val_acc']
#
# plt.plot(epochs,acc,'g',label='Training acc')
# plt.plot(epochs,val_acc,'b',label='Validation acc')
# plt.title('Training and validation accuracy')
# plt.xlabel('Epochs')
# plt.ylabel('Accuracy')
# plt.legend()
# plt.show()
|
Python
|
UTF-8
| 506
| 3.59375
| 4
|
[
"CC-BY-4.0"
] |
permissive
|
# this sets up a figure with some dotted lines on y=0 and x=0 for reference
with plt.xkcd():
plt.figure(figsize=(8, 8))
plt.plot([0, 0], [-0.5, 1.5], ':', color='xkcd:black')
plt.plot([-0.5, 1.5], [0, 0], ':', color='xkcd:black')
# determine which variables you want to look at
plt.scatter(v_w, # variable on the abscissa / x-axis
v_s) # variable on the ordinate / y-axis
plt.xlabel('world-motion velocity [m/s]')
plt.ylabel('self-motion velocity [m/s]')
plt.show()
|
C++
|
UTF-8
| 5,269
| 2.5625
| 3
|
[] |
no_license
|
// pool.hpp
//
// Class Implementation: wdl::threadpool::pool
#pragma once
#include <windows.h>
#include <chrono>
#include <wdl/timing/filetime.hpp>
#include <wdl/threadpool/base.hpp>
#include <wdl/threadpool/environment.hpp>
#include <wdl/threadpool/cleanup_group.hpp>
namespace wdl::threadpool
{
// wdl::threadpool::work_callback_f
//
// Defines function signature for work callback.
using work_callback_f = void(__stdcall*)(
PTP_CALLBACK_INSTANCE,
void*,
PTP_WORK);
// wdl::threadpool::wait_completion_f
//
// Defines function signature for wait completion callback.
using wait_completion_f = void(__stdcall*)(
PTP_CALLBACK_INSTANCE,
void*,
PTP_WAIT,
TP_WAIT_RESULT);
// wdl::threadpool::timer_completion_f
//
// Defines callback signature for timer completion callback.
using timer_completion_f = void(*)(
PTP_CALLBACK_INSTANCE,
void*,
PTP_TIMER);
// wdl::threadpool::io_completion_f
//
// Defines function signature for IO completion callback.
using io_completion_f = void(*)(
PTP_CALLBACK_INSTANCE,
void*,
void*,
unsigned long,
ULONG_PTR,
PTP_IO);
// wdl::threadpool::pool_cancellation_policy
//
// Determines if the created pool cancels
// outstanding callbacks on destruction.
enum class pool_cancellation_policy
{
no_cancel,
cancel
};
// wdl::threadpool::pool
//
// Wrapper around user-controlled threadpool.
class pool
{
pool_handle m_handle;
environment m_environment;
cleanup_group m_cleanup_group;
pool_cancellation_policy m_policy;
public:
pool(pool_cancellation_policy policy = pool_cancellation_policy::no_cancel)
: m_handle{ ::CreateThreadpool(nullptr) }
, m_cleanup_group{}
, m_policy{ policy }
{
m_cleanup_group.set_cancellation_policy(
static_cast<bool>(policy)
? cleanup_group_cancellation_policy::cancel
: cleanup_group_cancellation_policy::no_cancel
);
// associate the private pool with the internal environment
::SetThreadpoolCallbackPool(
m_environment.get(),
m_handle.get());
// and set a cleanup group for the environment
::SetThreadpoolCallbackCleanupGroup(
m_environment.get(),
m_cleanup_group.get(),
nullptr);
}
// rely on unique_handle for release
~pool() = default;
// non-copyable, non-movable
pool(pool const&) = delete;
pool& operator=(pool const&) = delete;
pool(pool&&) = delete;
pool& operator=(pool&&) = delete;
void set_max_threadcount(unsigned long count)
{
::SetThreadpoolThreadMaximum(m_handle.get(), count);
}
bool set_min_threadcount(unsigned long count)
{
return ::SetThreadpoolThreadMinimum(m_handle.get(), count);
}
PTP_WORK create_work(work_callback_f callback, void* ctx)
{
auto work_object = ::CreateThreadpoolWork(
callback,
ctx,
m_environment.get());
return work_object;
}
PTP_WAIT create_wait(wait_completion_f callback, void* ctx)
{
auto wait_object = ::CreateThreadpoolWait(
callback,
ctx,
m_environment.get());
return wait_object;
}
PTP_TIMER create_timer(timer_completion_f callback, void* ctx)
{
auto timer_object = ::CreateThreadpoolTimer(
callback,
ctx,
m_environment.get());
return timer_object;
}
PTP_IO create_io(HANDLE handle, io_completion_f callback, void* ctx)
{
auto io_object = ::CreateThreadpoolIo(
handle,
callback,
ctx,
m_environment.get());
return io_object;
}
bool is_valid() const noexcept
{
return static_cast<bool>(m_handle);
}
explicit operator bool()
{
return static_cast<bool>(m_handle);
}
};
PTP_WORK create_work(pool& p, work_callback_f fn, void* ctx)
{
return p.create_work(fn, ctx);
}
void submit_work(PTP_WORK work_object)
{
::SubmitThreadpoolWork(work_object);
}
PTP_WAIT create_wait(pool& p, wait_completion_f fn, void* ctx)
{
return p.create_wait(fn, ctx);
}
void set_wait(PTP_WAIT wait_object, HANDLE handle)
{
::SetThreadpoolWait(wait_object, handle, nullptr);
}
template <typename DurationType>
void set_wait(
PTP_WAIT wait_object,
HANDLE handle,
DurationType timeout
)
{
auto ft = wdl::timing::to_filetime<DurationType>(timeout);
::SetThreadpoolWait(wait_object, handle, &ft);
}
PTP_TIMER create_timer(pool& p, timer_completion_f fn, void* ctx)
{
return p.create_timer(fn, ctx);
}
template <typename DueDuration,
typename PeriodDuration,
typename WindowDuration>
void set_timer(
PTP_TIMER timer_object,
DueDuration due_time,
PeriodDuration period,
WindowDuration window
)
{
auto ft = wdl::timing::to_filetime<DueDuration>(due_time);
auto p = std::chrono::duration_cast<std::chrono::milliseconds>(period).count();
auto w = std::chrono::duration_cast<std::chrono::milliseconds>(window).count();
// TODO: explicit narrowing conversions
::SetThreadpoolTimer(
timer_object,
&ft,
static_cast<unsigned long>(p),
static_cast<unsigned long>(w)
);
}
PTP_IO create_io(pool& p, HANDLE handle, io_completion_f fn, void* ctx)
{
return p.create_io(handle, fn, ctx);
}
void start_io(PTP_IO io_object)
{
::StartThreadpoolIo(io_object);
}
}
|
Markdown
|
UTF-8
| 920
| 3.140625
| 3
|
[] |
no_license
|
# 第01节:MySQL数据库概述
### 一、概述
数据库用来存储应用程序中的数据,需要持久化存储,不能像变量一样放在内存中,服务器重启就消失了,所以需要将数据存储在数据库中叨叨持久化存储的目的。
### 二、常用的关系型数据库
1. MySQL:开源免费
2. Oracle:大型系统(银行系统,ERP系统,医院系统等,Java体系)
3. SQL server:基于windows server服务器中使用,c#, .net体系
关系型数据库使用**表**来存储数据
[MySQL的下载官网](https://downloads.mysql.com/archives/community/)
数据库安装完成后,还要安装sqlyog(数据库操作可视化工具)
### 三、MySQL
#### SQL
结构化查询语言,所有关系型数据库都使用SQL来操作数据库。
#### 连接数据库
1. 使用命令工具连接:`mysql -u root -p`
2. 使用SQLyog连接(可视化工具)
|
Markdown
|
UTF-8
| 48,106
| 3.28125
| 3
|
[] |
no_license
|
## 女性的性爱动机(通识课堂)
##### 辛迪·M.梅斯顿博士; 戴维·M.巴斯博士
爱的相遇
2014-01-17 14:11:07
距离相近的人不一定能够碰撞出爱的火花,但反复接触(次数要足够多)能够增加相爱的概率。一项研究发现,多次短暂的正面相对——不超过35秒,也不交谈——能够增加彼
此的好感。换言之,我们喜欢熟悉的面孔。
迷人的味道
2014-01-17 14:20:19
也许男人天生嗅觉迟钝或者天生是视觉动物,女人的芬芳不能立刻挑起男人的性欲。相反,味道是捕获女人心的撒手锏。清新怡人可以倾倒女人,恶臭难闻只能吓倒女人。
2014-01-17 14:20:46
女性认为身材匀称的男性极具魅惑,特别是当处于排卵期时,正是这段时间女性最易受孕。显然,女性敏锐的嗅觉是进化的结果,她们择偶时倾向选择健康的、有着优质基因的男
性。女人红杏出墙时寻觅的情人一般都身材匀称,这再次表明身材匀称的男性最能挑起女人的情欲。
散发性感“男人味”
2014-01-17 14:28:12
迷人的味道不仅影响女性的择偶,而且还影响女性做爱的时间和频率,甚至受孕概率。有关学者曾指出经常闻男性散发出的费洛蒙能增加女性的受孕概率。费洛蒙是口腔、腋窝、
乳房、肛门、泌尿管等部位的腺体分泌物。除人类以外,其他哺乳动物都有一种被称之为“犁鼻器”的特殊嗅觉器官,“犁鼻器”能够识别费洛蒙信号,“主持”动物界的交配仪
式。一项研究发现,规律的性生活(一周至少一次)能够调整女性的月经周期,提高女性基础体温从而加大受孕概率,增加黄体期的雌激素分泌,黄体期指排卵后到月经来潮的前
一天。另一项研究指出,40天内做爱超过两次的女性排卵次数远远高于做爱较少的女性。
情场得意
2014-01-17 14:29:00
事实上,不仅女性,连男性也承认肩宽胯窄的男人往往光芒四射,器宇轩昂,能够在气势上压倒众人,这说明女人通常爱慕那些超群出众的男人。肩宽胯窄的男人首次发生性关系
的时间也比较早,一般是16岁左右。经调查发现,相比肩窄的男性,他们的性伴侣比较多,风流韵事也比较多。另外,他们也经常受到已婚妇女的勾引。身材性感也容易招他人
嫉恨,也就是说肩宽胯窄的男人容易被其他男人当成潜在的情敌。
风度翩翩
2014-01-17 14:45:01
举手投足间能够表现一个人骨骼的力量,肌肉的结实程度,甚至平衡能力。如果一个人行走潇洒,舞姿曼妙,那么就可以做如下推断:第一,表明他正青春年少,活力四射。比如
,少年的舞步刚劲有力,而年老者总给人心有余力不足之感。第二,表明他精力充沛,身体健康,气运正盛。
2014-01-17 14:49:21
除走路姿势外,男人的其他动作对女人来讲也有深刻的含义。单向的同性触摸,比如一个男人伸手去摸另一个男人的后背等,能够很好地表达双方的地位,这点已被反复证明过。
女性认为“主动触摸者”比较强势,也欣赏这样的男人。另外,扩展动作,比如伸展胳膊或腿,也能够很好地表达一个人是否强势。在女性看来,举手投足洒脱的男性,比如不会
做双手交叉抱胸的动作,也会显得能力出众,比较有威望。
有性格才能性感
2014-01-17 15:38:46
经过研究发现两种性格特点最能吸引女性,一是幽默感,二是自信。
“互补”胜过“相似”?
2014-01-17 15:42:10
简而言之,相似性有助于感情稳定。志趣相投,才能交流沟通,彼此扶持,互相依偎,从而减小了分手的风险。所以,尽管“互补”的人也会相互吸引,但婚姻感情中主要还是“
物以类聚,人以群分”。
他是我的菜
2014-01-17 15:55:26
女性的性爱取舍是潜意识的。男性身上的味道、浑厚的嗓音都深深吸引着她们。但她们并不知道为什么有的味道那么迷人而有的却令人作呕。女性知道什么样的男人性感,但是却
不知道深藏其后的人类进化的奥妙。女性在排卵期时喜欢健硕硬朗的男性,而在其他时候则可能倾向于斯文优雅的男性,这恰恰展现了女性无与伦比的择偶智慧,尽管她们自己对
此毫不知情。
抚摸的神奇魔力
2014-01-17 16:10:17
女人的肌肤可以说是最大的“性点”。肌肤由复杂的神经系统构成,能够感受温度、触摸、质地等的细微变化。身体对性刺激特别敏感的器官或区域称为“性感带”,也称为“性
敏感区”。最为人所知的性感带有脖子、耳垂、嘴唇、胸部、生殖器、臀部、大腿内侧、肛门、膝盖后部、手指、脚趾等。有的女性几乎全身都是性感带。不论身体的哪个部位,
只要触摸,如绒毛轻柔地拂过脸颊、裸露肌肤的碰触、让别人或给别人按摩,都能强烈激发性欲。
2014-01-17 16:10:25
女性的乳头及乳晕(乳头周围皮肤色素沉着较深的环形区)是神经末梢的聚集区,所以非常敏感。女性的乳房受到抚摸或按摩后,可以使血液流入乳房组织,细小的肌肉纤维促使
乳头硬挺。乳头和乳晕变得更加敏感,从而增强女性的性快感:
性唤起
2014-01-17 16:14:29
当女性在性唤起时,血液会流向骨盆区,包括阴道、阴唇、阴蒂以及尿道、子宫,甚至输卵管和卵巢等部位。这种性唤起引起的血液汇集叫作“生殖器血管充血”。在未发生性唤
起时,女性阴道从大小和形状上看类似于意大利烤面卷——不带馅,4英寸长,内壁不光滑,有平行分布的褶皱。当血管充血时,阴道内2/3显著扩张,加大能够容纳外物的空
间。阴道上下侧膨胀,子宫也相应升提。这样会缩小阴道开口,减小对外物的紧握力。小阴唇由于充血,厚度会增加两到三倍,迫使大阴唇离开阴道口更远,以使外物能够顺利进
入阴道。随着性刺激的持续增强,阴蒂会变长,变宽,并藏在阴唇下面,减少接受到的刺激。
2014-01-17 16:16:08
另外,血管充血时,阴道内会分泌阴液。大多数人认为阴液由阴道内的某一腺体分泌,但事实并非如此。女性性兴奋时,阴道组织充血,从而将液体挤入阴道内。即便未产生性兴
奋时,液体也会通过阴道壁缓缓渗入阴道内,保持阴道润泽,以防内壁粘连在一起。因此,阴道充血和阴液息息相关,均为性唤起的重要标志。
2014-01-17 16:16:23
当生殖器血管充血时,女性会感到骨盆区“胀满”“紧张”或“悸动”。身体开始燥热,精神特别亢奋。此刻,女性会产生箭在弦上不得不发的性冲动,就像皮肤瘙痒难忍,必须
抓一抓。这种自然的生理反应不仅让女性身心愉快,还能发出强烈的欲求信息,从而使性兴奋的体验更加恣意销魂。
2014-01-17 16:16:39
换句话说,女性精神上的性唤起并不取决于生理上的性唤起,所以,伟哥之类的催情药能使男性勃起,但对女性却束手无策,尽管男女生殖器组织相差无几,均由错综复杂的肌肉
(性肌)所环绕的微细血管网组成。当血管充血时,男性阴茎勃起,女性阴蒂等膨胀。为使血管充血,性肌首先要保持松弛的状态。伟哥、艾力达、犀利士等的药物作用原理就是
促使性肌保持长时间松弛,让血液有足够的时间流向血管。多项研究已证明,女性服用伟哥也能增加血管充血量。一些草药配方如麻黄碱、育亨宾碱加左型精氨酸–谷氨酸钠、银
杏叶提取物等也会对女性产生同样效果。
2014-01-17 16:20:50
当性兴奋时,女性如果感受到的是徐徐燃烧的火苗,那么男性则感受到的熊熊燃烧的烈焰。为什么会有如此大的区别?一种观点认为这是因为男性更为“亲近”或熟悉自己的生殖
器。言之有理,不论从生理构造还是从日常生活角度考虑。首先,从生理构造角度看,男性阴茎大而且毫无掩饰地裸露在外,尤其是在勃起时。其次,从日常生活角度看,男性阴
茎还兼具着排尿的功能,所以在很小的时候,男孩就学会了在上厕所时要用手接触并握住“小弟弟”。相反,女孩接受的教育则是,“不许碰”,好像那里是身上的危险地带。结
果,很多女性活了一辈子都不清楚自己的生理构造。
探索神秘的“G点”
2014-01-17 16:24:22
之前讲过,女性的性喜好千差万别,所以女性对进入自己身体的外物也有截然不同的兴趣,管它是阴茎、手指、舌头、窥镜、按摩器、仿真阳具还是其他什么东西。事实上,阴道
的神经末梢全部集中于阴道前壁靠近阴道口的部位。也就是说,该部位高度敏感,能够感受到最轻微的碰触。阴道内部也有敏感点,但需要较大力度才能起到刺激作用。这种生理
构造极为合理,如果高度敏感的神经末梢遍布整个阴道,那么性交过程将会苦不堪言,疼痛难忍。 因此,当外物插入阴道时,快感主要发生于阴道口的敏感地带。但随着刺激的
反复施加,该地带会变麻木,快感减弱,所以插入的那一刹那最销魂。因此,在房事过程中,可以间断性地对该部位给予刺激,不妨时不时将注意力转移到身体其他敏感地带,待
该部位恢复高度敏感后再施加刺激,从而让女性体验潮水般的快感。
2014-01-17 16:25:54
阴道内有两个敏感部位在受到压力时也会带来快感。一个是子宫颈,子宫颈近似圆锥体,连接阴道与子宫,上端与子宫体相连,下端深入阴道内部。虽然在子宫颈上面没有任何神
经末梢,但子宫颈却对压力或抽动高度敏感。可是子宫颈的快感因人而异,有的女性认为子宫颈受到反复戳刺时不舒服甚至疼痛,有的女性认为有节律的推动能够带来极为舒适愉
悦的感觉,还有其他女性认为这是奔向性高潮的必经之路。
2014-01-17 16:26:28
女性寻找阴道内G点的最好办法就是用手指,最好是两个或三个手指。然后要持续有力地刺激阴道内部,注意要朝着上方,即直指肚脐眼的方向。有的女性谈到一开始碰触G点时
有尿意,但是随着刺激的不断施加,尿意消失,随之而来的是排山倒海的快感。相比阴蒂高潮,G点高潮更加令人癫狂。但是对多数女性来讲,抵达G点高潮比较困难,特别是男
性阴茎一般无法准确击中女性的G点。背入式或男下女上的姿势更容易达到G点高潮。 也有女性曾谈到自己达到G点高潮时有射液现象。女性射液俗称阴道射液或潮吹,部分女
性在达到高潮时会从尿道排出一种液体,但不是单纯的尿液。有些性学家认为该液体由位于G点附近的斯基恩氏腺(又称尿道旁腺)分泌。但到目前为止,这种说法还未得到科学
界有力的证明。
何为性高潮
2014-01-17 19:05:44
女性性高潮是一种变化的、短暂的快感巅峰,过程中会出现各种知觉变化,此刻骨盆区阴道横纹肌会不自主地间歇式地收缩,并伴随有子宫和肛门的收缩,以及性唤起时的血管充
血(有时为局部)的肌肉会出现短暂性的僵硬,这种一系列生理变化会带来身心的满足感。
性爱巅峰的生理体验
2014-01-17 19:06:34
在高潮过后,男女体内的催乳素倍增,大约一小时后恢复到常态。人们一般认为催乳素是男性在高潮后进入“疲软期”的原因,疲软期就是指男性射精后阴茎疲软并无法再次勃起
的状态。疲软期的长短和年龄有很大关系,年龄越大,疲软期越长,也就是说需要较长时间才能再次勃起。但是催乳素对女性却毫无影响。所以,女性可以在性交中高潮迭起,后
浪推前浪,一浪高过一浪。不同于男性,女性可以达到马斯特和琼森教授所说的“高潮状态”——长达数分钟之久的高潮期。男女性高潮还有一点区别,就是男性在高度性唤起时
会进入“不可逆”阶段,此刻高潮就像是洪水猛兽一样不可遏止。但女性却截然相反,外界刺激一旦刹车,不管是阴蒂高潮还是阴道高潮都会戛然而止。情侣们一定要注意。
孑然一身品清闲,比翼双飞饮合欢
2014-01-17 19:10:05
和谐完美的性爱需要双方沟通。在房事过程中,可以用言语或手势指导对方,或者直接将对方的手等从“禁区”挪到“自由地带”。但很多时候女性不是难以启齿就是羞于表达。
2014-01-17 19:10:17
性爱交流,不论多么困难或尴尬,可以让人受益终生:
性高潮障碍
2014-01-17 19:12:10
临床心理医生以及精神科医生认为女性产生性高潮障碍主要受两个因素影响,一个是性刺激不足,另一个是注意力涣散。女性在床上经常神游四海,比如只想着取悦对方,忽略了
自己的感受,或者忙着摆魅惑的姿势,或者担心隔壁的孩子或父母听到,或者满脑子想的都是工作的问题,或者琢磨对方到底好不好,或者充满了罪恶感——所谓的“性爱杀手”
。还有就是由于宗教或者其他原因,女性的性教育极为禁锢:性交就是为了和丈夫一起传宗接代。所以,任何以其他目的进行的性交会让女性从心底涌起一股罪恶感。 社会文化
环境也起一定的作用。研究世界女性性行为的人类学家发现,如果社会鼓励女性像男性一样享受性爱,那么大部分女性都可抵达性高潮。例如,在南太平洋库克群岛最南端的曼加
阿岛上,人们认为女性在性交中最好达到2~3次的多重性高潮。而且不能给女性带来多重性高潮的男性在当地没有地位。(现在拉罗汤加航空每周有四个航班飞往曼加阿岛。)
与此相反,如果周围的人们普遍不重视或不知道女性性高潮,那么女性也就很难有性高潮。因为当人们不期望女性有性高潮时,女性不会主动学习也得不到相关的指导。和男性不
同,女性确实要下一番功夫才能学会如何攀登快感巅峰。
原始的诱惑
2014-01-17 19:15:03
如果一个男人能够在床上体贴呵护女人,费尽心思让她快乐,努力给她高潮,那么这个男人一定是“无私的爱人”。如果他在性爱中无私奉献,那么在其他方面也一定包容大度,
是一个可长相厮守的爱人,是疼爱孩子的父亲。所以说,选择“无私的爱人”,就等于选择了一个对自己和孩子都不离不弃、体贴入微的好男人。也许这就是所谓的爱情。
爱情是毒药
2014-01-18 11:01:55
在对这几位年轻人进行大脑扫描时,研究人员给他们看了恋人和好友的相片。结果发现,当看到恋人相片时,大脑中主管快乐、满足感觉的区域极为活跃,而主管伤心、恐惧、焦
虑等感觉的区域却十分抑制。事实上,此时大脑出现的变化很像吃了可卡因等兴奋剂。恋爱的感觉会抑制大脑中控制理性思维的区域,所以恋爱中的人经常“精神恍惚,魂不守舍
”。或者正如科研人员所说,当人们决定相爱时,就已经没有必要用理性去评判彼此。
永远像初恋
2014-01-18 11:03:03
在其他包办婚姻的一夫多妻制社会中,浪漫爱情虽然不算大逆不道,但有情人却常常被生生地拆散。在许多阿拉伯社会中,第一个妻子通常由长辈指定,但第二个妻子可由自己选
择。在非洲肯尼亚东南部的泰塔,当地女性都愿意当第二个或第三个妻子。第一次婚姻一般是出于父母之命,媒妁之言,往后的婚姻才是真爱的产物。所以,男性一般会比较宠第
二个或第三个妻子。
2014-01-18 11:04:13
除此之外,相关研究证明,男性更容易“一见钟情”,这可能是人类长期进化的结果。通常来讲,男性更容易被外表所迷惑,而女性需要气味、性格等多种信号才能爆发出爱的火
花。
2014-01-18 11:04:24
除此之外,男性似乎更不容易移情别恋。传统观点认为,男人总是喜新厌旧,容易移情别恋,而女人在爱中总是死心塌地,容易受到伤害。但一份从1972到1974年针对2
31对大学生情侣的跟踪调查却得出了相反的结论,并有力地驳斥了这种偏见。据该调查结果显示,女性更容易提出分手,而且很早就能预感到将要分手。因此在分手后,女方一
般认为恋情是慢慢死亡的,而男方通常认为恋情是突然终结的,简直是“晴天霹雳”。此外,回忆昔日恋情时,女性列举的矛盾或问题比较多,而男性却较少。
2014-01-18 11:04:36
事实也表明分手对于男性的伤害更大。当然,这要具体情况具体分析,不过总的来讲,男性表示更加寂寞、抑郁。
爱与性
2014-01-18 11:05:40
有许多受访女性表示她们发生关系不是为了得到爱,而是为了表达爱:
性就是用行动来表达爱。爱有很多种,不同的爱需要用不同的行动来表达。当我渴慕一个人的身体或心灵或身心时,我想我会选择用性来表达我的渴慕之情。
性浓情更浓
2014-01-22 14:40:30
正如很多女性想通过性来表达爱或得到爱一样,也有很多女性想通过性来增进彼此的感情。她们说,“渴望亲密无间”,“希望有更深层的交流”,“觉得离不开他”,“在性爱
中增进感情”,“想要融为一体”,等等。其实这几个回答都表达了同一个意思:希望通过性爱获得或增强彼此的爱意。我们的调查结果再一次颠覆了传统观点,即不论是男大学
生还是女大学生,他们都希望通过性爱增进彼此的感情。
2014-01-22 14:41:54
据梅斯顿实验室所做的一项调查,有四种行为或信号可以激发女人的情欲。前三种行动或信号都与性吸引和性唤起有关。首先是明确的色情信号,包括观看或者阅读色情故事,与
情人“打情骂俏”,或者感觉欲火难耐,比如下体变湿等。其次是身份地位,包括看见有名有权的人或者与他们聊天。再次是“暧昧”信号,包括紧贴着身体跳舞,共进特别晚餐
,在一起欢笑,等等。最后就是感情,感情可以点燃身体的欲望,让女人最终交付身体。
当吻不再是简单的吻
2014-01-22 14:42:35
一项研究发现,接吻后,人体内的应激激素皮质醇也就是压力荷尔蒙会减少。所以说,恋人可以吻走压力和忧愁。亲吻还可以传递健康信息,一般有疾病或身体不好的人有口臭。
另外,接吻对女性来讲是试金石。通过一个吻,女性可以决定是否要进行下一步,换句话说,是否要把自己的身体交付给对方,达到灵与肉的完美结合。这种试金石的作用对女性
更为重要。据一项调查结果显示,53%的男性接受不接吻就直接上床,相比之下,只有15%的女性说可以考虑不接吻就直接上床。接吻不仅可以传递健康信息,还可以让人心
潮澎湃,兴致高昂,让爱情更加甜蜜。
爱与情
2014-01-22 14:49:38
毫无疑问,女性更无法容忍自己的男友精神出轨,也就是对别人投入感情。这非常符合进化论的道理。在女性眼里,自己的男人和另外一个女人发生关系并不代表着他是认真的,
也许只是一时的性冲动。如果他和另外一个女人有了感情,那么再次发生性关系是在所难免的。如果他和另外一个女人不仅发生了性关系而且还发生了感情,那么他很有可能将时
间、精力、金钱都投入到另外一个女人身上——这就对自己构成了彻彻底底的威胁。
猎获与掠夺
2014-01-22 14:56:51
在人类漫长的进化过程中,那些最终能够赢得优质男性的女性会占有多种优势——良好的基因,健康的后代,丰富的生存资源,较高的社会地位,等等。对于我们的祖先来讲,这
些优势就意味着成功地繁衍后代,直接地来讲就是拥有更多的儿女,间接地来讲就是拥有更多的孙辈,因为他们身体健壮,更具性魅力。所以说每个女人背后都隐藏着无数成功繁
衍的母亲。
2014-01-22 14:57:18
本章探讨女性是如何在情人、爱人的争夺中战胜情敌的。这里我们具体地分析“挖墙脚”的情况,就是夺人所爱,当第三者。首先分析女性通常使用的两大策略:增加自己的性魅
力,诋毁情敌的性魅力。
魅惑
2014-01-22 15:01:57
按照性选择的规律,择偶偏好一般是求偶竞争的内容。换句话说,男性之间的竞争反映女性的择偶偏好,女性之间的竞争反映男性的择偶偏好。所以,男性往往追逐的是地位和财
富,并大秀自己的幽默感、睿智、健美的肌肉等,因为这些都是女性喜欢的;同样,女性也千方百计获得男性认为性感的特质,其中最重要的就是外表。
排卵期的节奏性竞争
2014-01-22 15:03:09
有趣的是女性的打扮程度会随着排卵周期而变化——至少对于那些未使用口服避孕药的女性来说是如此。进化心理学家克里斯蒂娜·杜兰特和同事做了一项实验,要求参与女性每
周来两次实验室——一次是在排卵期,一次是在非排卵期。每次都给参与女性拍全身照片,并要求她们画出自己会穿什么衣服去参加社交活动。结果发现,与其他女性相比,处于
排卵期的妇女当天穿着比较性感,笔下画出的衣服也比较暴露。在性爱中比较随意的女性——说自己性开放并且拥有多个性伴侣——打扮得更加暴露性感。杜兰特及同事称这种倾
向表明处于排卵期的女性想要压倒竞争对手的心理更加强烈。
2014-01-22 15:03:24
从进化论角度看,女性在接近排卵期时最具择偶竞争力。在这个受孕阶段做出正确的恋爱决定至关重要,而且一旦选择失误,就要付出惨重的代价。这关系到繁衍以及生存的问题
。此时的女性若能在求偶大战中打败竞争对手并最终夺得优秀的配偶,那么产生的进化意义将是巨大的。
落得淫妇的名声
2014-01-22 15:08:22
通过毁坏竞争对手的名声可达到具体的目的:让其他女人不愿和她做朋友,让男人不愿和她长期交往。在配偶竞争中,抹黑他人同时抬高自己是有好处的,因为这可以缩小竞争对
手的择偶范围,扩大自己的择偶范围——不过需要注意运用语言艺术。比如,巴斯实验室发现其中一个语言策略就是说话时显得尽量客观,例如她们会说“我听说她和整个足球队
的人都睡过了”,或者“大家都说她得了疱疹”。
2014-01-22 15:08:27
你可能会想在这个性别平等观念深入人心的时代,不应该再用双重标准来评判男女的性行为,男人可以毫无顾忌地到处乱搞,那么女人也应该可以滥交而不受任何指责。事实上,
这是不可能的。因为双重标准不仅没有消失,而且似乎女性更爱强调女性的贞操观念。进化论心理学家安妮·坎贝尔做过多项有关女性名声的研究,她说:“这种道德观念的最坚
定支持者往往是女性自己。”为了保护自己的名声,女性往往孤立甚至公开排斥那些被骂成“贱货”和“淫妇”的同性,她们不想被“牵连”。一位科学家谈道:“对朋友坦言自
己的性行为或性感受是最危险的。很少有女性对朋友谈自己的性欲望或性行为,因为她们害怕朋友在背地里说自己的坏话——到处散布‘她是荡妇’的谣言。这种背叛可以毁掉女
性的脸面,但男性却没有这种担忧。”女人一旦惹上这种作风不良的名声,就算跳进黄河也洗不清,最终会影响到女人的终身大事。
复仇
2014-01-22 15:13:04
在复仇心理的驱使下,很多女性选择和前任男友的好朋友发生性行为,这种高发频率表明复仇能带给人极大的快感——这也给了窃偶者可乘之机。性竞争的形式多种多样,比如同
其他女人争夺优秀的男人,努力留住身边的爱人,敌视影视媒体中的美女,防备阴险的入侵者,等等。性竞争的现象有着漫长的历史,因此在进化过程中,女性发展了强大的自我
防御体系。其中一种自我防御方法表现为人类可怕的心态——嫉妒
嫉妒之心缘何而起
2014-01-22 15:19:26
跨文化研究发现不忠行为在某些情况下最有可能被认为具有威胁性:1. 如果婚姻是陪伴、地位或生存所需;2. 如果婚姻之外很难找到性伴侣;3.
如果财产是私人所属;4. 如果生儿育女是头等大事
暴力下的守贞
2014-01-22 15:21:13
嫉妒的另一表现就是试图控制对方的行为。古往今来,一向是男性控制女性的行为。在中世纪的时候,贵族男性用贞操带缚住妻子,以保证她们的贞洁。现在,很多国家实行所谓
的女性割礼或者女性生殖器切除术。据有关专家估计,每年大约有8000万到1.2亿女性在孩童期或者青春期接受不同程度的生殖器切除术。目前,女性割礼的习俗仍在29
个国家流行,多数在非洲,但也存在于印度尼西亚和中东一些国家。女性生殖器切除术主要和伊斯兰教的传统有关,虽然《古兰经》中并未提及女性割礼,但是后期的伊斯兰经文
中常常强调女性割礼,并赋予其一种神圣的宗教意义。
2014-01-22 15:23:46
女性生殖器切除术主要有三种。最简单的一种称为“苏那”(苏那是阿拉伯文,意为惯例或常道),即去除阴蒂的包皮。第二种叫“阴蒂切除”,即将阴蒂的一部分或全部,小阴
唇的一部分或全部切除。更为极端的一种是“阴部扣锁法”(在苏丹最流行),即为禁止性交而封闭阴部:不仅阴蒂和小阴唇全部被切除,大阴唇的部分也会被切除,外阴两侧用
洋槐刺穿在一起或用肠线缝合,只留下一个小小的间隙以便尿与经血流出。当女孩成婚之后并准备开始性生活之时,阴部要被剖开,而且性交之后通常又被马上缝起来。
2014-01-22 15:23:58
在流行女性割礼的文化中,人们认为阴蒂未被切除的女性是肮脏的,会对与其发生性关系的男性造成健康隐患。但是,这一习俗的根本目的是减少女性的性欲,压抑女性的性行为
,尤其是婚前和婚外性行为。切除阴蒂会减少女性的性交快感,而阴部扣锁法让女性无法性交,甚至任何碰触都变得不可忍受。在实行割礼的地区,未接受割礼的女孩是嫁不出去
的。
让对方吃醋
2014-01-22 15:24:42
女性最惯用的让对方吃醋的办法就是随意地提起其他男人如何挑逗她,或者故意用身体触碰她,或者要了她的电话号码,等等。还有一种手段就是在伴侣面前和其他男人调情。也
有的人爱跟伴侣谈起自己的前任。每当这个时候,男性(和女性)往往努力控制自己的情绪。人们隐藏自己的醋意,害怕暴露自己的真实情感,不想让别人知道自己内心的不安。
但是心底里已经汹涌澎湃了。
采取极端手段
2014-01-22 15:25:30
和他人发生关系的这种策略一般都会适得其反,这是因为在长久的恋情中,人们一般期望对方能够做到性忠诚。
2014-01-22 15:25:51
调情可以很好地让对方认识到自己的魅力从而加倍地疼爱自己,但是当女人通过上床来引起对方的注意时,往往会遭受失败。
移情别恋
2014-01-22 15:27:32
在很多人看来,私通是道德败坏的行为,而且性不忠会对个人以及两个人的感情造成极大的伤害。一次的不忠行为可以造成伴侣心灵的巨大创伤,伴侣会因此感到嫉妒、伤心、沮
丧、愤怒、羞愧等。性不忠也是家庭暴力的主要原因之一,有的时候甚至可以成为杀人动机。人类学家劳拉·贝兹格所做的一项涉及89个文化的研究发现,性不忠是婚姻破裂的
第二大原因,第一大原因是不孕不育。
性欲不协调
2014-01-22 21:56:05
临床医生可能会建议大家找一个与自己“性匹配”的伴侣。如果两个人都愿意隔几个月过一次性生活,那么他们的性需求就是匹配的,也不大可能会为此搞得关系紧张。事实上,
性欲缺乏症——也就是性冷淡——只有在引发抑郁情绪时才可确诊。如果一方的性欲总是比另一方旺盛,那么很有可能会出现矛盾、妥协等。
2014-01-22 21:56:11
在热恋的时候,情侣们会误以为两个人是天作之合。在这个阶段,陷入爱河而无法自拔的恋人们茶饭不思,心里面只想着心爱的人,对对方的渴望极其强烈,而且会为彼此交融而
激动万分。结果就是“真实的”性欲被止不住的欲望所掩盖。数周或者数月后,人们最好进入一个比较镇定的“恋爱”期,更加关注彼此的交流与投入。毕竟,长达数月甚或数年
的热恋无助于解决生活中的许多问题,更不要说生存问题了。
扫兴
2014-01-22 21:57:08
性激素主要分为三类:孕激素、雌激素(主要有雌二醇、雌三醇、雌酚等)、雄激素(睾丸激素是最重要的雄激素)。孕激素在怀孕过程中扮演着非常重要的角色,因为孕激素负
责在子宫内为受精卵“筑巢”。科学研究并未发现孕激素和女性的性欲之间有密切联系,但是孕激素过多可导致经前综合征——常见的性爱杀手。 雌激素和睾丸激素却对女性的
性趣至关重要。雌激素除了具有保护女性骨骼和心脏的作用外(可能还有助于女性保持记忆力),还担负着当女性性唤起时润滑阴道的作用。同时,雌激素还能促使女性体态丰盈
。如果没有雌激素的作用,性交以及对乳头、阴蒂等性感带的刺激都会造成疼痛。
怀孕引发的紊乱
2014-01-22 22:11:06
怀孕时荷尔蒙会发生一系列变化。雌激素和孕激素都不会像以前那样时高时低,而是同时急剧增加,这有利于女性产后产奶,并且增加子宫内膜的厚度以防流产。雌激素增加可能
会使女性性欲旺盛,但是孕激素增加可能会使女性感到疲劳,动不动发脾气,想都不愿想性事。
勉强自己做爱是好事吗
2014-01-22 22:37:45
当女性处于“性爱中立”状态时最容易被挑起性欲,中立就是指没有想要做爱但也不厌恶做爱的状态。能否成功挑起“中立”女性的性欲要看几方面的因素,包括伴侣的前戏技巧
、女性对性刺激的敏感度、女性在性唤起时的身心愉悦程度等。其中有一些因素是女性——尤其是那些想积累性经验的女性——可以控制的。
处女情结
2014-01-22 22:41:32
人们一直大肆渲染贞操的重要性,但是早在18世纪的时候医生就提出长期没有性生活对人体有害,也就是说老处女容易出现健康问题。身体长时间“封闭”的处女容易患萎黄病
,其临床症状为皮肤变成偏绿的黄色,患者多为年轻女性。另外,也可能会出现“子宫窒息”的状况,即子宫在体内来回移动,造成排尿异常。在古代,假如未婚女性患上了此类
疾病,而一时之间又无法找到夫婿,那么该怎么办呢?中世纪时代的医生开出的药方是找信任的接生婆帮助患病女子手淫。不过患者听到这种治疗方法恐怕只能横眉怒目了,即便
在当今性开放的社会,人们也无法接受。
性生活添点“新鲜”
2014-01-23 18:50:03
毫无疑问,女性对男性的欲望存在着巨大的个体差异。女性是否能够做到忠诚取决于多方面的因素。如果女性性欲较强,而伴侣又无法满足自己,那么出轨的可能性较大。如果女
性经常被他人诱惑,那么可能会禁不住诱惑而偷情。如果女性对两个人的感情感到失落,那么也可能会陷入婚外情中。此外,生活状态也是一个因素。比如,一个刚刚开始探索性
爱奥秘的女性或者刚刚结束20年婚姻的女性可能更愿意享受自由而不愿意守着一个人度日。但是反过来,一个经历过多次感情的女性可能更愿意找一个相爱的人稳定下来。
生性豪放
2014-01-23 18:50:15
女性的个性也决定着她是否会追求多个性伴侣。在一项涉及52个国家(北美、南美、西欧、东欧、南欧、中东、非洲、大洋洲、南亚、东南亚、东亚)16288名参与者的调
查中,心理学家大卫·施密特发现拥有多个性伴侣的女性一般有两个性格特点:外向和冲动。性格外向的人活泼开朗,交友广泛,善于交际。冲动多指做事鲁莽,不考虑后果,感
情特别强烈,理性控制很薄弱。该调查发现性格越是外向和冲动的女性越爱追求新奇的性爱。
2014-01-23 18:52:19
同样地,巴斯进化心理学实验室对107对已婚夫妇所做的一项调查发现,性格冲动的人容易不忠,但是自恋的人更容易移情别恋,自恋的人自我陶醉、夸大自己、傲慢张扬,对
他人的疾苦非常冷漠或不闻不问。梅斯顿实验室对18岁到47岁之间的121名女性做了一项调查,发现完美主义者更容易出轨或者追求刺激新鲜的性爱。完美主义者对自己和
他人都抱有不现实的期望:完美主义者事事追求完美,从而对自己和他人都非常苛刻。调查发现越是追求完美的女性性伴侣就越多,也越容易出轨。完美主义者对性伴侣的床上表
现有着过高的或者不可实现的要求,结果总是陷入沮丧和不满的心情,最终会选择他人来满足自己的性需求。
狭义和广义的性爱价值
2014-01-23 18:54:09
在以打猎采集为生的传统社会中,男人以食物换取性爱。比如生活在秘鲁的萨拉纳瓦人,“男人通过狩猎来展现自己的男子气概,需要用猎物来打动女人,也就是用肉换取性爱”
。研究萨拉纳瓦人的人类学家珍妮特·西斯金德表示对此无法理解,因为“没有任何证据可以证明女性没有男性那么喜欢性爱或者比男性更加喜欢吃肉”。
金蛋
2014-01-23 18:54:56
男性还有一个心理特点,就是性爱认知偏差,即过分解读女性模棱两可的信号,也可以说容易自作多情。在第五章中我们谈嫉妒心理时提到过,一个简单的微笑就足以令男人动心
思,其实她的微笑也许只是出于友好或者礼貌。其他容易引起男性误会的信号包括碰一下手臂、站得近、时间稍长一点的对视等。结果,女性可以利用男性的这种心理来满足自己
的欲望,这叫作“诱饵调包”策略,就是让男性误以为自己感兴趣,诱使男性付出各种努力,一旦达到目的便撒手走人。
以性换物
2014-01-23 19:01:12
金钱不是诱使女性和他人发生性关系的唯一因素,女性也会为工作、加薪、升职目的而和上司发生关系。这种现象叫作“潜规则”,尤指女演员为了赢得角色而做的肉体交易。玛
丽莲·梦露承认自己为了打入好莱坞演艺圈、为了赢得主角而和他人发生过性关系,当然这些不堪回首的经历给她造成了巨大的心灵创伤。据说和试镜导演发生关系后,她洗澡洗
了几个小时,希望把那“皱巴巴的老男人”的污秽冲干净。好莱坞的“潜规则”现象仍在盛行,奥斯卡获得者朱莉娅·菲利普的书《你永远不会再在这个城市吃午餐》对此有详细
记录。“潜规则”的现象不仅美国有,其他国家也有。印度电视台的“全印度通缉”节目曾爆出丑闻,几个宝莱坞电影人被指责向年轻女演员索取性交易。2006年,中国女演
员张钰公开了20个偷拍的性爱录像,揭露影视圈性交易黑幕。
炮友关系,求欢电话,勾勾搭搭
2014-01-23 19:01:53
传统上,友谊是一种来自双向(或交互)关系的情感,朋友间互相信任、互相忠诚、互相尊重。但是现代社会又给友谊增添了性爱的成分,在大学校园以及城市年轻人中这种现象
尤为普遍。研究发现大约60%的美国大学生曾和朋友有过炮友关系,大约36%的大学生有“炮友”。事实上,当女性想寻欢作乐时,一般都会找朋友(63%)而不是陌生人
(37%)。
身材、爱护、权力、服从
2014-01-23 19:03:54
“自尊”是心理学词汇,指自我肯定,自我认许。有自尊的人肯定自身的价值、肯定自身的优点、不向别人卑躬屈膝、不允许别人歧视、感到自豪、有成就感、尊重自我。自尊始
于羞耻心,自尊自爱的人行动能力强,比如能够在一定压力下完成工作任务;自尊自爱的人有成熟的心理,比如能够勇于面对失败;自尊自爱的人关注自己的健康,比如主动避孕
、自己检查乳房、及时调节焦虑和抑郁情绪。
跟芭比说再见
2014-01-23 19:04:21
对自己的身材缺乏自信的女性不仅性欲低下而且性反应迟钝。她们性冷淡,性唤起困难,很难抵达性高潮。梅斯顿性心理生理学实验室做了一项实验,85名女大学生先后来到实
验室填写性生活和身材方面的两份问卷调查,身材方面的问卷调查询问她们的体重以及对自己身材的满意程度。然后,她们会独自在房间内阅读色情故事,并写出自己“兴奋”的
程度。相比对自己身材不满的女性,对自己身材较为满意的女性更加“兴奋”。在现实生活中,对自己身材不满的女性性欲较低。
缺乏关爱
2014-01-23 19:08:04
有的人生性活泼,乐天无忧,但是心理研究发现童年经历影响个人的心理素质和性格,成长过程中儿童需要来自父母的关爱和支持。例如,一项对16749名青少年所做的调查
发现,受到父母悉心关照的孩子更加自信。让孩子感受到父母的爱非常关键——父母照顾孩子,警惕孩子的安危,孩子遇到困难时第一时间伸出援助之手。也许正是有了父母的保
护,孩子才敢于探索和冒险,并最终养成健全的人格。从小缺乏父母关爱的女性往往比较自卑,为了得到父母从未给予的关注或者温暖,她们不惜以身体作为代价。
学会放手
2014-01-23 19:09:22
有的人通过外在的因素,比如财富和社会地位,来评判自我价值。而有的人则通过爱情来评判自我价值。因为不是所有的爱情都能够天长地久,所以随着爱情的得与失,心理会出
现剧烈的浮动。如果一个女人认为男人的爱情就是自己的全部,那么男人的离去会将她推向崩溃的边缘,会剥夺她人生的全部意义。尽管有的人不这么极端,但是失去爱情终归是
一件令人悲伤的事情。 爱情受挫后,大家都会经历一段伤心痛苦的日子,在这期间,有的人找朋友疗伤,有的人借酒浇愁,有的人痴迷巧克力,而有的人则放纵自己。一位受访
女性写道:“忘记某人的最好方式就是遇见某人!”不止一位受访女性谈到自己如何利用其他男人来忘记失恋的痛苦。每个人都有自己的故事。
行使性权力
2014-01-23 19:10:45
在许多言情小说中都有这样的情节,不顾女主人公的拳打脚踢,男主人公用武力将其“制服”。很多心理学家指出,这是因为这种强迫的性爱令女性感到兴奋,这反映了一种病态
心理或者女性服从男性的模式化观念。然而,科学研究给出了另一种解释。心理学家帕特丽夏·霍利曾对约900名女性做了抽样调查,研究女性是否有过在暴力下屈服于男性的
性幻想。研究发现,有这种幻想的女性既不唯唯诺诺也不病态,相反,她们往往是强势、独立、自信的女性。而现实中温柔委婉的女性少有这种被暴力屈服的性幻想。霍利总结说
,这种被暴力屈服的性幻想反映的是女性权力而不是懦弱的性格,因为幻想中的男性为她们着魔,为她们失去理智,完全被她们的魅力所折服。
性屈服
2014-01-23 19:11:43
一种合理的解释就是,既然男性不惜用暴力来强迫自己,那么证明他对自己欲罢不能,从而有一种驾驭男性的权力感。我们经过研究发现,女性的两种性爱动机——“我想被他控
制”和“我想控制他”相互联系在一起。有数据证明这两种原因相辅相成,这意味着屈从是另一种形式的控制。
偏色
2014-01-23 19:13:27
事实上,巴斯进化心理学实验室指出,为了骗女人上床,男性最常使用的伎俩就是欺骗对方的感情。在一项调查中,我们请240名女性和239名男性讲一讲自己被异性欺骗的
情况。结果发现男性欺骗女性的方法包括: ·隐藏同另外一个女人的正式恋爱关系(9%); ·说谎说自己不喜欢另外一个女人(26%);
·隐藏自己对另外一个女人的感情(25%); ·夸大自己的事业心(21%); ·假装自己非常善良体贴(42%); ·误导她相信自己有多么喜欢她(36%);
·隐藏自己同另外一个女人调情的事实(40%); ·为了骗对方上床,假装自己非常喜欢对方(29%); ·误导她相信自己会与她长相厮守(28%)。
以上给出的数据很有可能比实际数据少许多。因为另一项调查发现,在112名男性中,有71%的人承认自己曾为了和对方上床而夸大自己的真实感情。
性生活的益处
2014-01-23 19:19:42
现在,我们已经讨论过女性主要的性爱动机:为了爱与被爱,为了加深感情,为了感受甜蜜的爱情,为了享受床笫之欢。我们介绍了女性如何利用性爱达到自己的目的——获得财
富、报复、吸引或者留住伴侣。我们也分析了女性发生非自愿性爱的原因:自己的责任感或者被对方施压、欺骗、殴打。另外,我们也提到女性的其他性爱动机:建立自信、积累
经验、摆脱处女之身、寻求新奇刺激。其实性爱不论对女性的心理健康还是生理健康都有着众多益处。
治疗痛经
2014-01-23 19:20:18
性生活可以治疗痛经。未绝经的妇女,每个月子宫内膜都会分泌前列腺素。前列腺素引起子宮平滑肌的收缩,月经周期开始的时候,可以帮助经血的排出,但是同时也会引发痛经
。性生活可以影响前列腺素对身体的作用,所以有的受访女性谈到自己通过做爱来缓解痛经
2014-01-23 19:20:32
从某种角度来讲,性生活就像是阴道的清洁工。经血中带有的子宫内膜组织有时候会回流到骨盆区,这种现象叫作“经血逆流”,容易造成子宫内膜异位症,而过性生活可将残留
的经血逼出阴道,从而减少患病概率。性高潮时,随着子宫收缩,残留的经血被逼出子宫,从而降低子宫内膜异位症的患病率。另外,耶鲁大学医学院的该项研究发现,经期使用
卫生巾的女性患子宫内膜异位症的概率是用卫生棉棒女性的两倍。这表明,卫生棉棒能够更有效地清除残留在体内的经血。
催眠
2014-01-23 19:33:22
长期抑郁会对身体造成各种各样的伤害。睡眠问题困扰着2000万美国人——女性是男性的两倍。时不时会失眠的人更多,因为在激动或者抑郁的时候,大家往往会喝大量的咖
啡或者酒。建议睡眠不规律的人:不要喝咖啡、抽烟、喝酒;晚饭不要吃太多;只有在睡觉的时候上床;经常锻炼身体;卧室保持安静、黑暗、凉爽。
许多受访女性的回答证明性生活有助于睡眠
调节情绪的灵丹妙药
2014-01-23 21:31:34
在某些方面,自慰确实比有伴侣的性爱更好,但是纽约州立大学奥尔巴尼分校的心理学家戈登·盖洛普指出,女性和异性伴侣做爱有一个特别的益处。在该项调查中,研究者要求
293名女大学生填写一份有关抑郁症的表格,然后回答一份调查问卷,问题包括:多久过一次性生活?已经多久没有过性生活了?在采用什么样的避孕措施?结果发现,不使用
避孕套的女性(可能在用口服避孕药)患抑郁症的比例低于经常使用避孕套的女性,而且比没有性生活的女性更加快乐。最令人吃惊的是,13%的使用避孕套的女性曾试图自杀
,而不使用避孕套的女性中只有5%的人曾试图自杀。
“1”是世界上最孤独的数字
2014-01-23 21:32:16
孤独是导致抑郁症的另一个原因。当然,每个人的性格不同,有的人生性活泼,喜欢在人群中周旋,而有的人生性腼腆少语,不喜欢与人交往。但是一定程度的社交是必要的或者
说是必需的,没有人际交往的人容易感到孤单寂寞。多数异性恋女性在晚年都会陷入孤单寂寞中,因为女性一般会嫁给比自己年长的男性,加之男性寿命又比女性短,所以到晚年
时女性往往面临着独守空房的危险,而且总体上来讲,老年女性人口比老年男性人口多,因此她们也很难找到合适的伴侣度过余生。
结语
2014-01-23 21:36:18
女性的性爱动机是人类动机心理学中最奇妙、最复杂、最捉摸不透的问题。在本书中,我们探讨了各种各样的动机——从疯狂的绝望到狂热的爱情,从保护伴侣自尊的慷慨无私到
刻意复仇的自私自利,从探索的欣喜到阴暗的欺诈,从治疗头痛的俗不可耐到接近上帝的高超境界。 为了简明扼要地说明问题,本书将每个性爱动机都独立开来谈论,但这里要
着重强调的是女性的性爱动机是复杂多面的。有的女人可能既想着在朋友面前威风一下又想着探寻性爱的奥秘。有的可能既想寻觅新的伴侣又对现任伴侣不满。有的可能既想着缓
解自己的压力又想着保护爱人的自尊,又想着拉近彼此间的距离。
* * *
多看笔记 来自多看阅读 for Kindle
duokanbookid:970b799717444699b1121f9a10315afb
|
C#
|
UTF-8
| 1,829
| 2.984375
| 3
|
[] |
no_license
|
namespace SourceInclude
{
using System;
using System.IO;
// Prints out the runtime information to stdout (the specified text writer).
// Include this in your project as source.
public static class RuntimeConfiguration
{
public static void PrintRunConfig(TextWriter stdout)
{
const string configuration =
#if DEBUG
"Debug";
#else
"Release";
#endif
const string platform =
#if PlatformAnyCPU
"AnyCPU";
#else
#if Platform86
"x86";
#else
#if Platform64
"x64";
#else
"WARNING: Undefined: Define PlatformAnyCPU, Platform86, or Platform64 compile-time constants in project.";
#endif
#endif
#endif
stdout.WriteLine("========= Running on ===========");
var vars = new []
{
"PROCESSOR_ARCHITECTURE",
"PROCESSOR_IDENTIFIER",
"PROCESSOR_LEVEL",
"PROCESSOR_REVISION",
"NUMBER_OF_PROCESSORS",
"FrameworkVersion",
"FrameworkVersion32",
};
foreach (var @var in vars)
{
stdout.WriteLine("\t{0}: {1}", @var, Environment.GetEnvironmentVariable(@var));
}
stdout.WriteLine();
stdout.WriteLine("========= Compiled as ===========");
stdout.WriteLine("\tConfiguration: {0}", configuration);
stdout.WriteLine("\tPlatform: {0}", platform);
stdout.WriteLine("================================");
stdout.WriteLine();
}
}
}
|
Python
|
UTF-8
| 4,586
| 3.140625
| 3
|
[] |
no_license
|
def deactivate(text, tag, skipped=False):
r"""
Deactivates ``tag`` in ``text``.
.. container:: example
Writes (active) tag into LilyPond input:
>>> staff = abjad.Staff("c'4 d' e' f'")
>>> markup = abjad.Markup('Allegro').with_color('red')
>>> abjad.attach(
... markup,
... staff[0],
... tag='RED_MARKUP',
... )
>>> text = format(staff, 'lilypond')
>>> text = abjad.LilyPondFormatManager.left_shift_tags(text)
>>> print(text)
\new Staff {
c'4
- \markup { %! RED_MARKUP
\with-color %! RED_MARKUP
#red %! RED_MARKUP
Allegro %! RED_MARKUP
} %! RED_MARKUP
d'4
e'4
f'4
}
>>> abjad.show(staff) # doctest: +SKIP
Deactivates tag:
>>> text = format(staff, 'lilypond')
>>> text, count = abjad.deactivate(text, 'RED_MARKUP')
>>> print(text)
\new Staff {
c'4
%%% - \markup { %! RED_MARKUP
%%% \with-color %! RED_MARKUP
%%% #red %! RED_MARKUP
%%% Allegro %! RED_MARKUP
%%% } %! RED_MARKUP
d'4
e'4
f'4
}
>>> lines = [_.strip('\n') for _ in text.split('\n')]
>>> lilypond_file = abjad.LilyPondFile.new(lines)
>>> abjad.show(lilypond_file) # doctest: +SKIP
Activates tag again:
>>> text, count = abjad.activate(text, 'RED_MARKUP')
>>> print(text)
\new Staff {
c'4
- \markup { %! RED_MARKUP
\with-color %! RED_MARKUP
#red %! RED_MARKUP
Allegro %! RED_MARKUP
} %! RED_MARKUP
d'4
e'4
f'4
}
>>> lines = [_.strip('\n') for _ in text.split('\n')]
>>> lilypond_file = abjad.LilyPondFile.new(lines)
>>> abjad.show(lilypond_file) # doctest: +SKIP
Deactivates tag again:
>>> text, count = abjad.deactivate(text, 'RED_MARKUP')
>>> print(text)
\new Staff {
c'4
%%% - \markup { %! RED_MARKUP
%%% \with-color %! RED_MARKUP
%%% #red %! RED_MARKUP
%%% Allegro %! RED_MARKUP
%%% } %! RED_MARKUP
d'4
e'4
f'4
}
>>> lines = [_.strip('\n') for _ in text.split('\n')]
>>> lilypond_file = abjad.LilyPondFile.new(lines)
>>> abjad.show(lilypond_file) # doctest: +SKIP
Tags can toggle indefinitely.
Returns text, count pair.
Count gives number of deactivated tags.
"""
import abjad
assert isinstance(tag, str) or callable(tag), repr(tag)
lines, count, skipped_count = [], 0, 0
treated_last_line, last_index = False, None
found_already_deactivated_on_last_line = False
text_lines = text.split('\n')
text_lines = [_ + '\n' for _ in text_lines[:-1]] + text_lines[-1:]
lines = []
for line in text_lines:
first_nonwhitespace_index = len(line) - len(line.lstrip())
index = first_nonwhitespace_index
if not abjad.Line(line).match(tag):
lines.append(line)
treated_last_line, last_index = False, None
found_already_deactivated_on_last_line = False
continue
if line[index] != '%':
if last_index is None:
last_index = index
if ' %@%' in line:
prefix = '%@% '
line = line.replace(' %@%', '')
else:
prefix = '%%% '
target = line[last_index-4:last_index]
assert target == ' ', repr((line, target, index, tag))
characters = list(line)
characters[last_index-4:last_index] = list(prefix)
line = ''.join(characters)
if not treated_last_line:
count += 1
treated_last_line = True
found_already_deactivated_on_last_line = False
else:
if not found_already_deactivated_on_last_line:
skipped_count += 1
found_already_deactivated_on_last_line = True
treated_last_line = False
lines.append(line)
text = ''.join(lines)
if skipped is True:
return text, count, skipped_count
else:
return text, count
|
C++
|
UTF-8
| 1,713
| 2.984375
| 3
|
[] |
no_license
|
#include<iostream>
using namespace std;
int gotResult = 0;
long largeArea = 0;
void calcLargestArea(const int m,const int n,const float priceArray[][n],int A,int B,int C,int D,const float budget){
long currentArea = (B - A) * (D - C);
if(gotResult){
if(currentArea <= largeArea){
return;
}
}
float priceOfArea = 0;
for(int u = A; u<=B; u++){
for(int v = C; v <=D ; v++){
priceOfArea += priceArray[u][v];
}
}
if(priceOfArea <= budget){
gotResult = 1;
largeArea = currentArea;
return;
}
if(A+1<=B)
calcLargestArea(m,n,priceArray,A+1,B,C,D);
if(B-1>=A)
calcLargestArea(m,n,priceArray,A,B-1,C,D);
if(C+1<=D)
calcLargestArea(m,n,priceArray,A,B,C+1,D);
if(D-1>=C)
calcLargestArea(m,n,priceArray,A,B,C,D-1);
}
int main(){
int testCases;
long results[testCases] = {0};
cin>>testCases;
for(int k=0;k<testCases;k++){
int m=0;
int n=0;
cin>>m>>n;
float c = 0;
cin>>c;
float priceOfEachCell[m][n] = {0};
int l = 0;
cin>>l;
for(int u=0;u<l;u++){
int x,y,l,w,p;
cin>>x>>y>>l>>w>>p;
float pricePerCell = p / (w * l);
for(int li = x ; li < x + l; li++){
for(int wi = y; wi < y + w; wi++){
priceOfEachCell[li][wi] += pricePerCell;
}
}
}
calcLargestArea(m,n,priceOfEachCell,0,m-1,0,n-1);
results[k] = largeArea;
largeArea = 0;
gotResult = 0;
}
for(int b=0;b<testCases;b++){
cout<<"Case "<<b<<": "<<results[b];
}
return 0;
}
|
Java
|
UTF-8
| 3,878
| 3.015625
| 3
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Vista;
import Controlador.ClienteControlador;
import Controlador.FacturaControlador;
import Modelo.Cliente;
import java.util.Scanner;
/**
*
* @author GAMER I7 10TH GEN
*/
public class ClienteVista {
private Scanner teclado;
private ClienteControlador clienteControlador;
private FacturaControlador facturaControlador;
public ClienteVista (FacturaControlador facturaControlador){
this.teclado=new Scanner(System.in);
this.clienteControlador=new ClienteControlador();
this.facturaControlador= facturaControlador;
}
public void menu(){
int opcion=0;
do{
System.out.println("\nAdministración de Clientes");
System.out.println("1. Crear");
System.out.println("2. Actualizar");
System.out.println("3. Buscar/Leer");
System.out.println("4. Eliminar");
System.out.println("5. Listar/Imprimir");
System.out.println("6. Salir");
opcion=teclado.nextInt();
switch(opcion){
case 1:
this.crear();
break;
case 2:
this.actualizar();
break;
case 3:
this.buscar();
break;
case 4:
this.eliminar();
break;
case 5:
System.out.println("Listado de clientes: ");
clienteControlador.imprimir();
break;
}
}while(opcion<6);
}
public void crear(){
System.out.println("INGRESE LOS DATOS QUE SE REQUIERAN A CONTINUACIÓN: ");
System.out.println("Id: ");
long id=teclado.nextLong();
System.out.println("Nombre: ");
String nombre=teclado.next();
System.out.println("Apellido: ");
String apellido=teclado.next();
System.out.println("Cedula: ");
String cedula=teclado.next();
System.out.println("Fiabilidad de Pago: ");
String fiabilidadPago=teclado.next();
boolean resultado = clienteControlador.crear(id, nombre, apellido, cedula, fiabilidadPago);
System.out.println("Cliente creado: "+resultado);
}
public Cliente buscar(){
System.out.println("Buscar Cliente");
System.out.println("Cedula: ");
String cedula=teclado.next();
Cliente cliente= clienteControlador.buscar(cedula);
System.out.println(cliente);
return cliente;
}
public void actualizar(){
System.out.println("Actualizar");
System.out.println("Cedula: ");
String cedulaAnterior=teclado.next();
System.out.println("Cedula nueva: ");
String cedula=teclado.next();
boolean resultado=clienteControlador.acutalizar(cedulaAnterior,cedula);
System.out.println("Cliente actualizado: "+resultado);
}
public void eliminar(){
System.out.println("Eliminar Cliente");
System.out.println("Cedula");
String cedula=teclado.next();
boolean resultado=clienteControlador.eliminar(cedula);
System.out.println("Cliente eliminaro: "+ resultado);
}
public void asignarSeleccionado(Cliente cliente){
clienteControlador.setSeleccionado(cliente);
}
public ClienteControlador getClienteControlador(){
return clienteControlador;
}
public void setClienteControlador(ClienteControlador clienteControlador){
this.clienteControlador= clienteControlador;
}
public FacturaControlador getFacturaControlador(){
return facturaControlador;
}
public void setFacturaControlador(FacturaControlador facturaControlador){
this.facturaControlador=facturaControlador;
}
}
|
Java
|
UTF-8
| 857
| 2.0625
| 2
|
[] |
no_license
|
package cn.edu.qhnu.qhsfdx.ui;
import cn.edu.qhnu.qhsfdx.R;
import cn.edu.qhnu.qhsfdx.widget.TopBar;
import cn.edu.qhnu.qhsfdx.widget.TopBar.OnLeftButtonClickListener;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
public class AboutMe extends Activity implements View.OnClickListener {
private TopBar topBar;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aboutme);
topBar = (TopBar) findViewById(R.id.topBar);
topBar.setTitle("关于我们");
topBar.removeRightButton();
topBar.setLeftButton("", new OnLeftButtonClickListener() {
@Override
public void onClick(View button) {
// TODO Auto-generated method stub
AboutMe.this.finish();
}
});
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
|
PHP
|
UTF-8
| 2,335
| 2.6875
| 3
|
[
"MIT"
] |
permissive
|
<?php
/*
* This file is part of the ReCaptcha Validator Component.
*
* (c) Ilya Pokamestov
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace DS\Component\ReCaptchaValidator\Composer;
use Symfony\Component\Filesystem\Filesystem;
use Composer\Script\CommandEvent;
/**
* Script handler for post install/update commands.
*
* @author Ilya Pokamestov <dario_swain@yahoo.com>
*/
class ScriptHandler
{
/** @var Filesystem */
protected static $fileSystem;
public static function replaceViews(CommandEvent $event)
{
$event->getIO()->write('Copy ReCaptcha views to app/Resource/DS/ReCaptcha/views.');
$directory = getcwd();
self::$fileSystem = new Filesystem();
$directory .= '/app/Resources';
self::makeDirIfNOtExist($directory);
$directory .= '/DS';
self::makeDirIfNOtExist($directory);
$directory .= '/ReCaptcha';
self::makeDirIfNOtExist($directory);
$directory .= '/views';
self::makeDirIfNOtExist($directory);
if (self::$fileSystem->exists($directory.'/form_div_layout.html.twig')) {
if (!$event->getIO()->askConfirmation(
sprintf(
'form_div_layout.html.twig already exist in %s. Would you like to rewrite this file? [y/N] ',
$directory
),
false
)) {
return;
}
}
self::$fileSystem->copy(
__DIR__.'/../Resources/views/form_div_layout.html.twig',
$directory.'/form_div_layout.html.twig',
true
);
$event->getIO()->write('Files creation operation completed successfully.');
}
/**
* @param string $dir
* @throws \RuntimeException
*/
protected static function makeDirIfNOtExist($dir)
{
if (!self::isDirectoryExist($dir)) {
self::$fileSystem->mkdir($dir, 775);
}
if (!self::isDirectoryExist($dir)) {
throw new \RuntimeException(sprintf('Can\'t create directory: "%s"', $dir));
}
}
/**
* @param string $dir
* @return bool
*/
protected static function isDirectoryExist($dir)
{
return self::$fileSystem->exists($dir);
}
}
|
Python
|
UTF-8
| 210
| 3.609375
| 4
|
[] |
no_license
|
print("Hello");
primes=[2,3,4,5,7,9,23]
x=input("Enter a number")
x=int(x);
primes.append(x);
print(primes)
print(primes[0]);
x=len(primes);
print(x)
print(primes[-1]);
print(primes[2:8]);
x="A";
print(int(x));
|
C#
|
UTF-8
| 969
| 3.046875
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace ACMPrep
{
public partial class DynamicProgramming
{
[TestMethod]
public void DynamicProgramming_LongestPalindromeTest1()
{
string s = "abbac";
Assert.AreEqual("abba", LongestPalindrome(s));
}
[TestMethod]
public void DynamicProgramming_LongestPalindromeTest2()
{
string s = "abbac";
Assert.AreEqual("abba", LongestPalindrome1(s));
}
[TestMethod]
public void DynamicProgramming_LongestPalindromeTest3()
{
string s = "abbac";
Assert.AreEqual("abba", LongestPalindrome2(s));
}
[TestMethod]
public void DynamicProgramming_LongestPalindromeTest4()
{
string s = "abbac";
Assert.AreEqual("abba", LongestPalindrome3(s));
}
};
}
|
Python
|
UTF-8
| 710
| 4.15625
| 4
|
[] |
no_license
|
# Some more string stuff:
s = "test string for fun testing"
# find returns -1 if no results:
print(s.find("y"))
# rfind returns the last results
print(s.rfind("s"))
# string slices:
s[0] # first character
s[:10] # first ten characters (index 0 to 9)
s[10:] # characters from ten to the end of teh string
s[10:14] # characters ten to 13
s[-1] # negative numbers count from the end (think length - 1)
# replacing substrings without overwriting
t = s.replace("t", "0")
# save to s to overwrite
# more methods
s.isalnum() # check if is alphanumeric
s.isdecimal() # check if is decimal numbers (alphabetical/punctuation breaks it)
s.isnumeric() # check if it is numeric
s.isalpha() # check if only alphabetical
|
Java
|
UTF-8
| 12,130
| 2.046875
| 2
|
[] |
no_license
|
package reserva; /********************************************************************************
** Form generated from reading ui file 'ModalReserva.jui'
**
** Created by: Qt User Interface Compiler version 4.8.7
**
** WARNING! All changes made in this file will be lost when recompiling ui file!
********************************************************************************/
import com.trolltech.qt.core.*;
import com.trolltech.qt.gui.*;
import java.time.LocalDate;
import java.util.Arrays;
public class ModalReserva implements com.trolltech.qt.QUiForm<QMainWindow> {
public QWidget centralwidget;
public QGroupBox datoPersonalesGroup;
public QLabel nombre;
public QLabel telefono;
public QLineEdit nombreField;
public QLineEdit telefonoField;
public QGroupBox datosReservaGroup;
public QRadioButton banqueteBoton;
public QRadioButton congresoBoton;
public QRadioButton jornadaBoton;
public QGroupBox DatosEventoGroup;
public QComboBox tipoCocinaComboBox;
public QLabel fechaEventoLabel;
public QDateTimeEdit fechaEventoSpinner;
public QLabel tipoCocinaLabel;
public QLabel numeroPersonasLabel;
public QSpinBox numeroPersonasSpinner;
public QLabel tipoBanqueteLabel;
public QGroupBox datosEscondidosGroup;
public QSpinBox numeroJornadasSpinner;
public QLabel numeroJornadas;
public QLabel requiereHabitaciones;
public QRadioButton botonRadioEscondidoArriba;
public QRadioButton botonRadioEscondidoAbajo;
public QPushButton reservarBoton;
public QStatusBar statusbar;
public ModalReserva() {
super();
}
public void setupUi(QMainWindow MainWindow) {
MainWindow.setObjectName("MainWindow");
MainWindow.setWindowModality(Qt.WindowModality.WindowModal);
MainWindow.resize(new QSize(478, 366).expandedTo(MainWindow.minimumSizeHint()));
centralwidget = new QWidget(MainWindow);
centralwidget.setObjectName("centralwidget");
QPalette palette = new QPalette();
palette.setColor(QPalette.ColorGroup.Active, QPalette.ColorRole.Base, new QColor(255, 255, 255));
palette.setColor(QPalette.ColorGroup.Active, QPalette.ColorRole.Window, new QColor(255, 255, 255));
palette.setColor(QPalette.ColorGroup.Inactive, QPalette.ColorRole.Base, new QColor(255, 255, 255));
palette.setColor(QPalette.ColorGroup.Inactive, QPalette.ColorRole.Window, new QColor(255, 255, 255));
palette.setColor(QPalette.ColorGroup.Disabled, QPalette.ColorRole.Base, new QColor(255, 255, 255));
palette.setColor(QPalette.ColorGroup.Disabled, QPalette.ColorRole.Window, new QColor(255, 255, 255));
centralwidget.setPalette(palette);
centralwidget.setAutoFillBackground(true);
datoPersonalesGroup = new QGroupBox(centralwidget);
datoPersonalesGroup.setObjectName("datoPersonalesGroup");
datoPersonalesGroup.setGeometry(new QRect(30, 20, 421, 80));
nombre = new QLabel(datoPersonalesGroup);
nombre.setObjectName("nombreLabel");
nombre.setGeometry(new QRect(20, 20, 47, 13));
telefono = new QLabel(datoPersonalesGroup);
telefono.setObjectName("telefono");
telefono.setGeometry(new QRect(20, 50, 47, 13));
nombreField = new QLineEdit(datoPersonalesGroup);
nombreField.setObjectName("nombreField");
nombreField.setGeometry(new QRect(80, 20, 331, 20));
telefonoField = new QLineEdit(datoPersonalesGroup);
telefonoField.setObjectName("telefonoField");
telefonoField.setGeometry(new QRect(80, 50, 331, 20));
datosReservaGroup = new QGroupBox(centralwidget);
datosReservaGroup.setObjectName("datosReservaGroup");
datosReservaGroup.setGeometry(new QRect(30, 110, 421, 121));
banqueteBoton = new QRadioButton(datosReservaGroup);
banqueteBoton.setObjectName("banqueteBoton");
banqueteBoton.setGeometry(new QRect(120, 20, 82, 17));
congresoBoton = new QRadioButton(datosReservaGroup);
congresoBoton.setObjectName("congresoBoton");
congresoBoton.setGeometry(new QRect(230, 20, 71, 17));
jornadaBoton = new QRadioButton(datosReservaGroup);
//Dejamos pulsado el botón jornada por defecto para que no muestre los campos ocultos
jornadaBoton.click();
jornadaBoton.setObjectName("jornadaBoton");
jornadaBoton.setGeometry(new QRect(330, 20, 82, 17));
DatosEventoGroup = new QGroupBox(datosReservaGroup);
DatosEventoGroup.setObjectName("DatosEventoGroup");
DatosEventoGroup.setGeometry(new QRect(10, 40, 401, 71));
tipoCocinaComboBox = new QComboBox(DatosEventoGroup);
tipoCocinaComboBox.addItems(Arrays.asList("Buffet", "Carta",
"Cita con el chef", "No precisa"));
tipoCocinaComboBox.setObjectName("tipoCocinaComboBox");
tipoCocinaComboBox.setGeometry(new QRect(110, 40, 90, 22));
fechaEventoLabel = new QLabel(DatosEventoGroup);
fechaEventoLabel.setObjectName("fechaEventoLabel");
fechaEventoLabel.setGeometry(new QRect(10, 10, 101, 20));
fechaEventoSpinner = new QDateTimeEdit(DatosEventoGroup);
fechaEventoSpinner.setObjectName("fechaEventoSpinner");
fechaEventoSpinner.setGeometry(new QRect(110, 10, 281, 22));
fechaEventoSpinner.setCalendarPopup(true);
LocalDate hoy = LocalDate.now();
fechaEventoSpinner.setMinimumDate(new QDate(hoy.getYear(),
hoy.getMonthValue(),
hoy.getDayOfMonth()));
fechaEventoSpinner.setMaximumDate(new QDate(2030, 12, 31));
tipoCocinaLabel = new QLabel(DatosEventoGroup);
tipoCocinaLabel.setObjectName("tipoCocinaLabel");
tipoCocinaLabel.setGeometry(new QRect(10, 40, 81, 20));
numeroPersonasLabel = new QLabel(DatosEventoGroup);
numeroPersonasLabel.setObjectName("numeroPersonasLabel");
numeroPersonasLabel.setGeometry(new QRect(230, 40, 91, 16));
numeroPersonasSpinner = new QSpinBox(DatosEventoGroup);
numeroPersonasSpinner.setObjectName("numeroPersonasSpinner");
numeroPersonasSpinner.setGeometry(new QRect(341, 40, 51, 22));
numeroPersonasSpinner.setMinimum(1);
tipoBanqueteLabel = new QLabel(datosReservaGroup);
tipoBanqueteLabel.setObjectName("tipoBanqueteLabel");
tipoBanqueteLabel.setGeometry(new QRect(20, 20, 81, 16));
datosEscondidosGroup = new QGroupBox(centralwidget);
datosEscondidosGroup.setObjectName("datosEscondidosGroup");
datosEscondidosGroup.setGeometry(new QRect(30, 239, 421, 51));
numeroJornadasSpinner = new QSpinBox(datosEscondidosGroup);
numeroJornadasSpinner.setObjectName("numeroJornadasSpinner");
numeroJornadasSpinner.setGeometry(new QRect(120, 10, 42, 22));
numeroJornadas = new QLabel(datosEscondidosGroup);
numeroJornadas.setObjectName("numeroJornadas");
numeroJornadas.setGeometry(new QRect(20, 10, 120, 30));
requiereHabitaciones = new QLabel(datosEscondidosGroup);
requiereHabitaciones.setObjectName("requiereHabitaciones");
requiereHabitaciones.setGeometry(new QRect(220, 10, 111, 20));
botonRadioEscondidoArriba = new QRadioButton(datosEscondidosGroup);
botonRadioEscondidoArriba.setObjectName("botonRadioEscondidoArriba");
botonRadioEscondidoArriba.setGeometry(new QRect(340, 5, 100, 17));
botonRadioEscondidoAbajo = new QRadioButton(datosEscondidosGroup);
botonRadioEscondidoAbajo.setObjectName("botonRadiEscondidoArriba");
botonRadioEscondidoAbajo.setGeometry(new QRect(340, 30, 100, 17));
reservarBoton = new QPushButton(centralwidget);
//todo: elena logica al pulsar boton
reservarBoton.setObjectName("reservarBoton");
reservarBoton.setGeometry(new QRect(330, 300, 121, 41));
QFont font = new QFont();
font.setFamily("Segoe UI Semibold");
font.setPointSize(12);
font.setBold(true);
font.setWeight(75);
reservarBoton.setFont(font);
MainWindow.setCentralWidget(centralwidget);
statusbar = new QStatusBar(MainWindow);
statusbar.setObjectName("statusbar");
MainWindow.setStatusBar(statusbar);
retranslateUi(MainWindow);
//Escondemos los campos para que aparezcan al pulsar determinado boton
ocultarOpcionesEspeciales();
nombreField.textEdited.connect(this, "comprobarNombre()");
nombreField.textChanged.connect(this, "comprobarNombre()");
telefonoField.editingFinished.connect(this, "comprobarTelefono()");
banqueteBoton.clicked.connect(this, "mostrarOpcionesBanquete()");
banqueteBoton.released.connect(this, "ocultarOpcionesEspeciales()");
congresoBoton.pressed.connect(this, "mostrarOpcionesCongreso()");
jornadaBoton.pressed.connect(this, "ocultarOpcionesEspeciales()");
reservarBoton.clicked.connect(this, "comprobacionesAlReservar()");
MainWindow.connectSlotsByName();
} // setupUi
void ocultarOpcionesEspeciales() {
//Fijamos el mínimo del spinner oculto en 1
numeroJornadasSpinner.setMinimum(1);
//por defecto hacemos click en el botón de abajo
botonRadioEscondidoAbajo.click();
datosEscondidosGroup.hide();
}
void mostrarOpcionesBanquete() {
numeroJornadas.setText("Comensales\n por mesa");
requiereHabitaciones.setText("Tipo de mesa: ");
botonRadioEscondidoArriba.setText("Rectangular");
botonRadioEscondidoAbajo.setText("Redonda");
datosEscondidosGroup.show();
}
void mostrarOpcionesCongreso() {
numeroJornadas.setText("Número \n jornadas");
requiereHabitaciones.setText("Requiere habitaciones ");
botonRadioEscondidoArriba.setText("Sí");
botonRadioEscondidoAbajo.setText("No");
datosEscondidosGroup.show();
}
void comprobarNombre() {
String nombreIntroducido = nombreField.text();
if (nombreIntroducido == null || nombreIntroducido.isEmpty()) {
crearModalInformativo("Error", "El campo nombre es obligatorio");
return;
}
if (nombreIntroducido.contains("\\d{1,}")) {
crearModalInformativo("Error", "El nombre no puede contener números");
}
}
void comprobarTelefono() {
if (!telefonoField.text().trim()
.matches("(\\+34|0034|34)?[ -]*(6|7)[ -]*([0-9][ -]*){8}")) {
crearModalInformativo("Error:", "El teléfono introducido no es válido");
}
}
private void crearModalInformativo(String etiqueta, String mensajeError) {
ModalInformativo mainWindow = new ModalInformativo();
QMainWindow dialog = new QMainWindow();
mainWindow.setupUi(dialog);
mainWindow.escribirMensaje(etiqueta, mensajeError);
dialog.show();
}
void comprobacionesAlReservar() {
if (nombreField.text().trim().isEmpty()) {
comprobarNombre();
return;
} else if (telefonoField.text().trim().isEmpty()) {
comprobarTelefono();
return;
}
crearModalInformativo("¡Enhorabuena!", "Se ha reservado la habitación correctamente");
}
private void ventanaError() {
ModalInformativo Havana = new ModalInformativo();
QMainWindow dialog = new QMainWindow();
Havana.setupUi(dialog);
dialog.show();
}
void retranslateUi(QMainWindow MainWindow) {
MainWindow.setWindowTitle(QCoreApplication.translate("MainWindow", "MainWindow", null));
datoPersonalesGroup.setTitle(QCoreApplication.translate("MainWindow", "Datos Personales", null));
nombre.setText(QCoreApplication.translate("MainWindow", "Nombre:", null));
telefono.setText(QCoreApplication.translate("MainWindow", "Tel\u00e9fono:", null));
datosReservaGroup.setTitle(QCoreApplication.translate("MainWindow", "Datos Reserva", null));
banqueteBoton.setText(QCoreApplication.translate("MainWindow", "Banquete", null));
DatosEventoGroup.setTitle("");
fechaEventoLabel.setText(QCoreApplication.translate("MainWindow", "Fecha del evento:", null));
tipoCocinaLabel.setText(QCoreApplication.translate("MainWindow", "Tipo de cocina:", null));
numeroPersonasLabel.setText(QCoreApplication.translate("MainWindow", "Numero Personas:", null));
congresoBoton.setText(QCoreApplication.translate("MainWindow", "Congreso", null));
jornadaBoton.setText(QCoreApplication.translate("MainWindow", "Jornada", null));
tipoBanqueteLabel.setText(QCoreApplication.translate("MainWindow", "Tipo evento:", null));
datosEscondidosGroup.setTitle("");
numeroJornadas.setText(QCoreApplication.translate("MainWindow", "N\u00ba Jornadas:", null));
requiereHabitaciones.setText(QCoreApplication.translate("MainWindow", "Requiere habitaciones:", null));
botonRadioEscondidoArriba.setText(QCoreApplication.translate("MainWindow", "S\u00ed", null));
botonRadioEscondidoAbajo.setText(QCoreApplication.translate("MainWindow", "No", null));
reservarBoton.setText(QCoreApplication.translate("MainWindow", "Reservar", null));
} // retranslateUi
}
|
Java
|
UTF-8
| 2,192
| 1.84375
| 2
|
[
"Apache-2.0"
] |
permissive
|
package module512packageJava0;
import java.lang.Integer;
public class Foo0 {
Integer int0;
Integer int1;
public void foo0() {
new module1037packageJava0.Foo0().foo2();
new module966packageJava0.Foo0().foo4();
new module195packageJava0.Foo0().foo3();
new module784packageKt0.Foo0().foo5();
new module1213packageJava0.Foo0().foo3();
new module626packageJava0.Foo0().foo3();
new module400packageJava0.Foo0().foo3();
new module1220packageJava0.Foo0().foo1();
new module414packageJava0.Foo0().foo6();
new module948packageJava0.Foo0().foo1();
new module26packageJava0.Foo0().foo8();
new module46packageKt0.Foo0().foo4();
new module487packageJava0.Foo0().foo3();
new module73packageJava0.Foo0().foo0();
new leafModuleMaxpackageJava0.Foo0().foo1();
new module1195packageJava0.Foo0().foo0();
new module33packageJava0.Foo0().foo4();
new module888packageJava0.Foo0().foo3();
new module273packageKt0.Foo0().foo7();
new module559packageJava0.Foo0().foo3();
new module623packageJava0.Foo0().foo6();
new module1025packageJava0.Foo0().foo4();
new module1009packageKt0.Foo0().foo5();
new module1150packageJava0.Foo0().foo3();
new module636packageJava0.Foo0().foo3();
new module1200packageJava0.Foo0().foo3();
new module940packageKt0.Foo0().foo11();
new module554packageJava0.Foo0().foo3();
new module746packageJava0.Foo0().foo7();
new module130packageJava0.Foo0().foo4();
new module231packageJava0.Foo0().foo2();
new module1274packageJava0.Foo0().foo5();
new module466packageJava0.Foo0().foo4();
new module319packageJava0.Foo0().foo4();
new module744packageJava0.Foo0().foo6();
new module1246packageJava0.Foo0().foo3();
new module438packageKt0.Foo0().foo2();
new module105packageJava0.Foo0().foo2();
new module1082packageJava0.Foo0().foo3();
new module592packageJava0.Foo0().foo4();
new module792packageJava0.Foo0().foo3();
new module949packageJava0.Foo0().foo9();
}
public void foo1() {
foo0();
}
public void foo2() {
foo1();
}
public void foo3() {
foo2();
}
public void foo4() {
foo3();
}
}
|
Java
|
UTF-8
| 2,172
| 2.296875
| 2
|
[] |
no_license
|
package com.zzz.mt;
import com.zzz.mt.annotations.MtDao;
import com.zzz.mt.dao.MtDaoSave;
import com.zzz.mt.entity.User;
import com.zzz.mt.mapping.MapperHandler;
import com.zzz.mt.mapping.MapperResult;
import com.zzz.mt.support.SqlType;
import org.junit.Test;
import java.sql.Timestamp;
import java.util.*;
/**
* Created by 胡胜钧 on 8/6 0006.
*/
public class MtDaoSaveTest extends MtDaoBaseTest {
@MtDao
private MtDaoSave dao;
@Test
public void saveFromEntityTest() {
User user = new User();
user.setName("胡胜钧123");
user.setAge(22);
user.setSex(true);
user.setAddress("成都市123");
user.setUpdateTime(new java.sql.Date(new Date().getTime()));
user.setSqlType(SqlType.INSERT);
int n = dao.saveFromEntity(user);
System.out.println("返回的值为:" + n);
}
@Test
public void saveFromSqlTest() {
int n = dao.saveFromSql("hsj", true, 22, "成都", new Timestamp(new Date().getTime()));
System.out.println("返回的值为:" + n);
}
@Test
public void saveFromMapWithTableNameTest() {
Map<String, Object> map = new HashMap<>();
map.put("name", "hhssjj");
map.put("sex", true);
map.put("age", 12);
int n = dao.saveFromMapWithTableName(map);
System.out.println("返回的值为:" + n);
}
@Test
public void saveFromMapWithEntityClass() {
Map<String, Object> map = new HashMap<>();
map.put("name", "hhssjj");
map.put("sex", true);
map.put("age", 12);
int n = dao.saveFromMapWithEntityClass(map);
System.out.println("返回的值为:" + n);
}
@Test
public void testScanner() {
User user = new User();
user.setName("胡胜钧123");
user.setAge(22);
user.setSex(true);
user.setAddress("成都市123");
user.setTestTransient("testTransient");
user.setSqlType(SqlType.INSERT);
user.setUpdateTime(new java.sql.Date(new Date().getTime()));
MapperResult mapperResult = new MapperHandler(user, SqlType.INSERT).getMapperResult();
}
}
|
C++
|
UTF-8
| 4,887
| 2.6875
| 3
|
[] |
no_license
|
template<typename ValueType>
dunedaq::appfwk::FanOutDAQModule<ValueType>::FanOutDAQModule(std::string name)
: DAQModule(name)
, mode_(FanOutMode::NotConfigured)
, queueTimeout_(100)
, thread_(std::bind(&FanOutDAQModule<ValueType>::do_work, this))
, wait_interval_us_(std::numeric_limits<size_t>::max())
, inputQueue_(nullptr)
, outputQueues_()
{}
template<typename ValueType>
void
dunedaq::appfwk::FanOutDAQModule<ValueType>::execute_command(const std::string& cmd,
const std::vector<std::string>& /*args*/)
{
if (cmd == "configure" || cmd == "Configure") {
do_configure();
}
if (cmd == "start" || cmd == "Start") {
do_start();
}
if (cmd == "stop" || cmd == "Stop") {
do_stop();
}
}
template<typename ValueType>
std::string
dunedaq::appfwk::FanOutDAQModule<ValueType>::do_configure()
{
if (configuration_.contains("fanout_mode")) {
auto modeString = configuration_["fanout_mode"].get<std::string>();
if (modeString.find("roadcast") != std::string::npos) {
mode_ = FanOutMode::Broadcast;
} else if (modeString.find("irst") != std::string::npos) {
mode_ = FanOutMode::FirstAvailable;
} else {
// RoundRobin by default
mode_ = FanOutMode::RoundRobin;
}
} else {
// RoundRobin by default
mode_ = FanOutMode::RoundRobin;
}
wait_interval_us_ = configuration_.value<int>("wait_interval", 1000000);
auto inputName = configuration_["input"].get<std::string>();
TLOG(TLVL_DEBUG, "FanOutDAQModule") << get_name() << ": Getting queue with name " << inputName << " as input";
inputQueue_.reset(new DAQSource<ValueType>(inputName));
for (auto& output : configuration_["outputs"]) {
outputQueues_.emplace_back(new DAQSink<ValueType>(output.get<std::string>()));
}
return "Success";
}
template<typename ValueType>
std::string
dunedaq::appfwk::FanOutDAQModule<ValueType>::do_start()
{
thread_.start_working_thread_();
return "Success";
}
template<typename ValueType>
std::string
dunedaq::appfwk::FanOutDAQModule<ValueType>::do_stop()
{
thread_.stop_working_thread_();
return "Success";
}
template<typename ValueType>
void
dunedaq::appfwk::FanOutDAQModule<ValueType>::do_work()
{
auto roundRobinNext = outputQueues_.begin();
// unique_ptr needed since there's no guarantee ValueType has a no-argument
// constructor
std::unique_ptr<ValueType> data_ptr = nullptr;
while (thread_.thread_running()) {
if (inputQueue_->can_pop()) {
if (!inputQueue_->pop(*data_ptr, queueTimeout_)) {
TLOG(TLVL_WARNING) << get_name() << ": Tried but failed to pop a value from an inputQueue";
continue;
}
if (mode_ == FanOutMode::Broadcast) {
do_broadcast(*data_ptr);
} else if (mode_ == FanOutMode::FirstAvailable) {
auto sent = false;
while (!sent) {
for (auto& o : outputQueues_) {
if (o->can_push()) {
auto starttime = std::chrono::steady_clock::now();
o->push(std::move(*data_ptr), queueTimeout_);
auto endtime = std::chrono::steady_clock::now();
if (std::chrono::duration_cast<decltype(queueTimeout_)>(endtime - starttime) < queueTimeout_) {
sent = true;
break;
} else {
TLOG(TLVL_WARNING) << get_name()
<< ": A timeout occurred trying to push data "
"onto an outputqueue; data has been lost";
}
}
}
if (!sent) {
std::this_thread::sleep_for(std::chrono::microseconds(wait_interval_us_));
}
}
} else if (mode_ == FanOutMode::RoundRobin) {
while (true) {
if ((*roundRobinNext)->can_push()) {
auto starttime = std::chrono::steady_clock::now();
(*roundRobinNext)->push(std::move(*data_ptr), queueTimeout_);
auto endtime = std::chrono::steady_clock::now();
if (std::chrono::duration_cast<decltype(queueTimeout_)>(endtime - starttime) >= queueTimeout_) {
TLOG(TLVL_WARNING) << get_name()
<< ": A timeout occurred trying to push data "
"onto an outputqueue; data has been lost";
}
++roundRobinNext;
if (roundRobinNext == outputQueues_.end())
roundRobinNext = outputQueues_.begin();
break;
} else {
std::this_thread::sleep_for(std::chrono::microseconds(wait_interval_us_));
}
}
}
} else { // inputQueue_ is empty
TLOG(TLVL_TRACE, "FanOutDAQModule") << get_name() << ": Waiting for data";
std::this_thread::sleep_for(std::chrono::microseconds(wait_interval_us_));
}
}
}
|
JavaScript
|
UTF-8
| 498
| 3.390625
| 3
|
[] |
no_license
|
// let c = {'o': '2'}
// let a = {
// b: (() => {
// console.log('访问b')
// return c
// })(),
// t: 1
// }
// console.log(a.b)
// console.log(c)
// var a = 123
// function foo() {
// console.log('a',a)
// let b = 10
// }
// foo()
new Promise((resolve)=>{
setTimeout(()=>{
resolve()
},3000)
}).then(()=>{
console.log(77777)
})
setTimeout(()=>{
console.log(1111)
},3000)
setTimeout(()=>{
console.log(2222)
},2000)
setTimeout(()=>{
console.log(3333)
},4000)
|
Java
|
ISO-8859-1
| 847
| 3.265625
| 3
|
[] |
no_license
|
public class Grilo_Thread extends Thread{
private String nome;
private float pulo, distanciaPercorrida;
private int qtdPulos, distanciaTotal;
public Grilo_Thread (String nome, int distanciaTotal) {
this.nome=nome;
this.distanciaTotal=distanciaTotal;
start();
}
public void run() {
while (distanciaPercorrida < distanciaTotal) {
try {
pulo = Math.round(Math.random() * 50);
distanciaPercorrida += pulo;
qtdPulos++;
System.out.println(nome + " pulou " + pulo + "cm e j percorreu " + distanciaPercorrida + "cm");
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(nome + " alcanou a linha de chegada com " + qtdPulos + " pulos");
}
}
|
Shell
|
UTF-8
| 791
| 3.8125
| 4
|
[
"MIT"
] |
permissive
|
#!/bin/bash
#
# Lists "all" regular files in current pwd and pipes to input. Opens the
# selected file with xdg-open.
#
if [ -f $HOME/.dmenurc ]; then
. $HOME/.dmenurc
else
DMENU_VERT='dmenu -i'
fi
# whitelist filetypes
filetypes="(sh|py|java|mp3|ogg|jpeg|jpg|png|gif|tex|pdf|ods|cc|c|h|hh)"
if [ -z "$1" ]; then
dir="."
else
dir="$1/"
fi
files=$(find $dir -type f -regextype "posix-extended" -iregex "\..*(\.$filetypes)" -not -iregex '.*\.(git|svn|hg|waf|rope).*')
#echo "Found "$(echo "$files" | wc -l)" files."
# echo "$files"
result=$(echo "$files" | eval $DMENU_VERT -p open)
if [ ! -z "$result" ]; then
#mime=$(mimetype -b "$result")
#app=$(xdg-mime query default "$mime")
#echo "Open $result ($mime) with $app."
xdg-open "$result" 2> /dev/null
fi
|
Python
|
UTF-8
| 5,059
| 2.53125
| 3
|
[] |
no_license
|
import numpy as np
import pandas as pd
import common
import matplotlib.pyplot as plt
from sklearn import linear_model
import sklearn.preprocessing as preprocessing
def read_from_file(file_name, chunk_size=50000):
reader = pd.read_csv(file_name, iterator=True)
chunks = []
mark = True
while mark:
try:
df = reader.get_chunk(chunk_size)
chunks.append(df)
except:
print "Iterator Stop..."
mark = False
df = pd.concat(chunks,ignore_index=True)
return df
def process_ad_file(src_file_name,dst_file_name):
origin_ad_df = read_from_file(src_file_name)
dummy_app_platform = pd.get_dummies(origin_ad_df['appPlatform'], prefix='appPlatform')
processd_ad_df = pd.concat([origin_ad_df,dummy_app_platform],axis=1)
processd_ad_df.to_csv(dst_file_name, index=False)
def process_position_file(src_file_name,dst_file_name):
origin_pos_df = read_from_file(src_file_name)
dummy_siteset = pd.get_dummies(origin_pos_df['sitesetID'], prefix='sitesetID')
dummy_pos_type = pd.get_dummies(origin_pos_df['positionType'], prefix='positionType')
processd_pos_df = pd.concat([origin_pos_df,dummy_siteset,dummy_pos_type], axis=1)
processd_pos_df.to_csv(dst_file_name, index=False)
def process_user_file(src_file_name,dst_file_name):
origin_user_df = read_from_file(src_file_name)
origin_user_df['hometownProvID'] = origin_user_df['hometown'].as_matrix() / 100
origin_user_df['hometownCityID'] = origin_user_df['hometown'].as_matrix() % 100
origin_user_df['residenceProvID'] = origin_user_df['residence'].as_matrix() / 100
origin_user_df['residenceCityID'] = origin_user_df['residence'].as_matrix() % 100
dummy_gender = pd.get_dummies(origin_user_df['gender'], prefix='gender')
dummy_education = pd.get_dummies(origin_user_df['education'], prefix='education')
dummy_marr_status = pd.get_dummies(origin_user_df['marriageStatus'], prefix='marriageStatus')
dummy_have_baby = pd.get_dummies(origin_user_df['haveBaby'], prefix='haveBaby')
processd_user_df = pd.concat([origin_user_df, dummy_gender, dummy_education, dummy_marr_status, dummy_have_baby], axis=1)
processd_user_df.to_csv(dst_file_name, index=False)
def process_app_category_file(src_file_name,dst_file_name):
origin_app_cate_df = read_from_file(src_file_name)
origin_app_cate_df['appCategoryFirst'] = origin_app_cate_df['appCategory'].as_matrix() / 100
origin_app_cate_df['appCategorySecond'] = origin_app_cate_df['appCategory'].as_matrix() % 100
origin_app_cate_df.to_csv(dst_file_name, index=False)
def process_user_app_actions_file(src_file_name,dst_file_name):
origin_user_app_actions_df = read_from_file(src_file_name)
origin_user_app_actions_df['installTimeDay'] = origin_user_app_actions_df['installTime'].as_matrix() / 10000
origin_user_app_actions_df['installTimeHour'] = (origin_user_app_actions_df['installTime'].as_matrix() % 10000) / 100
origin_user_app_actions_df['installTimeMinu'] = origin_user_app_actions_df['installTime'].as_matrix() % 100
origin_user_app_actions_df.to_csv(dst_file_name, index=False)
def process_user_installed_app_file(src_file_name,dst_file_name):
origin_user_installed_app_df = read_from_file(src_file_name)
tmp_seri = origin_user_installed_app_df['userID'].value_counts().sort_index()
tmp_df = pd.DataFrame({'userID':list(tmp_seri.index), 'appCount':list(tmp_seri.values)})
tmp_df.to_csv(dst_file_name, index=False)
def process_train_file(src_file_name, dst_file_name,):
ori_train_df = read_from_file(src_file_name)
ori_train_df['clickTimeDay'] = ori_train_df['clickTime'].as_matrix() / 10000
ori_train_df['clickTimeHour'] = (ori_train_df['clickTime'].as_matrix() % 10000) / 100
ori_train_df['clickTimeMinu'] = ori_train_df['clickTime'].as_matrix() % 100
ori_train_df.to_csv(dst_file_name, index=False)
def process_test_file(src_file_name, dst_file_name):
ori_test_df = read_from_file(src_file_name)
ori_test_df['clickTimeDay'] = ori_test_df['clickTime'].as_matrix() / 10000
ori_test_df['clickTimeHour'] = (ori_test_df['clickTime'].as_matrix() % 10000) / 100
ori_test_df['clickTimeMinu'] = ori_test_df['clickTime'].as_matrix() % 100
ori_test_df.to_csv(dst_file_name,index=False)
if __name__ == '__main__':
process_ad_file(common.ORIGIN_AD_CSV, common.PROCESSED_AD_CSV)
process_position_file(common.ORIGIN_POSITION_CSV, common.PROCESSED_POSITION_CSV)
process_user_file(common.ORIGIN_USER_CSV, common.PROCESSED_USER_CSV)
process_app_category_file(common.ORIGIN_APP_CATEGORIES_CSV, common.PROCESSED_APP_CATEGORIES_CSV)
process_user_app_actions_file(common.ORIGIN_USER_APP_ACTIONS_CSV, common.PROCESSED_USER_APP_ACTIONS_CSV)
process_user_installed_app_file(common.ORIGIN_USER_INSTALLEDAPPS_CSV, common.PROCESSED_USER_INSTALLEDAPPS_CSV)
process_train_file(common.ORIGIN_TRAIN_CSV, common.PROCESSED_TRAIN_CSV)
process_test_file(common.ORIGIN_TEST_CSV, common.PROCESSED_TEST_CSV)
|
Python
|
UTF-8
| 1,644
| 2.8125
| 3
|
[
"MIT"
] |
permissive
|
# UNSTABLE
# Filter graph of ffmpeg consists of multiple "chians".
# Each chain looks like this:
# [in_pad][in_pad]... filter, filter, filter [out_pad][out_pad]...
# Multiple inputs and outputs, they are called pads.
# Between pads, are the filters to be applied in sequence to the video/audio
# We generate suitable filter string in this file.
def make_filter(name, *args, **kwargs):
''' Make a filter. The string has four forms:
filter
filter=value:value:value
filter=key=value:key=value:key=value
filter=value:value:key=value:key=value
'''
if not args and not kwargs:
return name
else:
prefix = name + '='
values = ':'.join(args)
kw = [('%s=%s' % (each, kwargs[each])) for each in kwargs]
kwvalues = ':'.join(kw)
if args and kwargs:
return prefix + values + ':' + kwvalues
elif not args:
return prefix + kwvalues
else:
return prefix + values
# Deprecated
class NoSuchPresetFilter(Exception):
pass
# Deprecated
preset_filters = {
'black-and-white': 'hue=s=0',
'vflip': 'vflip',
'hflip': 'hflip',
'fifo': 'fifo',
'frame-align': 'setpts=PTS-STARTPTS',
'overlay': 'overlay',
'setpts': 'setpts',
'trim': 'trim',
}
# Deprecated
def get_preset_filter(name):
''' Deprecated method, use make_filter() instead
Instead of making a filter by hand,
We generate a preset filter, if we have the name.
'''
try:
return preset_filters[name]
except KeyError:
raise NoSuchPresetFilter('filter name %s not found' % name)
|
Python
|
UTF-8
| 1,413
| 2.8125
| 3
|
[] |
no_license
|
import csv
import re
trips = {}
ftrips = {}
# Load all trips to hash
with open('../sweden/trips.txt', 'r') as f:
reader = csv.reader(f)
for row in reader:
if not row[0] == 'route_id':
trips[row[2]] = row
# Load all routes to hach
route = {}
with open('../sweden/routes.txt', 'r') as f:
reader = csv.reader(f)
for row in reader:
if not row[0] == 'route_id':
route[row[0]] = row
# Map all trimes -> trip -> route and add type to new data
stops = {}
types = {}
with open('../sweden/stop_times.txt', 'r') as f:
reader = csv.reader(f)
for row in reader:
if not row[0] == 'trip_id':
if not row[3] in stops:
stops[row[3]] = {}
stops[row[3]]['id'] = row[3]
thisroute = route[trips[row[0]][0]]
stops[row[3]]['agency_'+thisroute[1]] = 1
stops[row[3]]['type_'+thisroute[4]] = 1
types['agency_'+thisroute[1]] = 'agency_'+thisroute[1]
types['type_'+thisroute[4]] = 'type_'+thisroute[4]
# Make new file.
f = open('travelmodes.csv','w')
# Write to file:
f.write('ID')
for typ in sorted(types.iterkeys()):
f.write(',' + typ)
f.write('\n')
for row in stops:
f.write(row)
for typ in sorted(types.iterkeys()):
if typ in stops[row]:
f.write(',1')
else:
f.write(',')
f.write('\n')
f.close()
|
Markdown
|
UTF-8
| 1,598
| 2.515625
| 3
|
[] |
no_license
|
## Instructions to start the project:
1. Spinning up the devserver can be done with `npm start`
1. Storybook is also installed and can be run with `npm storybook`
### Storybook:
I've installed this to continue development after being blocked from an API (and I was not sure if I would get unblocked... below I explain more)
### Notes about OpenStreetMaps API:
I've used open street maps for geocoding.
It's a free API that can be used to get coordinates from places.
I've had a nice live results implementation but I've soon been blocked for making too many requests...
_**⚠️ So, a little warning below!**_
Try to not make too many queries in a short period, else you'll probably be blocked too ;)
If it happens you can open the app from another IP on a mobile hotspot for example.
## Notes about code:
Starting the project I wanted to have as little surprises as possible.
I already had some with the search of a free Geocoding API and that sucked up quite some time.
To keep up the speed I did these things:
- I sticked to class-based components (for stateful components) for now.
- Picked chakra-ui over styled components with a library for a quick setup...
Rebass seemed a bit outdated looking at the last human commit, and I couldn't make it run in the project somehow.🤔
## One more thing about shopfinder logic
- I Experimented to move the shopfinder logic to another component with context (and hooks). This would be better when a Google Maps overview comes in later. But to keep myself at the timebox I've decided not to continue this path.
|
JavaScript
|
UTF-8
| 483
| 2.625
| 3
|
[] |
no_license
|
import { Artist } from '../utils/models.utils'
export class ArtistService {
static getArtists = ({ name, page = 1 }) => {
return fetch(`https://api.setlist.fm/rest/0.1/search/artists.json?artistName=${name}&p=${page}`)
.then(response => response.json())
.then(json => json.artists.artist.map(artist => new Artist(artist)))
.catch(err => {
console.warn('Error fetching artists', err)
return [];
})
}
}
|
Python
|
UTF-8
| 2,188
| 2.71875
| 3
|
[] |
no_license
|
import nltk
import string
import sys
import pandas as pd
import pickle
from sklearn.feature_extraction.text import TfidfVectorizer, TfidfTransformer, CountVectorizer
# global tokenize
remove_punctuation_map = dict((ord(char), None) for char in string.punctuation)
def tokenize(text):
lowers = text.lower()
no_punctuation = lowers.translate(remove_punctuation_map)
tokens = nltk.word_tokenize(no_punctuation)
return tokens
class Emotion:
"""docstring for emotion"""
global tokenize
def tokenize(text):
lowers = text.lower()
no_punctuation = lowers.translate(remove_punctuation_map)
tokens = nltk.word_tokenize(no_punctuation)
return tokens
def __init__(self):
global remove_punctuation_map
remove_punctuation_map = dict((ord(char), None) for char in string.punctuation)
file_Name = "/home/ahmed/Desktop/collegeProjects/bot/emotion/emo/modelfile.txt"
# file_Name1 = "/home/ahmed/Desktop/collegeProjects/bot/emotion/emo/count_vect.txt"
# file_Name2 = "/home/ahmed/Desktop/collegeProjects/bot/emotion/emo/tfidfvec.txt"
fileObject = open(file_Name,'r')
# fileObject1 = open(file_Name1,'r')
# fileObject2 = open(file_Name2,'r')
global trained_clfs
trained_clfs = pickle.load(fileObject)
global count_vect
# count_vect = pickle.load(fileObject1)
global tfidfvec
# tfidfvec = pickle.load(fileObject2)
data = pd.read_csv('/home/ahmed/Desktop/collegeProjects/bot/emotion/emo/ise_processed_2.csv', header=None)
data.columns = ['emotion', 'text']
count_vect = CountVectorizer(tokenizer=tokenize, stop_words='english')
data_train_counts = count_vect.fit_transform(data.text)
tfidfvec = TfidfTransformer().fit(data_train_counts)
text_tfidf = tfidfvec.transform(data_train_counts)
def get_emotion(self, t):
result = []
for name in ['Logistic Regression', 'SVM', 'Multinomial Naive Bayes']:
docs_new = [t]
t_new_counts = count_vect.transform(docs_new)
t_new_tfidf = tfidfvec.transform(t_new_counts)
clf = trained_clfs[name]
predicted = clf.predict(t_new_tfidf)
r1 = {'name':name, 'emotion':predicted[0]}
result.append(r1)
sys.stdout.flush()
return result
emo = Emotion()
print emo.get_emotion("i feel sad")
|
Python
|
UTF-8
| 2,483
| 3.046875
| 3
|
[] |
no_license
|
from math import ceil
from itertools import combinations
from simpleai.search import (
SearchProblem,
breadth_first,
depth_first,
uniform_cost,
greedy,
astar,
)
from simpleai.search.viewers import WebViewer, BaseViewer
# es una tupla de 4 posiciones:
# - la gente del lado izquierdo del puente (cada uno con su tiempo de caminata)
# - la gente del lado derecho del puente (cada uno con su tiempo de caminata)
# - tiempo restante de la linterna
# - lado del puente en el que está la linterna (0=izqueirda, 1=derecha)
INITIAL_STATE = (10, 30, 60, 80, 120), (), 300, 0
class LinternaProblem(SearchProblem):
def is_goal(self, state):
return len(state[1]) == 5
def actions(self, state):
personas_izq, personas_der, segundos_linterna, lado_linterna = state
acciones = []
for persona in state[lado_linterna]:
if persona <= segundos_linterna:
acciones.append((persona, ))
for persona1, persona2 in combinations(state[lado_linterna], 2):
if max(persona1, persona2) <= segundos_linterna:
acciones.append((persona1, persona2))
return acciones
def result(self, state, action):
personas_izq, personas_der, segundos_linterna, lado_linterna = state
personas_izq = list(personas_izq)
personas_der = list(personas_der)
for persona in action:
if lado_linterna == 0:
personas_izq.remove(persona)
personas_der.append(persona)
else:
personas_der.remove(persona)
personas_izq.append(persona)
if lado_linterna == 0:
lado_linterna = 1
else:
lado_linterna = 0
segundos_linterna -= max(action)
return tuple(personas_izq), tuple(personas_der), segundos_linterna, lado_linterna
def cost(self, state1, action, state2):
return max(action)
def heuristic(self, state):
personas_izq, personas_der, segundos_linterna, lado_linterna = state
if personas_izq:
cantidad_viajes = ceil(len(personas_izq) / 2)
persona_mas_veloz = min(personas_izq)
return persona_mas_veloz * cantidad_viajes
else:
return 0
result = astar(LinternaProblem(INITIAL_STATE), graph_search=True)
print('Final state:', result.state)
for action, state in result.path():
print('Action:', action)
print('State:', state)
|
Python
|
UTF-8
| 2,415
| 3.21875
| 3
|
[] |
no_license
|
import itertools
INPUT_FILE = 'input.txt'
OUTPUT_FILE = 'output.txt'
def flipSwitch(outletFlow, switches):
outletFlowTemp = outletFlow[:]
for switch in switches:
switch = int(switch)
for i in range(len(outletFlowTemp)):
if(outletFlowTemp[i][switch] == '0'):
outlet = list(outletFlowTemp[i])
outlet[switch] = '1'
outletFlowTemp[i] = ''.join(outlet)
else:
outlet = list(outletFlowTemp[i])
outlet[switch] = '0'
outletFlowTemp[i] = ''.join(outlet)
return outletFlowTemp
def charging(outletFlow, deviceFlow):
outletFlowTemp = outletFlow[:]
outletFlowTemp.sort()
for device in deviceFlow:
if device in outletFlow:
outletFlowTemp.remove(device)
return len(outletFlowTemp)
def function1(outletFlow, deviceFlow, eleLen):
deviceFlow.sort()
output = 0
eleTempLength = ""
for i in range(eleLen):
eleTempLength += str(i)
allCharged = False
leftDevice = charging(outletFlow, deviceFlow)
if leftDevice == 0:
allCharged = True
while not allCharged:
output += 1
changeList = itertools.combinations(eleTempLength, output)
for flip in changeList:
tempOutletFlow = flipSwitch(outletFlow, flip)
leftDevice = charging(tempOutletFlow, deviceFlow)
if leftDevice == 0:
allCharged = True
break
if output == eleLen:
break
if leftDevice != 0:
return "NOT POSSIBLE"
return output
def mainFunciton():
inputFile = open(INPUT_FILE, 'r')
outputFile = open(OUTPUT_FILE, 'w')
noTestCase = int(inputFile.readline())
for i in xrange(noTestCase):
#INPUT
line = inputFile.readline().rstrip('\n').split(' ')
noDevice = int(line[0])
eleLen = int(line[1])
outletFlow=inputFile.readline().rstrip('\n').split(' ')
deviceFlow=inputFile.readline().rstrip('\n').split(' ')
#COMPUTATION
funOutput = function1(outletFlow, deviceFlow, eleLen)
#OUTPUT
outputLine = "Case #" + str(i+1) + ": "
outputLine += str(funOutput)
outputFile.write(outputLine + '\n')
inputFile.close()
outputFile.close()
if __name__ == '__main__':
mainFunciton()
|
Java
|
UTF-8
| 2,377
| 2.6875
| 3
|
[] |
no_license
|
package guru.springframework.sfgpc.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import java.util.HashSet;
import java.util.Set;
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "owners") // this is default behaviour
public class Owner extends Person {
@Builder
public Owner(final Long id, final String firstName, final String lastName, final String address,
final String city, final String telephone, final Set<Pet> pets) {
super(id, firstName, lastName);
this.address = address;
this.city = city;
this.telephone = telephone;
this.pets = pets;
}
private String address;
private String city;
private String telephone;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "owner")
private Set<Pet> pets = new HashSet<>();
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Owner)) {
return false;
}
if (!super.equals(o)) {
return false;
}
Owner owner = (Owner) o;
if (getAddress() != null ? !getAddress().equals(owner.getAddress()) : owner.getAddress() != null) {
return false;
}
if (getCity() != null ? !getCity().equals(owner.getCity()) : owner.getCity() != null) {
return false;
}
if (getTelephone() != null ? !getTelephone().equals(owner.getTelephone()) : owner.getTelephone() != null) {
return false;
}
return getPets() != null ? getPets().equals(owner.getPets()) : owner.getPets() == null;
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (getAddress() != null ? getAddress().hashCode() : 0);
result = 31 * result + (getCity() != null ? getCity().hashCode() : 0);
result = 31 * result + (getTelephone() != null ? getTelephone().hashCode() : 0);
result = 31 * result + (getPets() != null ? getPets().hashCode() : 0);
return result;
}
}
|
JavaScript
|
UTF-8
| 563
| 3.78125
| 4
|
[] |
no_license
|
const h1 = document.querySelector('h1');
const btn = document.querySelector('button');
let message = "";
btn.addEventListener('click', getTimeOfDay);
function getTimeOfDay() {
const dateObj = new Date();
if(dateObj.getHours() >= 0 && dateObj.getHours() <= 12) {
message = "It's morning";
}
else if(dateObj.getHours() >= 12 && dateObj.getHours() <= 17) {
message = "It's afternoon";
}
else {
message = "It's evening";
}
h1.innerText = message;
h1.setAttribute('style', 'border: 2px solid red;');
}
|
Python
|
UTF-8
| 3,282
| 2.96875
| 3
|
[] |
no_license
|
from pyspark.sql import SparkSession, Window
from pyspark.sql.types import *
from pyspark.sql.functions import *
# SETUP
spark = SparkSession.builder.appName('cleaner').getOrCreate()
df = spark \
.read \
.format('csv') \
.options(delimiter = ',') \
.load('datafeed') \
.toDF('control_area', 'unit', 'scp', 'raw_station', 'lines', 'division', 'raw_date', 'time', 'description', 'raw_entries', 'raw_exits')
# CLEAN AND CAST RELEVANT VARIABLES
df = df \
.withColumn('date', to_timestamp('raw_date', 'MM/dd/yyyy').cast(DateType())) \
.withColumn('hour', split('time', ':').getItem(0).cast(IntegerType())) \
.withColumn('total_entries', df['raw_entries'].cast(LongType())) \
.withColumn('total_exits', split('raw_exits', ' ').getItem(0).cast(LongType()))
# CALCULATE HOURLY ENTRIES AND EXITS
df = df.withColumn('dummy', lit(1))
window = Window.partitionBy('dummy').orderBy('control_area', 'unit', 'scp', 'date', 'hour')
df = df \
.withColumn('last_entries', lag('total_entries', 1).over(window)) \
.withColumn('last_exits', lag('total_exits', 1).over(window))
df = df \
.withColumn('entries', when(df['total_entries'] >= df['last_entries'], df['total_entries'] - df['last_entries']).otherwise(df['total_entries'])) \
.withColumn('exits', when(df['total_exits'] >= df['last_exits'], df['total_exits'] - df['last_exits']).otherwise(df['total_exits']))
# FILTER FOR OUTLIERS AND RELEVANT TIME PERIOD 3/1/2015 - 4/30/2020
df = df \
.filter(df['entries'] <= 88000) \
.filter(df['exits'] <= 88000) \
.filter(df['date'] >= '2015-03-01') \
.filter(df['date'] <= '2020-04-30')
# CREATE FIELDS FOR SEASON AND TIME OF DAY
df = df \
.withColumn('season', when(df['date'].between('2020-03-01', '2020-04-30'), 'coronavirus') \
.when(month(df['date']).between(3, 5), 'spring') \
.when(month(df['date']).between(6, 8), 'summer') \
.when(month(df['date']).between(9, 11), 'fall') \
.otherwise('winter')) \
.withColumn('time_of_day', when(df['hour'].between(3, 8), 'early-day') \
.when(df['hour'].between(11, 16), 'day') \
.otherwise('night'))
# MERGE ON LATITUDE AND LONGITUDE COORDINATES
coordinates = spark \
.read \
.format('csv') \
.options(delimiter = ',') \
.load('StationLocations.txt') \
.toDF('raw_station', 'station', 'raw_latitude', 'raw_longitude')
coordinates = coordinates \
.withColumn('latitude', coordinates['raw_latitude'].cast(DoubleType())) \
.withColumn('longitude', coordinates['raw_longitude'].cast(DoubleType()))
df = df.join(coordinates, df['raw_station'] == coordinates['raw_station'])
# AGGREGATE BY STATION, SEASON, AND TIME OF DAY
df = df \
.groupBy('station', 'latitude', 'longitude', 'season', 'time_of_day', 'date') \
.sum('entries', 'exits') \
.withColumnRenamed('sum(entries)', 'sum_entries') \
.withColumnRenamed('sum(exits)', 'sum_exits')
df = df \
.groupBy('station', 'latitude', 'longitude', 'season', 'time_of_day') \
.mean('sum_entries', 'sum_exits') \
.withColumnRenamed('avg(sum_entries)', 'avg_entries') \
.withColumnRenamed('avg(sum_exits)', 'avg_exits')
df.select(format_string('%s,%f,%f,%s,%s,%f,%f', 'station', 'latitude', 'longitude', 'season', 'time_of_day', 'avg_entries', 'avg_exits')).write.save('turnstile_parts', format = 'text')
spark.stop()
|
Java
|
UTF-8
| 22,773
| 2.015625
| 2
|
[
"MIT"
] |
permissive
|
package cero_tech.immersivefission.blocks.multiblocks.structures;
import blusunrize.immersiveengineering.common.IEContent;
import blusunrize.immersiveengineering.common.blocks.BlockTypes_MetalsAll;
import blusunrize.immersiveengineering.common.blocks.metal.BlockTypes_MetalDecoration0;
import blusunrize.immersiveengineering.common.blocks.metal.BlockTypes_MetalDevice0;
import blusunrize.immersiveengineering.common.blocks.metal.BlockTypes_MetalDevice1;
import blusunrize.immersiveengineering.common.blocks.wooden.BlockTypes_WoodenDecoration;
import net.minecraft.item.ItemStack;
public class StructureHeatExchanger {
public static final int[] DIMENSIONS = {7, 5, 5};
public static final ItemStack ORIGIN_BLOCK = new ItemStack(IEContent.blockMetalDevice0, 1, BlockTypes_MetalDevice0.BARREL.getMeta());
// TODO: bounding box
public static final ItemStack[][][] STRUCTURE = {
{ // y0
{ // x0
new ItemStack(IEContent.blockWoodenDecoration, 1, BlockTypes_WoodenDecoration.FENCE.getMeta()), // z0
ItemStack.EMPTY, // z1
ItemStack.EMPTY, // z2
ItemStack.EMPTY, // z3
new ItemStack(IEContent.blockWoodenDecoration, 1, BlockTypes_WoodenDecoration.FENCE.getMeta()) // z4
},
{ // x1
ItemStack.EMPTY, // z0
ItemStack.EMPTY, // z1
ItemStack.EMPTY, // z2
ItemStack.EMPTY, // z3
ItemStack.EMPTY // z4
},
{ // x2
ItemStack.EMPTY, // z0
ItemStack.EMPTY, // z1
ItemStack.EMPTY, // z2
ItemStack.EMPTY, // z3
ItemStack.EMPTY // z4
},
{ // x3
ItemStack.EMPTY, // z0
ItemStack.EMPTY, // z1
ItemStack.EMPTY, // z2
ItemStack.EMPTY, // z3
ItemStack.EMPTY // z4
},
{ // x4
new ItemStack(IEContent.blockWoodenDecoration, 1, BlockTypes_WoodenDecoration.FENCE.getMeta()), // z0
ItemStack.EMPTY, // z1
ItemStack.EMPTY, // z2
ItemStack.EMPTY, // z3
new ItemStack(IEContent.blockWoodenDecoration, 1, BlockTypes_WoodenDecoration.FENCE.getMeta()) // z4
}
},
{ // y1
{ // x0
new ItemStack(IEContent.blockWoodenDecoration, 1, BlockTypes_WoodenDecoration.FENCE.getMeta()), // z0
new ItemStack(IEContent.blockSheetmetalSlabs, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z1
new ItemStack(IEContent.blockSheetmetalSlabs, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z2
new ItemStack(IEContent.blockSheetmetalSlabs, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z3
new ItemStack(IEContent.blockWoodenDecoration, 1, BlockTypes_WoodenDecoration.FENCE.getMeta()) // z4
},
{ // x1
new ItemStack(IEContent.blockSheetmetalSlabs, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z0
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z1
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z2
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z3
new ItemStack(IEContent.blockSheetmetalSlabs, 1, BlockTypes_MetalsAll.STEEL.getMeta()) // z4
},
{ // x2
new ItemStack(IEContent.blockSheetmetalSlabs, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z0
new ItemStack(IEContent.blockMetalDevice0, 1, BlockTypes_MetalDevice0.BARREL.getMeta()), // z1
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z2
new ItemStack(IEContent.blockMetalDevice0, 1, BlockTypes_MetalDevice0.BARREL.getMeta()), // z3
new ItemStack(IEContent.blockSheetmetalSlabs, 1, BlockTypes_MetalsAll.STEEL.getMeta()) // z4
},
{ // x3
new ItemStack(IEContent.blockSheetmetalSlabs, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z0
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z1
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z2
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z3
new ItemStack(IEContent.blockSheetmetalSlabs, 1, BlockTypes_MetalsAll.STEEL.getMeta()) // z4
},
{ // x4
new ItemStack(IEContent.blockWoodenDecoration, 1, BlockTypes_WoodenDecoration.FENCE.getMeta()), // z0
new ItemStack(IEContent.blockSheetmetalSlabs, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z1
new ItemStack(IEContent.blockSheetmetalSlabs, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z2
new ItemStack(IEContent.blockSheetmetalSlabs, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z3
new ItemStack(IEContent.blockWoodenDecoration, 1, BlockTypes_WoodenDecoration.FENCE.getMeta()) // z4
}
},
{ // y2
{ // x0
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z0
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z1
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z2
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z3
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()) // z4
},
{ // x1
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z0
new ItemStack(IEContent.blockMetalDecoration0, 1, BlockTypes_MetalDecoration0.RADIATOR.getMeta()), // z1
new ItemStack(IEContent.blockMetalDecoration0, 1, BlockTypes_MetalDecoration0.RADIATOR.getMeta()), // z2
new ItemStack(IEContent.blockMetalDecoration0, 1, BlockTypes_MetalDecoration0.RADIATOR.getMeta()), // z3
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()) // z4
},
{ // x2
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z0
new ItemStack(IEContent.blockMetalDevice1, 1, BlockTypes_MetalDevice1.FLUID_PIPE.getMeta()), // z1
new ItemStack(IEContent.blockMetalDecoration0, 1, BlockTypes_MetalDecoration0.RADIATOR.getMeta()), // z2
new ItemStack(IEContent.blockMetalDevice1, 1, BlockTypes_MetalDevice1.FLUID_PIPE.getMeta()), // z3
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()) // z4
},
{ // x3
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z0
new ItemStack(IEContent.blockMetalDecoration0, 1, BlockTypes_MetalDecoration0.RADIATOR.getMeta()), // z1
new ItemStack(IEContent.blockMetalDecoration0, 1, BlockTypes_MetalDecoration0.RADIATOR.getMeta()), // z2
new ItemStack(IEContent.blockMetalDecoration0, 1, BlockTypes_MetalDecoration0.RADIATOR.getMeta()), // z3
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()) // z4
},
{ // x4
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z0
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z1
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z2
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z3
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()) // z4
}
},
{ // y3
{ // x0
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z0
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z1
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z2
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z3
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()) // z4
},
{ // x1
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z0
new ItemStack(IEContent.blockMetalDecoration0, 1, BlockTypes_MetalDecoration0.RADIATOR.getMeta()), // z1
new ItemStack(IEContent.blockMetalDecoration0, 1, BlockTypes_MetalDecoration0.RADIATOR.getMeta()), // z2
new ItemStack(IEContent.blockMetalDecoration0, 1, BlockTypes_MetalDecoration0.RADIATOR.getMeta()), // z3
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()) // z4
},
{ // x2
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z0
new ItemStack(IEContent.blockMetalDevice1, 1, BlockTypes_MetalDevice1.FLUID_PIPE.getMeta()), // z1
new ItemStack(IEContent.blockMetalDecoration0, 1, BlockTypes_MetalDecoration0.RADIATOR.getMeta()), // z2
new ItemStack(IEContent.blockMetalDevice1, 1, BlockTypes_MetalDevice1.FLUID_PIPE.getMeta()), // z3
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()) // z4
},
{ // x3
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z0
new ItemStack(IEContent.blockMetalDecoration0, 1, BlockTypes_MetalDecoration0.RADIATOR.getMeta()), // z1
new ItemStack(IEContent.blockMetalDecoration0, 1, BlockTypes_MetalDecoration0.RADIATOR.getMeta()), // z2
new ItemStack(IEContent.blockMetalDecoration0, 1, BlockTypes_MetalDecoration0.RADIATOR.getMeta()), // z3
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()) // z4
},
{ // x4
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z0
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z1
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z2
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z3
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()) // z4
}
},
{ // y4
{ // x0
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z0
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z1
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z2
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z3
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()) // z4
},
{ // x1
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z0
new ItemStack(IEContent.blockMetalDecoration0, 1, BlockTypes_MetalDecoration0.RADIATOR.getMeta()), // z1
new ItemStack(IEContent.blockMetalDecoration0, 1, BlockTypes_MetalDecoration0.RADIATOR.getMeta()), // z2
new ItemStack(IEContent.blockMetalDecoration0, 1, BlockTypes_MetalDecoration0.RADIATOR.getMeta()), // z3
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()) // z4
},
{ // x2
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z0
new ItemStack(IEContent.blockMetalDevice1, 1, BlockTypes_MetalDevice1.FLUID_PIPE.getMeta()), // z1
new ItemStack(IEContent.blockMetalDecoration0, 1, BlockTypes_MetalDecoration0.RADIATOR.getMeta()), // z2
new ItemStack(IEContent.blockMetalDevice1, 1, BlockTypes_MetalDevice1.FLUID_PIPE.getMeta()), // z3
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()) // z4
},
{ // x3
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z0
new ItemStack(IEContent.blockMetalDecoration0, 1, BlockTypes_MetalDecoration0.RADIATOR.getMeta()), // z1
new ItemStack(IEContent.blockMetalDecoration0, 1, BlockTypes_MetalDecoration0.RADIATOR.getMeta()), // z2
new ItemStack(IEContent.blockMetalDecoration0, 1, BlockTypes_MetalDecoration0.RADIATOR.getMeta()), // z3
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()) // z4
},
{ // x4
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z0
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z1
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z2
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z3
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()) // z4
}
},
{ // y5
{ // x0
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z0
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z1
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z2
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z3
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()) // z4
},
{ // x1
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z0
new ItemStack(IEContent.blockMetalDecoration0, 1, BlockTypes_MetalDecoration0.RADIATOR.getMeta()), // z1
new ItemStack(IEContent.blockMetalDecoration0, 1, BlockTypes_MetalDecoration0.RADIATOR.getMeta()), // z2
new ItemStack(IEContent.blockMetalDecoration0, 1, BlockTypes_MetalDecoration0.RADIATOR.getMeta()), // z3
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()) // z4
},
{ // x2
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z0
new ItemStack(IEContent.blockMetalDevice1, 1, BlockTypes_MetalDevice1.FLUID_PIPE.getMeta()), // z1
new ItemStack(IEContent.blockMetalDecoration0, 1, BlockTypes_MetalDecoration0.RADIATOR.getMeta()), // z2
new ItemStack(IEContent.blockMetalDevice1, 1, BlockTypes_MetalDevice1.FLUID_PIPE.getMeta()), // z3
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()) // z4
},
{ // x3
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z0
new ItemStack(IEContent.blockMetalDecoration0, 1, BlockTypes_MetalDecoration0.RADIATOR.getMeta()), // z1
new ItemStack(IEContent.blockMetalDecoration0, 1, BlockTypes_MetalDecoration0.RADIATOR.getMeta()), // z2
new ItemStack(IEContent.blockMetalDecoration0, 1, BlockTypes_MetalDecoration0.RADIATOR.getMeta()), // z3
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()) // z4
},
{ // x4
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z0
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z1
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z2
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z3
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()) // z4
}
},
{ // y6
{ // x0
ItemStack.EMPTY, // z0
new ItemStack(IEContent.blockSheetmetalSlabs, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z1
new ItemStack(IEContent.blockSheetmetalSlabs, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z2
new ItemStack(IEContent.blockSheetmetalSlabs, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z3
ItemStack.EMPTY // z4
},
{ // x1
new ItemStack(IEContent.blockSheetmetalSlabs, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z0
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z1
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z2
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z3
new ItemStack(IEContent.blockSheetmetalSlabs, 1, BlockTypes_MetalsAll.STEEL.getMeta()) // z4
},
{ // x2
new ItemStack(IEContent.blockSheetmetalSlabs, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z0
new ItemStack(IEContent.blockMetalDevice0, 1, BlockTypes_MetalDevice0.BARREL.getMeta()), // z1
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z2
new ItemStack(IEContent.blockMetalDevice0, 1, BlockTypes_MetalDevice0.BARREL.getMeta()), // z3
new ItemStack(IEContent.blockSheetmetalSlabs, 1, BlockTypes_MetalsAll.STEEL.getMeta()) // z4
},
{ // x3
new ItemStack(IEContent.blockSheetmetalSlabs, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z0
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z1
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z2
new ItemStack(IEContent.blockSheetmetal, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z3
new ItemStack(IEContent.blockSheetmetalSlabs, 1, BlockTypes_MetalsAll.STEEL.getMeta()) // z4
},
{ // x4
ItemStack.EMPTY, // z0
new ItemStack(IEContent.blockSheetmetalSlabs, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z1
new ItemStack(IEContent.blockSheetmetalSlabs, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z2
new ItemStack(IEContent.blockSheetmetalSlabs, 1, BlockTypes_MetalsAll.STEEL.getMeta()), // z3
ItemStack.EMPTY // z4
}
}
};
}
|
C
|
UTF-8
| 264
| 3.71875
| 4
|
[] |
no_license
|
#include <stdio.h>
int main()
{
int a,b;
printf("\nEnter the value of a,b:");
scanf("%d%d",&a,&b);
printf("\nBefore swappig the values area: a%d, b%d", a ,b);
a=a+b;
b=a-b;
a=a-b;
printf("\nAfter swapping the values are: a%d, b%d", a , b);
return(0);
}
|
Java
|
UTF-8
| 867
| 2.875
| 3
|
[] |
no_license
|
package damas.models;
import java.util.List;
public class Session {
private Game game;
private State state;
public Session() {
this.game = new Game();
this.state = new State();
}
public void resume() {
this.game =new Game();
this.state =new State();
}
public void next() {
this.state.next();
}
public StateValue getValueState() {
return this.state.getValueState();
}
public boolean isLooser() {
return this.game.isLooser();
}
public boolean isWinner() {
return this.game.isWinner();
}
public Piece getPiece(Coordinate origin) {
return game.getPiece(origin);
}
public boolean isLastMovement(Coordinate origin, Coordinate target) {
return false;
}
public Turn nextTurn(){
return null;
}
}
|
Python
|
UTF-8
| 807
| 3.78125
| 4
|
[] |
no_license
|
'''saída: mostre o número de meses para que um a dívida seja paga o total e o total de juros pago
entrada: pergunte o valor incial de uma dívida e o juros mensal'''
dividaInicial = float(input("insira o valor da dívida: "))
juroMes = float(input("Insira o juro mensal: "))
valorMensal = float(input("Insira o valor mensal para pagar: "))
pgtoEfetuado = 0
meses = 0
jurosTrasn = juroMes/100
jurosTotal = 0
dividaTotal = dividaInicial + (dividaInicial * jurosTrasn)
while pgtoEfetuado < dividaTotal:
jurosTotal += dividaInicial * jurosTrasn
pgtoEfetuado += valorMensal
meses += 1
print("Valor total da dívida R$ %5.2f " % dividaTotal)
print("Total pago R$ %5.2f" % pgtoEfetuado)
print("Total de Juros Pagos R$ %5.2f" % jurosTotal)
print("Total de meses para pagar: %d" % meses)
|
Java
|
UTF-8
| 605
| 2.28125
| 2
|
[] |
no_license
|
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
//File: JdbcTestApplication.java
public class JdbcTestApplication {
public static void main(String[] args) {
Resource res = new ClassPathResource("SpringConfig.xml");
BeanFactory factory = new XmlBeanFactory(res);
StudentDao dao = (StudentDao) factory.getBean("dao");
Student s = new Student(103, "RAM", "HYDERABAD");
int i =dao.updateStudent(s);
System.out.println(i);
}
}
|
TypeScript
|
UTF-8
| 2,977
| 2.65625
| 3
|
[] |
no_license
|
import * as R from 'ramda';
import * as constants from '../../application/constants';
import * as actions from './actions';
import * as types from './types';
import { Id, ServiceStore } from './types';
export { Id, ServiceStore };
export function buildDefaultStore(): types.ServiceStore {
return {
services: {},
servicesByTopic: {},
};
}
export const buildEmptyServicesForTopic = (): types.ValidServicesForTopic => ({
serviceIds: [],
type: constants.TOPIC_SERVICES_VALID,
});
export function reducer(store: types.ServiceStore = buildDefaultStore(), action?: actions.ServicesAction): types.ServiceStore {
if (!action) {
return store;
}
switch (action.type) {
case constants.LOAD_SERVICES_REQUEST:
return updateServicesRequest(store, action);
case constants.LOAD_SERVICES_SUCCESS:
return updateServicesSuccess(store, action);
case constants.LOAD_SERVICES_FAILURE:
return updateServicesFailure(store, action);
default:
return store;
}
}
const updateServicesRequest = (store: types.ServiceStore, action: actions.BuildTopicServicesRequestAction): types.ServiceStore => {
const topicId = action.payload.topicId;
return {
...store,
servicesByTopic: {
...store.servicesByTopic,
[topicId]: {
type: constants.TOPIC_SERVICES_LOADING,
},
},
};
};
const updateServicesSuccess = (store: types.ServiceStore, action: actions.BuildTopicServicesSuccessAction): types.ServiceStore => {
const newServices = action.payload.services;
const topicId = action.payload.topicId;
const newServicesAsMap = createServiceMap(newServices);
const newServiceIds = R.map((service: types.Service): string => service.id, newServices);
return {
...store,
services: {
...store.services,
...newServicesAsMap,
},
servicesByTopic: {
...store.servicesByTopic,
[topicId]: {
type: constants.TOPIC_SERVICES_VALID,
serviceIds: newServiceIds,
},
},
};
};
const updateServicesFailure = (store: types.ServiceStore, action: actions.BuildTopicServicesErrorAction): types.ServiceStore => {
const topicId = action.payload.topicId;
const errorMessageType = action.payload.errorMessageType;
return {
...store,
servicesByTopic: {
...store.servicesByTopic,
[topicId]: {
type: constants.TOPIC_SERVICES_ERROR,
errorMessageType,
},
},
};
};
const createServiceMap = (services: ReadonlyArray<types.Service>): types.ServiceMap => {
const theReducer = (serviceMap: types.ServiceMap, service: types.Service): types.ServiceMap => {
return { ...serviceMap, [service.id]: service };
};
return services.reduce(theReducer, {});
};
|
JavaScript
|
UTF-8
| 641
| 3.4375
| 3
|
[] |
no_license
|
function checkPalindrome(s){
var center = 0
var _center = 0
var low = 0,hei = 0
var len = s.length
var posi = [0, 0]
while(center < len){
_center = center+1
while(s[center] === s[_center]){
_center++
}
low = center-1
hei = _center
while(low >=0 && hei <len && s[low] === s[hei]){
low--
hei++
}
low = low+1
if(hei - low > posi[1] - posi[0]){
posi[0] = low
posi[1] = hei
}
center = _center
}
return s.slice(posi[0], posi[1])
}
console.log(checkPalindrome("aba"))
|
Ruby
|
UTF-8
| 614
| 3.0625
| 3
|
[] |
no_license
|
module PololuMaestro
class Servo
attr_accessor :min_angle, :max_angle, :min_ms, :max_ms
def initialize(driver, channel)
@driver = driver
@channel = channel
end
def set_angle(angle)
raise RuntimeError.new("Angle too low") if angle < @min_angle
raise RuntimeError.new("Angle too high") if angle > @max_angle
ratio = (angle - @min_angle).to_f / (@max_angle - @min_angle)
pos = @min_ms + (ratio * (@max_ms - @min_ms))
@driver.set_target(@channel, pos.to_i * 4)
end
def set_speed(speed)
@driver.set_speed(@channel, speed)
end
end
end
|
PHP
|
UTF-8
| 878
| 3.1875
| 3
|
[] |
no_license
|
<?php
/**
* Created by PhpStorm.
* User: linqiuyu
* Date: 19-3-18
* Time: 下午7:34
*/
class Tyre
{
public function roll()
{
echo 'The tire is rolling' . PHP_EOL;
}
}
class BMW
{
protected $tyre;
public function __construct($tyre)
{
$this->tyre = $tyre;
}
function run()
{
$tyre = new Tyre();
$tyre->roll();
echo 'BMW run' . PHP_EOL;
}
}
class Container
{
static $register = [];
static function bind($name, Closure $col)
{
self::$register[$name] = $col;
}
static function make($name)
{
$col = self::$register[$name];
return $col();
}
}
Container::bind('tyre', function () {
return new Tyre();
});
Container::bind('bmw', function () {
return new BMW(Container::make('tyre'));
});
$bmw = Container::make('bmw');
$bmw->run();
|
Java
|
UTF-8
| 832
| 2.453125
| 2
|
[] |
no_license
|
package br.com.caelum.fj26;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
/**
* Classe que representa a entidade Produto
*
* @author vagner
*
*/
@Entity
public class Produto {
@Id
@SequenceGenerator(name = "PRODUTO_ID", sequenceName = "PRODUTO_SEQ", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "PRODUTO_ID")
@Column(name = "ID")
private Long id;
private String descricao;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
}
|
Python
|
UTF-8
| 4,248
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup as soup
from selenium import webdriver
import requests
import time
class NetflixScraper:
def __init__(self, username, password):
self.username = username
self.password = password
self.driver = webdriver.Firefox(executable_path="C:\geckodriver.exe")
def close_browser(self):
driver = self.driver
driver.close()
def login(self):
driver = self.driver
driver.get("https://www.netflix.com/br/")
time.sleep(1)
login_button = driver.find_element_by_xpath("//a[@class='authLinks signupBasicHeader']")
login_button.click()
time.sleep(1)
username_box = driver.find_element_by_xpath("//input[@id='id_userLoginId']")
username_box.send_keys(self.username)
password_box = driver.find_element_by_xpath("//input[@id='id_password']")
password_box.send_keys(self.password)
password_box.send_keys(Keys.RETURN)
time.sleep(6)
select_user = driver.find_element_by_xpath("//div[@class='profile-icon']")
select_user.click()
def get_ids(self, categorie):
driver = self.driver
url = "https://www.netflix.com/browse/genre/83?so=az" if categorie == 'Series' else "https://www.netflix.com/browse/genre/34399?so=az"
driver.get(url)
time.sleep(3)
get_height = lambda:driver.execute_script("return window.pageYOffset;")
last_height = -5
current_height = get_height()
while(current_height != last_height):
last_height = current_height
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
time.sleep(2)
current_height = get_height()
urls = driver.find_elements_by_xpath("//div[@class='slider-item slider-item-1']//a")
title_ids = []
for url in urls:
try:
url = url.get_attribute('href')
start_point = url.find('/watch/') + 7
end_point = url.find('?', start_point)
title_ids.append(url[start_point:end_point])
except Exception as e:
print(e)
continue
return title_ids
def get_title_info(self, title_id, categorie):
url = "https://www.netflix.com/br/title/{}".format(title_id)
response_text = requests.get(url).text
html = soup(response_text, "html.parser")
information_block = html.find("div", {'id':'appMountPoint'})
name = html.h1.text
year = information_block.find('span', {'class':'year'}).text.replace(' ', '')
age = information_block.find('span', {'class':'maturity-number'}).text.replace(' ', '')
genre_list = information_block.find('span', {'class':'genre-list'}).text.replace('\xa0', '')
duration = information_block.find('span', {'class':'duration'}).text
try:
creators = information_block.find('span', {'class':'creator-name'}).text.replace('\xa0', '')
except Exception:
creators = 'Not found'
try:
directors = information_block.find('span', {'class':'director-name more-details-content'}).text.replace('\xa0', '')
except Exception:
directors = 'Not found'
try:
actors = information_block.find('span', {'class':'actors-list'}).text.replace('\xa0', '')
except Exception:
actors = 'Not found'
synopsis = information_block.find('p', {'class':'synopsis'}).text
row = [categorie, name, duration, year, actors, creators, directors, genre_list, age, synopsis]
return row
username = 'EMAIL'
password = 'PASSWORD'
bot = NetflixScraper(username, password)
bot.login()
series_ids = bot.get_ids('Series')
movies_ids = bot.get_ids('Movies')
bot.close_browser()
title_infos = [] # list of titles with name, year, duration, episodes etc.
series_remaining = len(series_ids)
movies_remaining = len(movies_ids)
for title_id in series_ids:
info = bot.get_title_info(title_id, 'Series')
title_infos.append(info)
print("{} done. {} series remaining...".format(info[1], series_remaining))
series_remaining -= 1
for title_id in movies_ids:
info = bot.get_title_info(title_id, 'Movies')
title_infos.append(info)
print("{} done. {} movies remaining...".format(info[1], movies_remaining))
movies_remaining -= 1
with open ('netflix_catalogue.csv', 'a', encoding="utf-8") as file:
file.write("Categorie;Name;Duration;Year;Starring;Creators;Directors;Genres;Maturity;Synopsis\n")
for title in title_infos:
to_write = ";".join(title) + '\n'
print(to_write)
file.write(to_write)
|
C#
|
UTF-8
| 2,589
| 2.875
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using Platform.Utils.Extensions;
namespace Platform.Utils
{
public static class Assemblies
{
private static bool _loaded = false;
private static Object _lock = new object();
private static void LoadAllAssemblies()
{
lock (_lock)
{
if (_loaded)
return;
var path = Directory.GetParent(new Uri(Assembly.GetCallingAssembly().CodeBase).LocalPath);
path.EnumerateFiles("*.dll").ToList().ForEach(s =>
{
try
{
var assName =
AssemblyName.GetAssemblyName(s.FullName);
if (AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(a => a.FullName == assName.FullName) == null)
Assembly.Load(assName);
}
catch
{
}
}
);
_loaded = true;
}
}
public static Assembly[] All()
{
LoadAllAssemblies();
return AppDomain.CurrentDomain.GetAssemblies();
}
public static IEnumerable<Type> AllTypes()
{
var result = new List<Type>();
foreach (Assembly assembly in All())
{
result.AddRange(assembly.AllTypes());
}
return result;
}
public static IEnumerable<Type> AllTypes<TBaseType>(TypeOptions options = TypeOptions.All)
{
var result = new List<Type>();
foreach (Assembly assembly in All())
{
result.AddRange(assembly.AllTypes<TBaseType>(options));
}
return result;
}
}
}
|
C++
|
UTF-8
| 276
| 2.609375
| 3
|
[] |
no_license
|
#pragma once
#include <ctime>
#include <string>
using std::string;
class Obra{
string nombre;
string codigo;
string fechaIngreso;
double precio;
public:
Obra(string,string, string,double);
virtual ~Obra();
virtual string toString()const;
string getFecha()const;
};
|
Python
|
UTF-8
| 1,822
| 3.1875
| 3
|
[] |
no_license
|
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.naive_bayes import GaussianNB
from sklearn.preprocessing import OneHotEncoder
from sklearn import metrics
import os
'''
SOcial Status Encoding
'''
def encoding(x):
if (x == 'Never Married'):
return 0
elif(x == 'Married'):
return 1
elif(x == 'Seperated'):
return 2
elif(x == 'Divorcee'):
return 3
elif (x == 'Widowed/Widower'):
return 4
def gender_encoding(x):
if (x == 'Female'):return 1
else : return 0
def main():
df = pd.read_csv("Social_Status.csv")
'''
Adding Encoding to Education and Gender
'''
for ind,row in df.iterrows():
df.loc[ind,"Cataegory"] = encoding(df.loc[ind,"Type"])
df = df.astype({"Cataegory": int})
for ind,row in df.iterrows():
df.loc[ind,"Coded_Gender"] = gender_encoding(df.loc[ind,"Gender"])
df = df.astype({"Coded_Gender": int})
'''
Creating training and Testing Data
'''
df = df[['Cataegory','Total','Coded_Gender']]
X = df.drop(['Coded_Gender'],axis = 'columns')
Y = df.Coded_Gender
X_train1, X_test1, Y_train1, Y_test1 = train_test_split(X, Y, test_size=0.1,random_state = 25)
'''
Performing Naive Bayes with X = Cataegory and Total-Deaths , Y = Gender
'''
gnb = GaussianNB()
gnb.fit(X_train1,Y_train1)
y_pred = gnb.predict(X_test1)
print(y_pred)
print("Gaussian Naive Bayes model accuracy(in %):", metrics.accuracy_score(Y_test1, y_pred)*100)
probabilities = gnb.predict_proba(X_test1)
print(probabilities)
print("Finished ......")
if __name__ == "__main__":
main()
|
JavaScript
|
UTF-8
| 991
| 2.859375
| 3
|
[] |
no_license
|
$(document).ready(function() {
fixNavAndAbout();
$(window).resize(function() {
fixNavAndAbout();
});
//makes about and nav equal
function fixNavAndAbout (){
var aboutHeight = $("#about").css("height");
var aboutHeightNum = parseInt(aboutHeight, 10);
var navHeight = $("#navbar").css("height");
var navHeightNum = parseInt(navHeight, 10);
console.log(aboutHeight, aboutHeightNum, navHeight, navHeightNum);
if(aboutHeightNum > navHeightNum) {
var difference = aboutHeightNum-navHeightNum;
var navMargin = difference/2;
var navsMargin = navMargin+"px";
$("#navbar").css("height", aboutHeight);
$("#about").css("height", aboutHeight);
$("#navbar nav").css("padding-top", navsMargin);
}
if(aboutHeightNum < navHeightNum) {
$("#about").css("height", navHeight);
$("#navbar").css("height", navHeight);
}
}
});
|
Python
|
UTF-8
| 143
| 3.71875
| 4
|
[] |
no_license
|
numberList = []
i = 0
while i < 5:
print("Enter a Number: ", end="")
numberList.append(int(input())**2)
i += 1
print(numberList)
|
Python
|
UTF-8
| 8,997
| 2.953125
| 3
|
[
"MIT"
] |
permissive
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 14 10:35:50 2020
@author: hales
"""
import copy
import ply
import lib
import lexer
import parser_combinator as pc
# test Item
def test_hello():
print('hi')
assert 1 == 1
print('test-parser')
tokenizer = lexer.tokenizer
#print(f'tokenizer={tokenizer}')
tokenizer.input('hello')
#print(tokenizer.__dict__)
t = next(tokenizer)
#print(t)
tokenizer.input('and again')
t = next(tokenizer)
#print(t)
#print('-'*4)
for t in tokenizer:
#print(t)
pass
def test_lex():
tokenizer.input('new string')
for tok in tokenizer:
print(tok.__dict__)
print(type(tok))
print(ply.lex.LexToken.__dict__)
assert tok.value in ['new','string']
test_lex()
def mk_item_stream(s:str):
tokenizer.input(s) #re-initialization
return pc.init_item([tok for tok in tokenizer])
def test_hello_world():
it = mk_item_stream("Hello World!")
vals = ['hello','world','!']
for i in range(3):
it = pc.next_item(it)
#print(it.acc)
assert it.acc.value == vals[i]
test_hello_world()
####
def test_update():
its = mk_item_stream('Hello')
it = pc.next_item(its)
assert it.acc.value == 'hello'
tok = copy.copy(it.acc)
tok.value = 'bye'
it1 = pc.update(tok,its)
assert it1.acc.value == 'bye'
def test_next_token(): #call as well.
its = mk_item_stream('Hello there!')
#print(f'its={its}')
p = pc.Parse.next_token().process
its1 = p(its)
#print(f'its={its} -')
#print(f'its1={its1}')
#its2 = p.process(its)
#print(f'its2={its2}')
assert its1.acc.value == 'hello'
test_update()
test_next_token()
def test_add():
its = mk_item_stream('Hello there')
p = pc.Parse.next_token()
p2 = p + p
its1 = p2.process(its)
#print(its1)
(a,b) = its1.acc
assert ('hello','there') == (a.value,b.value)
test_add()
def test_or():
its = mk_item_stream('Hello there')
p = pc.Parse.next_token()
q = pc.Parse.identity().if_test(lambda _ : False)
pq = p | q
its1 = pq.process(its)
assert its1.acc.value == 'hello'
qp = q.if_test(lambda _: False) | p
its2 = qp.process(its)
#print(its2)
assert its2.acc.value == 'hello'
test_or()
#def test_compose():
# its = mk_item_stream('Hello there')
# p = pc.Parse.next_token()
# p2 = p.compose(p)
# assert p2.process(its).acc.value == 'there'
#test_compose()
def test_nocatch():
its = mk_item_stream('Hello there')
p = pc.Parse.next_token().if_test(lambda _ : False)
try:
p.process(its)
assert False
except pc.ParseError:
assert True
try:
p.nocatch('msg').process(its)
assert False
except pc.ParseNoCatch:
assert True
test_nocatch()
def test_treat():
its = mk_item_stream('Hello there')
p = pc.Parse.next_token()
def t(_):
return 0
its1 = p.treat(t).process(its)
assert its1.acc == 0
test_treat()
def test_many():
its = mk_item_stream('Hello there # and more')
p = pc.Parse.next_token().if_type('WORD').many()
its1 = p.process(its)
#print(its1)
vals = [t.value for t in its1.acc]
assert vals == ['hello','there']
test_many()
def test_plus():
its = mk_item_stream('Hello there # and more')
p = pc.Parse.next_token().if_type('WORD').plus()
its1 = p.process(its)
#print(its1)
vals = [t.value for t in its1.acc]
assert vals == ['hello','there']
try:
q = pc.Parse.next_token().if_type('SYMBOL').plus()
its1= q.process(its)
assert False
except pc.ParseError:
assert True
test_plus()
def test_possibly():
its = mk_item_stream('Hello there # and more')
p = pc.Parse.next_token().if_type('WORD').possibly()
its1 = p.process(its)
#print(its1)
vals = [t.value for t in its1.acc]
assert vals == ['hello']
q = pc.Parse.next_token().if_type('SYMBOL').possibly()
its1= q.process(its)
vals = [t.value for t in its1.acc]
assert vals == []
test_possibly()
def test_identity():
its = mk_item_stream('Hello there # and more')
p = pc.Parse.identity()
its1 = p.process(its)
assert its1 == its
test_identity()
def test_nil():
its = mk_item_stream('Hello there # and more')
p = pc.Parse.next_token().nil()
its1 = p.process(its)
assert its1.acc == []
test_nil()
def test_separated_nonempty_list():
its = mk_item_stream('Hello, there, and more')
p = pc.Parse.next_token().if_type('WORD')
sep = pc.Parse.next_token().if_value(',')
its1 = p.separated_nonempty_list(sep).process(its)
vals = [t.value for t in its1.acc]
#print(its1)
assert vals == ['hello','there','and']
its1 = p.separated_list(sep).process(its)
vals = [t.value for t in its1.acc]
assert vals == ['hello','there','and']
test_separated_nonempty_list()
def test_if_test_treat():
pass
def test_all():
its = mk_item_stream('Hello there#and more')
p = pc.Parse.next_token().if_type('WORD')
q = pc.Parse.next_token().if_type('SYMBOL')
its1 = pc.Parse.all([p,p,q,p]).process(its)
vals = [t.value for t in its1.acc]
#print(its1)
assert vals == ['hello','there','#','and']
test_all()
def test_first():
its = mk_item_stream('#Hello there#and more')
p = pc.Parse.next_token().if_type('WORD')
q = pc.Parse.next_token().if_type('SYMBOL')
its1 = pc.Parse.first([p,p,q,p]).process(its)
assert its1.acc.value == '#'
test_first()
def test_wordify():
its = mk_item_stream('x')
p = pc.Parse.next_token()
tok = p.process(its).acc
tok1 = pc.wordify(p.process(its).acc)
assert pc.can_wordify(tok)
assert tok1.value == 'x' and tok1.type == 'WORD'
test_wordify()
#print (pc.synonym)
def test_synonym():
pc.synonym_add(['hi there','hithere']) # error
pc.synonym_add(['such']) # error
pc.synonym_add(['hi']) # error
pc.synonym_add(['alpha3']) #error
pc.synonym_add(['roundtrip','journey','stars'])
s = pc.synonymize('star')
#print(f's={s}')
assert s == 'journey roundtrip star'
assert pc.synonymize('yes') == 'yes'
its = mk_item_stream('X roundtrips')
p = pc.Parse.next_token()
its1 = p.process(its)
its2 = p.process(its1)
assert pc.synw(its1.acc) == 'x'
assert pc.synw(its2.acc) == 'journey roundtrip star'
test_synonym()
def test_next_word():
its = mk_item_stream('Hello X journey there now and then')
p = pc.next_word('hello')
its1 = p.process(its)
assert its1.acc.value == 'hello'
#next_any_word
p = pc.next_any_word()
its2 = p.process(its1)
assert its2.acc.value == 'x'
#next_any_word_except
p = pc.next_any_word_except(['star']) # synonym with journey.
try:
its3 = p.process(its2)
assert False
except pc.ParseError:
assert True
#first_word
p = pc.first_word('X journey there hello now')
#print(f'its={its}')
itp = p.process(its)
#print(f'itp={itp}')
assert itp.acc.value == 'hello'
#next_phrase
p = pc.next_phrase('star there now')
#print(its2)
its3 = p.process(its2)
val = [t.value for t in its3.acc]
#print(val)
assert val == ['journey roundtrip star','there','now']
#first_phrase
p = pc.first_phrase(['yes','not ever','and even','and then'])
its4 = p.process(its3)
#print(its4)
val = [t.value for t in its4.acc]
#print(val)
assert val == ['and','then']
test_next_word()
def test_until():
pass
def test_delimit():
its = mk_item_stream('(hello){there}')
its1 = pc.paren(pc.next_any_word()).process(its)
#tok = its1.acc
#print(tok)
vs = [t.value for t in its1.acc]
assert vs == ['hello']
its2 = pc.brace(pc.next_any_word()).process(its1)
assert its2.acc[0].value == 'there'
test_delimit()
def test_balanced_condition():
its = mk_item_stream('(Hi and (yet[+]) .) there (Bud) {#}.2 ')
p = pc.balanced_condition(pc.can_wordify)
its1 = p.process(its)
#print(its1.acc)
vs = [t.value for t in its1.acc]
#print(vs)
assert vs == ['(', 'hi', 'and', '(', 'yet', '[','+',']',')', '.', ')', 'there', '(', 'bud', ')', '{', '#', '}']
#test_balanced_condition()
#def show(toks):
#print('starting test_brace_semi')
def test_brace_semi():
#its = mk_item_stream('{a1 ; a2 ; a3 ; a4; a5}')
its = mk_item_stream('{Hi and ; (yet[+]) . ;there (Bud) ; {#;}.1}')
p = pc.brace_semi()
#print("starting_process")
its1 = p.process(its)
toks = its1.acc
#print('stopping_process')
#print(its1)
toks = toks[::-1][2]
#print(f'toks={toks}')
vs = [t.value for t in toks]
#print(vs)
assert vs == ['(', 'yet', '[', '+', ']', ')', '.']
test_brace_semi()
|
C#
|
GB18030
| 1,718
| 2.734375
| 3
|
[] |
no_license
|
#region using
using System;
using System.Collections.Generic;
using System.Text;
using MarvellousWorks.PracticalPattern.FlyweightPattern.ObjectPool;
using MarvellousWorks.PracticalPattern.FlyweightPattern.ObjectPool.Builder;
using MarvellousWorks.PracticalPattern.FlyweightPattern.ObjectPool.Cache;
#endregion
namespace MarvellousWorks.PracticalPattern.FlyweightPattern.ObjectPool.Dispatch
{
/// <summary>
/// ص
/// </summary>
public static class ObjectDispatch
{
/// <summary>
/// ǷԶ
/// </summary>
private static bool available = true;
/// <summary>
/// ÿʵʹȡָ͵Ķʵ
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static T Acquire<T>()
where T : PoolableBase, new()
{
available = false;
T item = null;
bool increasable;
ObjectCache cache = new ObjectCache();
if (!(cache.TryToAcquire<T>(out item, out increasable)))
{
if (increasable)
{
ObjectBuilder<T> builder = new ObjectBuilder<T>();
item = builder.BuildUp();
cache.Cache<T>(item);
}
}
available = true;
return item;
}
/// <summary>
/// ǷԶ
/// </summary>
public static bool Available
{
get { return available; }
}
}
}
|
PHP
|
UTF-8
| 7,079
| 3.28125
| 3
|
[
"MIT"
] |
permissive
|
<?php
/**
* Description of IBAN
*
* @author sven
*/
require_once( "fxISO7064_mod_97_10.php");
class IBAN {
// Makes all IBAN based attributes of an account available to the calling
// script
const IBAN = 1;
const COUNTRY = 2;
const CHECKSUM = 3;
const NATIONALBANKCODE = 4;
const ACCOUNT = 5;
/**
*
* @TODO complete IBAN COUNTRIES
*/
private $_IBAN_COUNTRIES = array("DE","NL","GR","GB","SA","CH","IL");
private $_ATTRIBUTES = array();
private $_VALIDATOR;
private function _isValid ( $IBAN ) {
// Check, whether the country is valid
if( in_array( substr( $IBAN, 0, 2 ), $this->_IBAN_COUNTRIES ) ) {
// Initiate the validator for the particular country
$VALIDATOR = $this->_chooseValidator( substr( $IBAN, 0, 2 ) );
// check, whether the IBAN "looks" correctly
if( $VALIDATOR->matchesExpression( $IBAN ) ) {
// check, whether the checksum is right
if( $VALIDATOR->isCheckSumCorrect( $IBAN ) ) {
// check, whether the IBAN is according the national rules
if( $VALIDATOR->accordingNationalRules( $IBAN ) ) {
return (TRUE );
}
}
}
}
return FALSE;
}
private function _chooseValidator( $country ) {
$VALIDATOR = null;
switch( $country ) {
case "DE":
require_once("IBAN_DE.inc");
$VALIDATOR = new IBAN_DE();
break;
default:
require_once("IBAN_DEFAULT.inc");
$VALIDATOR = new IBAN_DEFAULT( $country );
break;
}
return( $VALIDATOR );
}
/**
* The constructor allows to pass a ready IBAN.
* @param string $IBAN
* @return IBAN
*/
public function __construct( $IBAN = null ) {
if( !is_null( $IBAN ) ) {
$this->setIBAN( $IBAN );
}
}
/*public function getBIC( ) {
}*/
/**
* Returns the attribute, which stores
* @return string
* @throws InvalidArgumentException
*/
public function getIBAN( ) {
return $this->getAttribute( self::IBAN );
}
public function setIBAN( $IBAN ) {
// If I set the IBAN this way, I need to reset the other attributes
unset( $this->_ATTRIBUTES[self::NATIONALBANKCODE] );
unset( $this->_ATTRIBUTES[self::ACCOUNT] );
unset( $this->_ATTRIBUTES[self::COUNTRY] );
unset( $this->_ATTRIBUTES[self::IBAN] );
// First check if the IBAN is valid, before the routine is allowed to
// process it
if ( $this->_isValid( $IBAN ) ) {
$this->_VALIDATOR = $this->_chooseValidator( substr( $IBAN, 0, 2 ) );
$this->_ATTRIBUTES[IBAN::NATIONALBANKCODE] = $this->_VALIDATOR->extractInformation( $IBAN, IBAN::NATIONALBANKCODE );
$this->_ATTRIBUTES[IBAN::ACCOUNT] = $this->_VALIDATOR->extractInformation( $IBAN, IBAN::ACCOUNT );
$this->_ATTRIBUTES[IBAN::COUNTRY] = substr( $IBAN, 0, 2 );
$this->_ATTRIBUTES[IBAN::IBAN] = $IBAN;
}
}
public function getAttribute( $attrib ) {
if( in_array( $attrib, array( self::NATIONALBANKCODE, self::IBAN, self::CHECKSUM, self::ACCOUNT, self::COUNTRY ) ) ) {
if( in_array( $attrib, array_keys( $this->_ATTRIBUTES ) ) ) {
return( $this->_ATTRIBUTES[$attrib] );
} else {
throw new InvalidArgumentException("This information is not yet known.");
}
} else {
throw new InvalidArgumentException("You have passed an invalid attribute!");
}
}
/**
* @return boolean
* @todo It's not been implemented yet
* Return whether an IBAN, which has been passed by setIBAN, the constructor
* or is been calculated by the class itself is valid. The last mentioned
* case should always be true, if the class is doing it's job correctly.
*
* If it is not valid, than it is either not valid, or it is not been
* checked to be valid, so in case of FALSE, the validation process has
* to be fired first
*/
public function isValid( ) {
// If the user passed an IBAN, use that one for validation
if( isset( $this->_ATTRIBUTES[IBAN::IBAN] ) ) {
return( $this->_isValid( $this->_ATTRIBUTES[IBAN::IBAN] ) );
}
// If the user passed the other informations, for the IBAN creation
// use that one to determine, whether it is valid or not
/*if( !is_null( $this->_VALIDATOR ) ) {
if( $this->_VALIDATOR->areAllAttribsSet( array_keys( $this->_ATTRIBUTES ) ) ) {
$iban = $this->_VALIDATOR->genIBAN( $this->_ATTRIBUTES );
return( $this->_isValid( $iban ) );
}
}*/
else return FALSE;
}
public function setAttribute( $attrib, $value ) {
// Ensure, that the user won't set the checksum
if( $attrib == self::CHECKSUM ) {
throw new InvalidArgumentException("The checksum is a readonly attribute!");
}
// The Iban can be set on this way, but should be done with setIban
if( $attrib == self::IBAN ) {
$this->setIBAN( $value );
return;
}
if( $attrib == self::COUNTRY ) {
if( in_array( $value, $this->_IBAN_COUNTRIES ) ) {
$this->_VALIDATOR = $this->_chooseValidator( $value );
}
else { throw new InvalidArgumentException("An invalid country has been passed!", 10 ) ; }
}
if( in_array( $attrib, array( self::COUNTRY, self::ACCOUNT, self::NATIONALBANKCODE))) {
$this->_ATTRIBUTES[$attrib] = $value;
unset( $this->_ATTRIBUTES[self::IBAN] );
}
// If all informations are available, the IBAN can be generated
if( isset( $this->_VALIDATOR ) ) {
if( $this->_VALIDATOR->areAllAttribsSet( array_keys( $this->_ATTRIBUTES ) ) ) {
$this->_ATTRIBUTES[self::IBAN] = $this->_VALIDATOR->genIBAN( $this->_ATTRIBUTES );
}
}
}
}
?>
|
JavaScript
|
UTF-8
| 1,049
| 2.59375
| 3
|
[] |
no_license
|
const users = [
{
id: "3662",
name: "Emma",
email: "emma@example.com",
age: 29
},
{
id: "33272",
name: "Debra",
email: "debra@example.com"
},
{
id: "3742",
name: "Eric",
email: "eric@example.com"
}
];
const posts = [
{
id: "1",
title: "First Post",
body: "This is the first post",
published: true,
author: "3662"
},
{
id: "2",
title: "Second Post",
body: "This is the second post",
published: true,
author: "3662"
},
{
id: "3",
title: "Coming Soon",
body: "This will be amazing",
published: false,
author: "33272"
}
];
const comments = [
{
id: "111",
text: "Great post!",
author: "33272",
post: "1"
},
{
id: "222",
text: "Check out this related post",
author: "3742",
post: "1"
},
{
id: "333",
text: "Cool, thanks for sharing!",
author: "33272",
post: "2"
},
{
id: "444",
text: "Love it!",
author: "3742",
post: "2"
}
];
export default {
users,
posts,
comments
};
|
JavaScript
|
UTF-8
| 886
| 2.5625
| 3
|
[] |
no_license
|
import React from "react";
import _ from "lodash";
import "./style.css";
import FourSquare from "./FourSquare";
import Reverb from "./Reverb";
import GameOfLife from "./GameOfLife";
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
index: 1
};
this.onKeyDown = this.onKeyDown.bind(this);
}
componentWillMount() {
document.addEventListener("keydown", this.onKeyDown);
console.log("mount");
}
onKeyDown(e) {
const index = parseInt(e.key, 10);
if (index > 0) {
this.setState({ index });
}
}
render() {
switch (this.state.index) {
case 1:
return <Reverb />;
case 2:
return <GameOfLife />;
case 3:
return <FourSquare />;
default:
return <div style={{ marginTop: 10 }}>We can't count that high</div>;
}
}
}
|
TypeScript
|
UTF-8
| 2,264
| 2.78125
| 3
|
[] |
no_license
|
const merge = require('lodash.merge');
let localStorage: any;
if (typeof window !== 'undefined' && typeof window.localStorage !== 'undefined') {
localStorage = window.localStorage;
}
import { TAsyncStorage } from './types';
const API: TAsyncStorage = {
getItem: (key) => {
return API.multiGet([key])
.then(values => values[0][1]);
},
setItem: (key, value) => {
return API.multiSet([[key, value]]);
},
clear: () => {
return new Promise((resolve) => {
localStorage.clear();
resolve();
});
},
getAllKeys: () => {
return new Promise((resolve) => {
resolve(Object.keys(localStorage));
});
},
removeItem: (key) => {
return API.multiRemove([key]);
},
mergeItem: (key, value) => {
return API.multiMerge([[key, value]]);
},
multiGet: (keys) => {
return new Promise((resolve) => {
const keyValues = keys.reduce(
(acc, key) => acc.concat([[key, localStorage.getItem(key)]]),
[],
);
resolve(keyValues);
});
},
multiSet: (kvPairs) => {
return new Promise((resolve, reject) => {
const errors: any [] = [];
kvPairs.forEach(([key, value]) => {
try {
localStorage.setItem(key, value);
} catch (error) {
errors.push(error);
}
});
return errors.length > 0
? reject(errors)
: resolve();
});
},
multiMerge: (kvPairs) => {
return new Promise((resolve, reject) => {
const errors: any [] = [];
kvPairs.forEach(([key, value]) => {
const rawValue = localStorage.getItem(key);
if (!rawValue) {
return;
}
try {
localStorage.setItem(
key,
JSON.stringify(merge(JSON.parse(rawValue), JSON.parse(value))),
);
} catch (error) {
errors.push(error);
}
});
return errors.length > 0
? reject(errors)
: resolve();
});
},
multiRemove: (keys) => {
return new Promise((resolve) => {
keys.forEach(key => localStorage.removeItem(key));
resolve();
});
},
flushGetRequests: () => {
console.warn('AsyncStorage.flushGetRequests: Not supported on `web`');
},
};
export default API;
|
Java
|
UTF-8
| 586
| 2.0625
| 2
|
[
"MIT"
] |
permissive
|
package com.demo.combo;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.demo.dao.ProvinceDao;
import com.demo.model.Province;
@Service
public class ProvinceComboBean {
@Autowired
private ProvinceDao provinceDao;
List<Province> list = new ArrayList<Province>();
@PostConstruct
private List<Province> init() {
return list = provinceDao.findAll();
}
public List<Province> getList() {
return list;
}
}
|
Ruby
|
UTF-8
| 6,386
| 3.34375
| 3
|
[] |
no_license
|
require 'tuple'
RSpec.describe Tuple do
it "returns a Point with a w of 1" do
a = Tuple.for(1.0).new(4.3, -4.2, 3.1)
expect(a.x).to eq(4.3)
expect(a.y).to eq(-4.2)
expect(a.z).to eq(3.1)
expect(a.w).to eq(1.0)
expect(a).to be_a(Point)
expect(a).to_not be_a(Vector)
end
it "returns a Vector with a w of 0" do
a = Tuple.for(0.0).new(4.3, -4.2, 3.1)
expect(a.x).to eq(4.3)
expect(a.y).to eq(-4.2)
expect(a.z).to eq(3.1)
expect(a.w).to eq(0.0)
expect(a).to be_a(Vector)
expect(a).to_not be_a(Point)
end
it 'allows vectors to negate' do
a = Tuple.for(0).new(4, 5, 6)
b = -a
expect(b).to be_a(Vector)
expect(b.x).to be(-4)
expect(b.y).to be(-5)
expect(b.z).to be(-6)
end
it 'allows Vectors to multiply by a scalar value' do
vector = Tuple.for(0).new(1, -2, 4)
v1 = vector * 3.5
expect(v1).to be_a(Vector)
expect(v1.x).to eq(3.5)
expect(v1.y).to eq(-7)
expect(v1.z).to eq(14)
end
it 'allows Vectors to divide by a scalar value' do
vector = Tuple.for(0).new(7, -14, 28)
v1 = vector / 3.5
expect(v1).to be_a(Vector)
expect(v1.x).to eq(2.0)
expect(v1.y).to eq(-4.0)
expect(v1.z).to eq(8.0)
end
describe 'Vector#magnitude' do
it 'calculates the magnitude of a given vector' do
# It’s how far you would travel in a straight line
# if you were to walk from one end of the vector to the other
vector = Tuple.for(0).new(1, 2, 3)
expect(vector.magnitude).to eq Math.sqrt(14)
end
end
describe 'Vector#normalize' do
it 'returns a vector in the same direction with a magnitude of 1' do
vector = Tuple.for(0).new(1, 2, 3)
normalized = vector.normalize
expect(normalized).to be_a(Vector)
expect(normalized.magnitude).to eq 1
expect(normalized.x).to eq(1 / Math.sqrt(14))
expect(normalized.y).to eq(2 / Math.sqrt(14))
expect(normalized.z).to eq(3 / Math.sqrt(14))
end
end
describe 'Vector#dot' do
it 'returns the sum of the products of two vectors' do
v1 = Vector.new(1, 2, 3)
v2 = Vector.new(2, 3, 4)
expect(v1.dot(v2)).to eq 20
end
end
describe 'Vector#cross' do
it 'returns a new vector perpendicular to both vectors' do
v1 = Vector.new(1, 2, 3)
v2 = Vector.new(2, 3, 4)
expected1 = Vector.new(-1, 2, -1)
expected2 = Vector.new(1, -2, 1)
expect(v1.cross(v2) == expected1).to be true
expect(v2.cross(v1) == expected2).to be true
end
end
describe 'tuples module' do
it "contains a Point method that returns a point" do
a = Tuples::point(4, -4, 3)
expect(a.x).to eq(4)
expect(a.y).to eq(-4)
expect(a.z).to eq(3)
expect(a.w).to eq(1.0)
expect(a).to be_a(Point)
expect(a).to_not be_a(Vector)
end
it "contains a Vector method that returns a vector" do
a = Tuples::vector(4, -4, 3)
expect(a.x).to eq(4)
expect(a.y).to eq(-4)
expect(a.z).to eq(3)
expect(a.w).to eq(0.0)
expect(a).to be_a(Vector)
expect(a).to_not be_a(Point)
end
describe 'tuples_equal? function' do
it 'returns true if two tuples are the same type with same values' do
a = Tuple.for(1).new(1, 2, 3)
b = Tuples::point(1, 2, 3)
expect(Tuples::tuples_equal?(a, b)).to be true
expect(a == b).to be true
end
it 'returns false if two tuples are not the same type' do
a = Tuple.for(1).new(1, 2, 3)
b = Tuple.for(0).new(1, 2, 3)
# expect(Tuples::tuples_equal?(a, b)).to be false
expect(a == b).to be false
end
it 'returns false if two tuples are the same type but differing values' do
a = Tuple.for(0).new(1, 2, 3)
b = Tuple.for(0).new(1, 2, 300)
expect(Tuples::tuples_equal?(a, b)).to be false
expect(a == b).to be false
end
end
end
describe 'TupleMathable module' do
describe 'contains a + method' do
it 'adds two vectors and returns a vector' do
a = Tuple.for(0).new(1, 1, 1)
b = Tuple.for(0).new(5, 6, 7)
c = a + b
expect(c.x).to be(6)
expect(c.y).to be(7)
expect(c.z).to be(8)
expect(c).to be_a(Vector)
end
it 'takes a point and vector and returns a new point' do
a = Tuple.for(1).new(-10, -10, -10)
b = Tuple.for(0).new(5, 6, 7)
c = a + b
expect(c.x).to be(-5)
expect(c.y).to be(-4)
expect(c.z).to be(-3)
expect(c).to be_a(Point)
end
it 'takes a vector and point and returns a new point' do
a = Tuple.for(0).new(-10, -10, -10)
b = Tuple.for(1).new(5, 6, 7)
c = a + b
expect(c.x).to be(-5)
expect(c.y).to be(-4)
expect(c.z).to be(-3)
expect(c).to be_a(Point)
end
it 'takes a point and point and returns an error' do
a = Tuple.for(1).new(-10, -10, -10)
b = Tuple.for(1).new(5, 6, 7)
expect { a + b }.to raise_error(Tuple::UnsupportedTupleTypeError)
end
end
describe 'contains a - method' do
it 'subtracts two points and returns a vector from p2 to p1' do
a = Tuple.for(1).new(10, 10, 10)
b = Tuple.for(1).new(1, 2, 3)
c = a - b
expect(c).to be_a(Vector)
expect(c.x).to be(9)
expect(c.y).to be(8)
expect(c.z).to be(7)
end
it 'subtracts a vector from a point and returns a point' do
# going backwards from point
point = Tuple.for(1).new(10, 10, 10)
vector = Tuple.for(0).new(4, 5, 6)
c = point - vector
expect(c).to be_a(Point)
expect(c.x).to be(6)
expect(c.y).to be(5)
expect(c.z).to be(4)
end
it 'subtracts two vectors and returns a vector' do
v1 = Tuple.for(0).new(10, 10, 10)
v2 = Tuple.for(0).new(4, 5, 6)
c = v1 - v2
expect(c).to be_a(Vector)
expect(c.x).to be(6)
expect(c.y).to be(5)
expect(c.z).to be(4)
end
it 'raises an error if subtract a point from a vector' do
vector = Tuple.for(0).new(10, 10, 10)
point = Tuple.for(1).new(4, 5, 6)
expect { vector - point }.to raise_error(Tuple::UnsupportedTupleTypeError)
end
end
end
end
|
C++
|
UTF-8
| 1,524
| 2.734375
| 3
|
[] |
no_license
|
// Written by Barnaby Collins, 2020
#include <FastLED.h>
#define LED_PIN 2
#define NUM_LEDS 125
#define LAYER_SIZE 25
#define FPS 10
#define BRIGHTNESS 255
CRGB leds[NUM_LEDS];
unsigned long lastMillis;
int numLayers;
// stores information about the peaks to be run - for each one:
// - max height
// - time
// - current step
float peaks[LAYER_SIZE][3];
void setup() {
Serial.begin(9600);
delay(3000);
FastLED.addLeds<PL9823, LED_PIN, GRB>(leds, NUM_LEDS);
FastLED.setBrightness(BRIGHTNESS);
numLayers = NUM_LEDS / LAYER_SIZE;
}
void loop() {
unsigned long currentMillis = millis();
if (currentMillis != lastMillis && currentMillis % (int) (1000/FPS) == 0) {
lastMillis = currentMillis;
for (int i = 0; i < LAYER_SIZE; i++) {
if (peaks[i][2] >= peaks[i][1]) {
peaks[i][0] = random(10, 51)/10;
peaks[i][1] = random(FPS/2, FPS*2);
peaks[i][2] = 0;
}
int p = peaks[i][1]*2;
float a = peaks[i][0];
float x = peaks[i][2];
// https://en.wikipedia.org/wiki/Triangle_wave
float curHeight = ((2*a)/p) * abs(fmod((x - p/4), p) - p/2) - a/2;
int curLED = 0;
while (curHeight != 0) {
float value = min(curHeight, 1);
leds[25 * curLED + i] = CRGB(value * 255, value * 255, value * 255);
curHeight -= value;
curLED += 1;
}
while (curLED < numLayers) {
leds[25 * curLED + i] = CRGB(0, 0, 0);
curLED += 1;
}
peaks[i][2] += 1;
}
FastLED.show();
}
}
|
Java
|
UTF-8
| 658
| 1.875
| 2
|
[] |
no_license
|
package com.phamtan.cuu_tro.util.mail;
import com.phamtan.base.email.data_structure.EmailContentData;
import com.phamtan.base.email.request.EmailRequest;
import com.phamtan.base.email.service.EmailService;
import com.phamtan.base.enumeration.EmailEnum;
import lombok.AllArgsConstructor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.Arrays;
@Service
@AllArgsConstructor
public class GmailService {
private final EmailService emailService;
@Async("asyncThreadPool")
public void sendEmail(EmailRequest emailRequest){
emailService.sendEmail(emailRequest);
}
}
|
Markdown
|
UTF-8
| 2,264
| 2.8125
| 3
|
[] |
no_license
|
<h1>Sprint 5</h1>
<h2>Tarefas Desenvolvidas:</h2>
<li>Indicador de pontualidade no pagamento por cartão de crédito</li>
<li>Desenvolvimento da Interface Gráfica</li>
<li>Programação das funcionalidades do software</li>
<h3>Indicador de Pontualidade</h3>
Pontualidade de pagamento por pessoa: indica se a pessoa física está em dia ou não com o vencimento da fatura.
Dados utilizados: na tabela de pagamento, contém dados de crédito, onde será verificado a data de vencimento da fatura com a data de pagamento do cliente.
Cálculo: quanto maior o déficit de atraso menor a pontuação.
<li>Antes da data de vencimento = nota 5</li>
<li>Pagamento na data de vencimento = nota 4 </li>
<li>Entre 1 a 7 dias de atraso = nota 3 </li>
<li>Entre 8 a 14 dias de atraso = nota 2 </li>
<li>Acima de 14 dias de atraso = nota 1</li>
Por meio do indicador de pontualidade, classificamos os clientes conforme todos os pagamentos efetuados de forma individual. Assim, pontuando confome a data de pagamento, gerando uma média sobre o total de pagamentos realizados, para assim qualificar os clientes e gerar uma pontuação geral para os grupos de regiões do Brasil, com o intuito de indicar quais as regiões com melhor índice de pontualidade no pagamento por cartão de crédito e qual o perfil deste consumidor.

<h3>Gráfico de Distribuição de Clientes por Estados</h3>
Por meio do gráfico, mostrar os estados com mais clientes que utilizam o cartão de crédito e assim determinar qual região seria interessante investir.

<h3>Gráfico com perfil do cliente com melhor indicador de pontualidade no pagamento</h3>
Mostra o perfil do cliente que tem o pagamento das faturas do cartão em dia, mostrando sua faixa etária e sexo do cliente. Com o objetivo de aperfeiçoar as campanhas de marketing para determinado consumidor.

|
Java
|
UTF-8
| 2,305
| 2.59375
| 3
|
[] |
no_license
|
package com.hxy.timing.timingdome.Tasks;
import com.hxy.timing.timingdome.mail.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* CRON表达式 含义
* <p>
* "0 0 12 * * ?" 每天中午十二点触发
* "0 15 10 ? * *" 每天早上10:15触发
* "0 15 10 * * ?" 每天早上10:15触发
* "0 15 10 * * ? *" 每天早上10:15触发
* "0 15 10 * * ? 2005" 2005年的每天早上10:15触发
* "0 * 14 * * ?" 每天从下午2点开始到2点59分每分钟一次触发
* "0 0/5 14 * * ?" 每天从下午2点开始到2:55分结束每5分钟一次触发
* "0 0/5 14,18 * * ?" 每天的下午2点至2:55和6点至6点55分两个时间段内每5分钟一次触发
* "0 0-5 14 * * ?" 每天14:00至14:05每分钟一次触发
* "0 10,44 14 ? 3 WED" 三月的每周三的14:10和14:44触发
* "0 15 10 ? * MON-FRI" 每个周一、周二、周三、周四、周五的10:15触发
*
* @Scheduled(fixedRate = 5000) :上一次开始执行时间点之后5秒再执行
* @Scheduled(fixedDelay = 5000) :上一次执行完毕时间点之后5秒再执行
* @Scheduled(initialDelay=1000, fixedRate=5000) :第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次
* /* @Scheduled(cron="
*//*5 * * * * *") :通过cron表达式定义规则*/
/**
* 定时发送邮件
*/
@Component
public class ScheduledTasks {
@Autowired
private MailService mailService;
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");
//private String to="hxyHelloWorld@163.com";
private String to = "13095536731@163.com";
//@Scheduled(fixedRate = 5000)
@Scheduled(cron = "0 47 12 ? * *")
public void reportCurrentTime() {
for (int i = 0; i < 7; i++) {
if (i == 5) {
String str = "现在时间是:" + dateFormat.format(new Date());
mailService.sendSimpleMail(to,"主题:测试邮件", "收到邮件: "+str);
System.out.println(str + i);
return;
}
}
System.out.println("条件不满足");
}
}
|
Python
|
UTF-8
| 356
| 3.015625
| 3
|
[] |
no_license
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import cgi
form = cgi.FieldStorage()
print("Content-type: text/html\n")
html = """
<title>CGI script</title>
<h1>Greetings</h1>
<hr>
<p>%s</p>
<p>The input date is: %s</p>
<p>The input city is: %s</p>
<hr>"""
date = form['date'].value
city = form['citys'].value
print(html % ("hello, what's up?", date, city))
|
Java
|
UTF-8
| 427
| 1.625
| 2
|
[
"MIT"
] |
permissive
|
package org.ekstep.graph.model;
import org.ekstep.common.dto.Request;
public interface ICollection extends INode {
void addMember(Request request);
void addMembers(Request request);
void removeMember(Request request);
void removeMembers(Request request);
void getMembers(Request request);
void isMember(Request request);
void getCardinality(Request request);
}
|
PHP
|
UTF-8
| 24,799
| 2.671875
| 3
|
[] |
no_license
|
<?php
/**
* This file used for adding fields to the products category taxonomy page and saving those values correctly :)
*
* @package wp-e-commerce
* @since 3.8
* @todo UI needs a lot of loving - lots of padding issues, if we have these boxes, they should be sortable, closable, hidable, etc.
*/
function wpsc_ajax_set_variation_order(){
global $wpdb;
$sort_order = $_POST['sort_order'];
$parent_id = $_POST['parent_id'];
$result = true;
foreach( $sort_order as $key => $value ) {
if ( empty( $value ) ) {
continue;
}
$value = preg_replace( '/[^0-9]/', '', $value );
if ( ! wpsc_update_meta( $value, 'sort_order', $key, 'wpsc_variation' ) ) {
$result = false;
}
}
}
/**
* WP eCommerce edit and add product category page functions
*
* These are the main WPSC Admin functions
*
* @package wp-e-commerce
* @since 3.7
*/
function wpsc_ajax_set_category_order(){
global $wpdb;
$sort_order = $_POST['sort_order'];
$parent_id = $_POST['parent_id'];
$result = true;
foreach ( $sort_order as $key=>$value ){
if ( empty( $value ) )
continue;
$value = preg_replace( '/[^0-9]/', '', $value );
if ( ! wpsc_update_meta( $value, 'sort_order', $key, 'wpsc_category' ) )
$result = false;
}
}
add_filter( 'manage_edit-wpsc_product_category_columns', 'wpsc_custom_category_columns' );
add_filter( 'manage_wpsc_product_category_custom_column', 'wpsc_custom_category_column_data', 10, 3);
add_action( 'wpsc_product_category_add_form_fields', 'wpsc_admin_category_forms_add' ); // After left-col
add_action( 'wpsc_product_category_edit_form_fields', 'wpsc_admin_category_forms_edit' ); // After left-col
add_action( 'created_wpsc_product_category', 'wpsc_save_category_set', 10 , 2 ); //After created
add_action( 'edited_wpsc_product_category', 'wpsc_save_category_set', 10 , 2 ); //After saved
/**
* wpsc_custom_category_columns
* Adds images column to category column.
* @internal Don't feel handle column is necessary, but you would add it here if you wanted to
* @param (array) columns | Array of columns assigned to this taxonomy
* @return (array) columns | Modified array of columns
*/
function wpsc_custom_category_columns( $columns ) {
// Doing it this funny way to ensure that image stays in far left, even if other items are added via plugin.
unset( $columns["cb"] );
$custom_array = array(
'cb' => '<input type="checkbox" />',
'image' => __( 'Image', 'wpsc' )
);
$columns = array_merge( $custom_array, $columns );
return $columns;
}
/**
* Custom Category Column Data
*
* Adds images to the custom category column.
*
* @param string $string Column output.
* @param string $column_name Column name.
* @param string $term_id Term ID.
* @return string Updated column output.
*/
function wpsc_custom_category_column_data( $string, $column_name, $term_id ) {
if ( 'image' == $column_name ) {
$term = get_term_by( 'id', $term_id, 'wpsc_product_category' );
$image = wpsc_get_categorymeta( $term_id, 'image' );
$format = '<img src="%s" title="%s" alt="%2$s" width="30" height="30" />';
if ( ! empty( $image ) ) {
$string = sprintf( $format, WPSC_CORE_IMAGES_URL . $image, esc_attr( $term->name ) );
} else {
$string = sprintf( $format, WPSC_CORE_IMAGES_URL . '/no-image-uploaded.gif', esc_attr( $term->name ) );
}
}
return $string;
}
/**
* wpsc_admin_get_category_array
* Recursively step through the categories and return it in a clean multi demensional array
* for use in other list functions
* @param int $parent_id
*/
function wpsc_admin_get_category_array( $parent_id = null ){
global $wpdb;
$orderedList = array();
if ( ! isset( $parent_id ) )
$parent_id = 0;
$category_list = get_terms( 'wpsc_product_category', 'hide_empty=0&parent=' . $parent_id );
if ( ! is_array( $category_list ) ) {
return false;
}
foreach ( $category_list as $category ) {
$category_order = wpsc_get_categorymeta( $category->term_id, 'order' );
$category_image = wpsc_get_categorymeta( $category->term_id, 'image' );
if ( ! isset( $category_order ) || $category_order == 0 )
$category_order = ( count( $orderedList ) + 1 );
print "<!-- setting category Order number to " . $category_order . "-->";
$orderedList[$category_order]['id'] = $category->term_id;
$orderedList[$category_order]['name'] = $category->name;
$orderedList[$category_order]['image'] = $category_image;
$orderedList[$category_order]['parent_id'] = $parent_id;
$orderedList[$category_order]['children'] = wpsc_admin_get_category_array( $category->term_id );
}
ksort( $orderedList );
return $orderedList;
}
/**
* wpsc_admin_category_group_list, prints the left hand side of the add categories page
* nothing returned
*/
function wpsc_admin_category_forms_add() {
global $wpdb;
$category_value_count = 0;
$display_type = isset( $category['display_type'] ) ? $category['display_type'] : '';
?>
<h3><?php esc_html_e('Advanced Store Settings', 'wpsc'); ?></h3>
<h4><?php esc_html_e('Presentation Settings', 'wpsc'); ?></h4>
<p class='description'><?php esc_html_e( 'These settings override the general presentation settings found in Settings > Store > Presentation.', 'wpsc' ); ?></p>
<div style="margin: 15px 0 15px 0">
<label for='image'><?php esc_html_e( 'Category Image' , 'wpsc' ); ?></label>
<input type='file' name='image' value='' />
</div>
<div class="form-field">
<label for='display_type'><?php esc_html_e( 'Product Display', 'wpsc' ); ?></label>
<select name='display_type'>
<option value='default'<?php checked( $display_type, 'default' ); ?>><?php esc_html_e('Default View', 'wpsc'); ?></option>
<option value='list'<?php disabled( _wpsc_is_display_type_supported( 'list' ), false ); ?><?php checked( $display_type, 'list' ); ?>><?php esc_html_e('List View', 'wpsc'); ?></option>
<option value='grid'<?php disabled( _wpsc_is_display_type_supported( 'grid' ), false ); ?><?php checked( $display_type, 'grid' ); ?>><?php esc_html_e('Grid View', 'wpsc'); ?></option>
</select>
</div>
<?php if ( function_exists( "getimagesize" ) ) : ?>
<div class="form-field">
<?php esc_html_e( 'Thumbnail Size', 'wpsc' ); ?>
<fieldset class="wpsc-width-height-fields">
<legend class="screen-reader-text"><span><?php esc_html_e( 'Thumbnail Size', 'wpsc' ); ?></span></legend>
<label for="image_width"><?php esc_html_e( 'Width', 'wpsc' ); ?></label>
<input name="image_width" type="number" step="1" min="0" id="image_width" value="<?php if ( isset( $category['image_width'] ) ) echo esc_attr( $category['image_width'] ); ?>" class="small-text" style="width: 70px">
<label for="large_size_h"><?php esc_html_e( 'Height', 'wpsc' ); ?></label>
<input name="image_height" type="number" step="1" min="0" id="image_height" value="<?php if ( isset( $category['image_height'] ) ) echo esc_attr( $category['image_height'] ); ?>" class="small-text" style="width: 70px">
</fieldset>
</div>
<?php endif;?>
<!-- START OF TARGET MARKET SELECTION -->
<?php
$category_id = '';
if ( isset( $_GET['tag_ID'] ) ) {
$category_id = absint( $_GET['tag_ID'] );
}
$countrylist = WPSC_Countries::get_countries_array( true, true );
$selectedCountries = wpsc_get_meta( $category_id, 'target_market', 'wpsc_category' );
?>
<h4><?php esc_html_e( 'Restrict to Target Markets', 'wpsc' )?></h4>
<div class='form-field'>
<?php if ( wpsc_is_suhosin_enabled() ) : ?>
<em><?php esc_html_e( "The Target Markets feature has been disabled because you have the Suhosin PHP extension installed on this server. If you need to use the Target Markets feature then disable the suhosin extension, if you can not do this, you will need to contact your hosting provider.", 'wpsc' ); ?></em>
<?php else: ?>
<div class='multiple-select-container'>
<span><?php esc_html_e( 'Select', 'wpsc' ); ?> <a href='' class='wpsc_select_all'><?php esc_html_e( 'All', 'wpsc' ); ?></a> <a href='' class='wpsc_select_none'><?php esc_html_e( 'None', 'wpsc' ); ?></a></span><br />
<div id='resizeable' class='ui-widget-content multiple-select'>
<?php foreach( $countrylist as $country ): ?>
<?php if ( in_array( $country['id'], (array)$selectedCountries ) ): ?>
<input type='checkbox' name='countrylist2[]' id='countrylist2-<?php echo $country['id']; ?>' value='<?php echo $country['id']; ?>' checked='<?php echo $country['visible']; ?>' />
<label for="countrylist2-<?php echo $country['id']; ?>"><?php esc_html_e( $country['country'] ); ?></label><br />
<?php else: ?>
<input type='checkbox' name='countrylist2[]' id='countrylist2-<?php echo $country['id']; ?>' value='<?php echo $country['id']; ?>' />
<label for="countrylist2-<?php echo $country['id']; ?>"><?php esc_html_e( $country['country'] ); ?></label><br />
<?php endif; ?>
<?php endforeach; ?>
</div>
</div>
<span class='wpscsmall description'><?php esc_html_e( 'Select the markets you are selling this category to.', 'wpsc' ); ?><span>
<?php endif; ?>
</div>
<!-- Checkout settings -->
<h4><?php esc_html_e( 'Checkout Settings', 'wpsc' ); ?></h4>
<?php
if ( ! isset( $category['term_id'] ) ) $category['term_id'] = '';
$used_additonal_form_set = wpsc_get_categorymeta( $category['term_id'], 'use_additional_form_set' );
?>
<div class='form-field'>
<label for="use_additional_form_set"><?php esc_html_e( 'Category requires additional checkout form fields', 'wpsc' ); ?></label>
<select name='use_additional_form_set'>
<option value=''><?php esc_html_e( 'None', 'wpsc' ); ?></option>
<?php
$checkout_sets = get_option( 'wpsc_checkout_form_sets' );
unset( $checkout_sets[0] );
foreach ( (array)$checkout_sets as $key => $value ) {
$selected_state = "";
if ( $used_additonal_form_set == $key )
$selected_state = "selected='selected'";
?>
<option <?php echo $selected_state; ?> value='<?php echo $key; ?>'><?php echo esc_html( $value ); ?></option>
<?php
}
?>
</select>
</div>
<?php $uses_billing_address = (bool)wpsc_get_categorymeta( $category['term_id'], 'uses_billing_address' ); ?>
<div>
<label><?php esc_html_e( 'Address to calculate shipping with', 'wpsc' ); ?></label>
<label><input type="radio" value="0" name="uses_billing_address" <?php checked( $uses_billing_address, 0 ); ?> /> <?php esc_html_e( 'Shipping Address (default)', 'wpsc' ); ?></label>
<label><input type="radio" value="1" name="uses_billing_address" <?php checked( $uses_billing_address, 1 ); ?> /> <?php esc_html_e( 'Billing Address', 'wpsc' ); ?></label>
<p class='description'><?php esc_html_e( 'Products in this category will use the address specified to calculate shipping costs.', 'wpsc' ); ?></p>
</div>
<table class="category_forms">
<tr>
</tr>
</table>
<?php
}
/**
* Check whether a display type (such as grid, list) is supported.
*
* @since 3.8.9
* @access private
* @param string $display_type Display type
* @return bool Return true if display type is supported.
*/
function _wpsc_is_display_type_supported( $display_type ) {
$callback = 'product_display_' . $display_type;
return function_exists( $callback );
}
function wpsc_admin_category_forms_edit() {
global $wpdb;
$category_value_count = 0;
$category_name = '';
$category = array();
$category_id = absint( $_REQUEST["tag_ID"] );
$category = get_term( $category_id, 'wpsc_product_category', ARRAY_A );
$category['nice-name'] = wpsc_get_categorymeta( $category['term_id'], 'nice-name' );
$category['description'] = wpsc_get_categorymeta( $category['term_id'], 'description' );
$category['image'] = wpsc_get_categorymeta( $category['term_id'], 'image' );
$category['fee'] = wpsc_get_categorymeta( $category['term_id'], 'fee' );
$category['active'] = wpsc_get_categorymeta( $category['term_id'], 'active' );
$category['order'] = wpsc_get_categorymeta( $category['term_id'], 'order' );
$category['display_type'] = wpsc_get_categorymeta( $category['term_id'], 'display_type' );
$category['image_height'] = wpsc_get_categorymeta( $category['term_id'], 'image_height' );
$category['image_width'] = wpsc_get_categorymeta( $category['term_id'], 'image_width' );
$category['use_additional_form_set'] = wpsc_get_categorymeta( $category['term_id'], 'use_additional_form_set' );
?>
<tr>
<td colspan="2">
<h3><?php esc_html_e( 'Advanced Store Settings', 'wpsc' ); ?></h3>
<h4><?php esc_html_e( 'Shortcodes and Template Tags', 'wpsc' ); ?></h4>
<p class='description'><?php esc_html_e( 'These settings override the general presentation settings found in Settings > Store > Presentation.', 'wpsc' ); ?></p>
</td>
</tr>
<tr class="form-field">
<th scope="row" valign="top">
<label for="display_type"><?php esc_html_e( 'Catalog View', 'wpsc' ); ?></label>
</th>
<td>
<?php
$display_type = isset( $category['display_type'] ) ? $category['display_type'] : '';
?>
<select name='display_type'>
<option value='default'<?php selected( $display_type, 'default' ); ?>><?php esc_html_e( 'Default View', 'wpsc' ); ?></option>
<option value='list'<?php disabled( _wpsc_is_display_type_supported( 'list' ), false ); ?><?php selected( $display_type, 'list' ); ?>><?php esc_html_e('List View', 'wpsc'); ?></option>
<option value='grid' <?php disabled( _wpsc_is_display_type_supported( 'grid' ), false ); ?><?php selected( $display_type, 'grid' ); ?>><?php esc_html_e( 'Grid View', 'wpsc' ); ?></option>
</select><br />
</td>
</tr>
<tr class="form-field">
<th scope="row" valign="top">
<label for="image"><?php esc_html_e( 'Category Image', 'wpsc' ); ?></label>
</th>
<td>
<?php
$category_image = wpsc_category_image( $category['term_id'] );
if ( $category_image )
echo '<p><img src=' . esc_url( $category_image ) . ' alt="' . esc_attr( $category['name'] ) . '" title="' . esc_attr( $category['name'] ) . '" class="wpsc_category_image" /></p>';
?>
<input type='file' name='image' value='' /><br />
<label><input type='checkbox' name='deleteimage' class="wpsc_cat_box" value='1' /><?php esc_html_e( 'Delete Image', 'wpsc' ); ?></label><br/>
<span class="description"><?php esc_html_e( 'You can set an image for the category here. If one exists, check the box to delete.', 'wpsc' ); ?></span>
</td>
</tr>
<?php if ( function_exists( "getimagesize" ) ) : ?>
<tr class="form-field">
<th scope="row" valign="top">
<label for="image"><?php esc_html_e( 'Thumbnail Size', 'wpsc' ); ?></label>
</th>
<td>
<fieldset class="wpsc-width-height-fields">
<legend class="screen-reader-text"><span><?php esc_html_e( 'Thumbnail Size', 'wpsc' ); ?></span></legend>
<label for="image_width"><?php esc_html_e( 'Width', 'wpsc' ); ?></label>
<input name="image_width" type="number" step="1" min="0" id="image_width" value="<?php if ( isset( $category['image_width'] ) ) echo esc_attr( $category['image_width'] ); ?>" class="small-text">
<label for="large_size_h"><?php esc_html_e( 'Height', 'wpsc' ); ?></label>
<input name="image_height" type="number" step="1" min="0" id="image_height" value="<?php if ( isset( $category['image_height'] ) ) echo esc_attr( $category['image_height'] ); ?>" class="small-text">
</fieldset>
</td>
</tr>
<?php endif; // 'getimagesize' condition ?>
<tr>
<td colspan="2"><h4><?php esc_html_e( 'Shortcodes and Template Tags', 'wpsc' ); ?></h4></td>
</tr>
<tr class="form-field">
<th scope="row" valign="top">
<label for="image"><?php esc_html_e( 'Display Category Shortcode', 'wpsc' ); ?></label>
</th>
<td>
<code>[wpsc_products category_url_name='<?php echo $category["slug"]; ?>']</code><br />
<span class="description"><?php esc_html_e( 'Shortcodes are used to display a particular category or group within any WordPress page or post.', 'wpsc' ); ?></span>
</td>
</tr>
<tr class="form-field">
<th scope="row" valign="top">
<label for="image"><?php esc_html_e( 'Display Category Template Tag', 'wpsc' ); ?></label>
</th>
<td>
<code><?php echo wpsc_display_products_page( array( 'category_url_name' => '<?php echo $category["slug"]; ?>' ) ); ?></code><br />
<span class="description"><?php esc_html_e( 'Template tags are used to display a particular category or group within your theme / template.', 'wpsc' ); ?></span>
</td>
</tr>
<!-- START OF TARGET MARKET SELECTION -->
<tr>
<td colspan="2">
<h4><?php esc_html_e( 'Target Market Restrictions', 'wpsc' ); ?></h4>
</td>
</tr>
<?php
$countrylist = WPSC_Countries::get_countries_array( true, true );
$selectedCountries = wpsc_get_meta( $category_id,'target_market','wpsc_category' );
?>
<tr>
<th scope="row" valign="top">
<label for="image"><?php esc_html_e( 'Target Markets', 'wpsc' ); ?></label>
</th>
<td>
<?php if ( wpsc_is_suhosin_enabled() ) : ?>
<em><?php esc_html_e( 'The Target Markets feature has been disabled because you have the Suhosin PHP extension installed on this server. If you need to use the Target Markets feature, then disable the suhosin extension. If you can not do this, you will need to contact your hosting provider.','wpsc' ); ?></em>
<?php else : ?>
<span><?php esc_html_e( 'Select', 'wpsc' ); ?>: <a href='' class='wpsc_select_all'><?php esc_html_e( 'All', 'wpsc' ); ?></a> <a href='' class='wpsc_select_none'><?php esc_html_e( 'None', 'wpsc' ); ?></a></span><br />
<div id='resizeable' class='ui-widget-content multiple-select'>
<?php foreach( $countrylist as $country ) {
if ( in_array( $country['id'], (array)$selectedCountries ) ) {
?>
<input type='checkbox' name='countrylist2[]' id='countrylist2-<?php echo $country['id']; ?>' value='<?php echo $country['id']; ?>' checked='<?php echo $country['visible']; ?>' />
<label for="countrylist2-<?php echo $country['id']; ?>"><?php esc_html_e( $country['country'] ); ?></label><br />
<?php
} else {
?>
<input type='checkbox' name='countrylist2[]' id='countrylist2-<?php echo $country['id']; ?>' value='<?php echo $country['id']; ?>' />
<label for="countrylist2-<?php echo $country['id']; ?>"><?php esc_html_e( $country['country'] ); ?></label><br />
<?php
}
} ?>
</div>
<?php endif; ?><br />
<span class="description"><?php esc_html_e( 'Select the markets you are selling this category to.', 'wpsc' ); ?></span>
</td>
</tr>
<!-- Checkout settings -->
<tr>
<td colspan="2">
<h4><?php esc_html_e( 'Checkout Settings', 'wpsc' ); ?></h4>
</td>
</tr>
<?php
if ( !isset( $category['term_id'] ) )
$category['term_id'] = '';
$used_additonal_form_set = wpsc_get_categorymeta( $category['term_id'], 'use_additional_form_set' );
$checkout_sets = get_option('wpsc_checkout_form_sets');
unset($checkout_sets[0]);
$uses_billing_address = (bool)wpsc_get_categorymeta( $category['term_id'], 'uses_billing_address' );
?>
<tr class="form-field">
<th scope="row" valign="top">
<label for="image"><?php esc_html_e( 'Category requires additional checkout form fields', 'wpsc' ); ?></label>
</th>
<td>
<select name='use_additional_form_set'>
<option value=''><?php esc_html_e( 'None', 'wpsc' ); ?></option>
<?php
foreach( (array) $checkout_sets as $key => $value ) {
$selected_state = "";
if ( $used_additonal_form_set == $key ) {
$selected_state = "selected='selected'";
} ?>
<option <?php echo $selected_state; ?> value='<?php echo $key; ?>'><?php echo esc_html( $value ); ?></option>
<?php
}
?>
</select>
</td>
</tr>
<tr class="form-field">
<th scope="row" valign="top">
<label><?php esc_html_e( 'Address to calculate shipping with', 'wpsc' ); ?></label>
</th>
<td>
<label><input type="radio" class="wpsc_cat_box" value="0" name="uses_billing_address" <?php echo ( ( $uses_billing_address != true ) ? 'checked="checked"' : '' ); ?> /> <?php esc_html_e( 'Shipping Address (default)', 'wpsc' ); ?></label><br />
<label><input type="radio" class="wpsc_cat_box" value="1" name="uses_billing_address" <?php echo ( ( $uses_billing_address == true ) ? 'checked="checked"' : '' ); ?> /> <?php esc_html_e( 'Billing Address', 'wpsc' ); ?></label>
<p class='description'><?php esc_html_e( 'Products in this category will use the address specified to calculate shipping costs.', 'wpsc' ); ?></p>
</td>
</tr>
<?php
}
/**
* wpsc_save_category_set, Saves the category set data
* @param nothing
* @return nothing
*/
function wpsc_save_category_set( $category_id, $tt_id ) {
global $wpdb;
if ( ! empty( $_POST ) ) {
/* Image Processing Code*/
if ( ! empty( $_FILES['image'] ) && preg_match( "/\.(gif|jp(e)*g|png){1}$/i", $_FILES['image']['name'] ) ) {
if ( function_exists( "getimagesize" ) ) {
if ( isset( $_POST['width'] ) && ( (int) $_POST['width'] > 10 && (int) $_POST['width'] < 512 ) && ( (int)$_POST['height'] > 10 && (int)$_POST['height'] < 512 ) ) {
$width = (int) $_POST['width'];
$height = (int) $_POST['height'];
image_processing( $_FILES['image']['tmp_name'], ( WPSC_CATEGORY_DIR.$_FILES['image']['name'] ), $width, $height, 'image' );
} else {
image_processing( $_FILES['image']['tmp_name'], ( WPSC_CATEGORY_DIR.$_FILES['image']['name'] ), null, null, 'image' );
}
$image = esc_sql( $_FILES['image']['name'] );
} else {
$new_image_path = ( WPSC_CATEGORY_DIR.basename($_FILES['image']['name'] ) );
move_uploaded_file( $_FILES['image']['tmp_name'], $new_image_path );
$stat = stat( dirname( $new_image_path ) );
$perms = $stat['mode'] & 0000666;
@ chmod( $new_image_path, $perms );
$image = esc_sql( $_FILES['image']['name'] );
}
} else {
$image = '';
}
//Good to here
if ( isset( $_POST['tag_ID'] ) ) {
//Editing
$category_id = (int) $_POST['tag_ID'];
$category = get_term_by( 'id', $category_id, 'wpsc_product_category' );
$url_name = $category->slug;
}
if ( isset( $_POST['deleteimage'] ) && $_POST['deleteimage'] == 1 ) {
wpsc_delete_categorymeta( $category_id, 'image' );
} else if ( $image != '' ) {
wpsc_update_categorymeta( $category_id, 'image', $image );
}
if ( ! empty( $_POST['height'] ) && is_numeric( $_POST['height'] ) && ! empty( $_POST['width'] ) && is_numeric( $_POST['width'] ) && $image == null ) {
$imagedata = wpsc_get_categorymeta( $category_id, 'image' );
if ( $imagedata != null ) {
$height = (int) $_POST['height'];
$width = (int) $_POST['width'];
$imagepath = WPSC_CATEGORY_DIR . $imagedata;
$image_output = WPSC_CATEGORY_DIR . $imagedata;
image_processing( $imagepath, $image_output, $width, $height );
}
}
wpsc_update_categorymeta( $category_id, 'fee', '0' );
wpsc_update_categorymeta( $category_id, 'active', '1' );
wpsc_update_categorymeta( $category_id, 'order', '0' );
if ( isset( $_POST['display_type'] ) ) {
wpsc_update_categorymeta( $category_id, 'display_type', esc_sql( stripslashes( $_POST['display_type'] ) ) );
}
if ( isset( $_POST['image_height'] ) ) {
wpsc_update_categorymeta( $category_id, 'image_height', (int) $_POST['image_height'] );
}
if ( isset( $_POST['image_width'] ) ) {
wpsc_update_categorymeta( $category_id, 'image_width', (int) $_POST['image_width'] );
}
if ( ! empty( $_POST['use_additional_form_set'] ) ) {
wpsc_update_categorymeta( $category_id, 'use_additional_form_set', $_POST['use_additional_form_set'] );
} else {
wpsc_delete_categorymeta( $category_id, 'use_additional_form_set' );
}
if ( ! empty( $_POST['uses_billing_address'] ) ) {
wpsc_update_categorymeta( $category_id, 'uses_billing_address', 1 );
$uses_additional_forms = true;
} else {
wpsc_update_categorymeta( $category_id, 'uses_billing_address', 0 );
$uses_additional_forms = false;
}
if ( ! empty( $_POST['countrylist2'] ) && ( $category_id > 0 ) ) {
$AllSelected = false;
$countryList = $wpdb->get_col( "SELECT `id` FROM `" . WPSC_TABLE_CURRENCY_LIST . "`" );
if ( $AllSelected != true ){
$posted_countries = array_map( 'intval', $_POST['countrylist2'] );
$unselectedCountries = array_diff( $countryList, $posted_countries );
//find the countries that are selected
$selectedCountries = array_intersect( $countryList, $posted_countries );
wpsc_update_categorymeta( $category_id, 'target_market', $selectedCountries );
}
} elseif ( ! isset( $_POST['countrylist2'] ) ){
wpsc_update_categorymeta( $category_id, 'target_market', '' );
$AllSelected = true;
}
}
}
?>
|
C
|
UTF-8
| 3,445
| 2.703125
| 3
|
[] |
no_license
|
#pragma once
struct SegmentOverlapResult
{
float collisionParam;
bool overlapped;
};
struct OverlapResult
{
vec normal;
vec collisionPoint;
float penetration;
};
SegmentOverlapResult test_circle_segment_overlap(vec circleCenter, float circleRadius, vec aabbTopLeft, vec aabbBottomRight)
{
SegmentOverlapResult res;
float paddleWidth = aabbBottomRight.x - aabbTopLeft.x;
float distanceToPaddle = aabbTopLeft.x - circleCenter.x;
vec toPaddle = aabbTopLeft - circleCenter;
float a = paddleWidth * paddleWidth;
float b = 2 * distanceToPaddle * paddleWidth;
float c = vec_dot(toPaddle, toPaddle) - circleRadius * circleRadius;
float collisionParam = -1.0f;
float discriminant = b*b - 4 * a*c;
if (discriminant >= 0)
{
discriminant = sqrt(discriminant);
float t1 = (-b - discriminant) / (2 * a);
float t2 = (-b + discriminant) / (2 * a);
if (t1 >= 0 && t1 <= 1)
{
collisionParam = t1;
}
if (t2 >= 0 && t2 <= 1)
{
collisionParam = t2;
}
}
res.collisionParam = collisionParam;
if (collisionParam >= 0)
{
res.overlapped = true;
}
else
{
res.overlapped = false;
}
return res;
}
// Taken from https://gamedevelopment.tutsplus.com/tutorials/how-to-create-a-custom-2d-physics-engine-the-basics-and-impulse-resolution--gamedev-6331
bool test_circle_aabb_overlap(OverlapResult& result, vec circleCenter, float circleRadius, vec aabbMin, vec aabbMax, bool bTestOnly)
{
result = {};
vec halfExtent = (aabbMax - aabbMin) * 0.5f;
vec aabbCenter = aabbMin + halfExtent;
vec toCircle = circleCenter - aabbCenter;
vec closestDistanceToCircleFromAabbCenter
{
clamp(toCircle.x, -halfExtent.x, halfExtent.x),
clamp(toCircle.y, -halfExtent.y, halfExtent.y)
};
bool circleCenterInsideAabb = false;
if (toCircle == closestDistanceToCircleFromAabbCenter)
{
circleCenterInsideAabb = true;
// Find closest axis
if (abs(toCircle.x) > abs(toCircle.y))
{
// Clamp to closest extent
if (closestDistanceToCircleFromAabbCenter.x > 0)
closestDistanceToCircleFromAabbCenter.x = halfExtent.x;
else
closestDistanceToCircleFromAabbCenter.x = -halfExtent.x;
}
// y axis is shorter
else
{
// Clamp to closest extent
if (closestDistanceToCircleFromAabbCenter.y > 0)
closestDistanceToCircleFromAabbCenter.y = halfExtent.y;
else
closestDistanceToCircleFromAabbCenter.y = -halfExtent.y;
}
}
result.normal = toCircle - closestDistanceToCircleFromAabbCenter;
float d = vec_lengthsq(result.normal);
float r = circleRadius;
// Early out of the radius is shorter than distance to closest point and
// Circle not inside the AABB
if (d > r* r && !circleCenterInsideAabb)
return false;
// Avoided sqrt until we needed
d = sqrt(d);
result.normal /= d;
// Collision normal needs to be flipped to point outside if circle was
// inside the AABB
if (circleCenterInsideAabb)
{
result.normal = vec_normalize(-toCircle);
result.penetration = r - d;
}
else
{
result.penetration = d - r;
}
return true;
}
|
Markdown
|
UTF-8
| 732
| 3.015625
| 3
|
[] |
no_license
|
# 文法
## 0型文法
设G=(Vn,Vt,P,S),若果它的每个产生式α→β是这样的一种建构:a∈(Vn∪Vt)*,且至少含有一个`非终结符`而β∈(V
n∪Vt),则G是一个0型文法,也称`短语文法`。处理能力相当于图灵机,并且递归可枚举。
## 1型文法
也叫`上下文有关文法`,对应线性有界自动机。在0型文法基础上每一个α→β都有|β|>=|α|,有一个特例,a→ ,也满足1型文法
## 2型文法
也叫`上下文无关文法`,对于下推自动机。在1型文法中满足每一个α→β都有α是费终结符
## 3型文法
也叫`正规文法`,对应`有限状态自动机`,在2型文法的基础上满足A→α|αB(右线性)或A→α|Bα(左线性)
|
Java
|
UTF-8
| 2,719
| 3.046875
| 3
|
[] |
no_license
|
package com.cbergoon.algorithm.search;
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
import com.cbergoon.exception.ImproperGraphBuildException;
import com.cbergoon.exception.InvalidVertexIndexException;
import com.cbergoon.graph.Graph;
import com.cbergoon.graph.model.EdgeBase;
import com.cbergoon.graph.model.VertexBase;
/**
* Depth first search implementation for the graph. Search provides
* an extended functionality set to allow for no target and start-less
* (no entry point) searches.
* @author cbergoon
*
* @param <V>
* @param <E>
*/
public class DFS<V extends VertexBase, E extends EdgeBase> extends GraphSearch<V, E> {
/**
* Queue of vertices to be visited in search.
*/
private Stack<V> toVisit;
/**
* Constructor with graph only. This will set the search up for no target
* with no origin point.
* @param g Graph to search.
*/
public DFS(Graph<V, E> g) {
super(g);
toVisit = new Stack<V>();
}
/**
* Constructor with graph and target. This will set the search up for a
* targeted search with no origin.
* @param g Graph to search.
* @param target Target of the search.
*/
public DFS(Graph<V, E> g, V target){
super(g, target);
toVisit = new Stack<V>();
}
/**
* Constructor with graph, start and, target. This will set the search up
* for a targeted search with an origin.
* @param g Graph to search.
* @param start Entry point of the graph.
* @param target Target of the search.
*/
public DFS(Graph<V, E> g, V start, V target){
super(g, start, target);
toVisit = new Stack<V>();
}
/**
* Gets the queue of vertices (not before seen) to visit.
* @return The queue of vertices to visit.
*/
public Stack<V> getToVisit() {
return toVisit;
}
/**
* Sets the queue of vertices (not before seen) to visit.
* @return The queue of vertices to visit.
*/
public void setToVisit(Stack<V> toVisit) {
this.toVisit = toVisit;
}
/**
* DFS specific implementation of search.
*/
@Override
public V searchImplementation() throws ImproperGraphBuildException {
if(start == null){
start = graph.getRootVertex();
}
Set<V> seen = new HashSet<V>();
toVisit.add(start);
while(!toVisit.isEmpty()){
V v = toVisit.pop();
if(!seen.contains(v)){
seen.add(v);
try {
for(Integer w : graph.getNeighbors(v.getIndex())){
if(target != null && target.isEqualTo(graph.getVertexContent(w), "")){
return target;
}
toVisit.push(graph.getVertexContent(w));
}
} catch (InvalidVertexIndexException e) {
throw new ImproperGraphBuildException("Graph is not built properly; check indexes and links.");
}
}
}
return null;
}
}
|
SQL
|
UTF-8
| 241
| 3.515625
| 4
|
[] |
no_license
|
SELECT user.first_name, user.last_name, user2.first_name as friend_first_name, user2.last_name as friend_last_name
FROM user
LEFT JOIN friendships
ON user.id = friendships.user_id
LEFT JOIN user AS user2
ON user2.id = friendships.friend_id
|
Python
|
UTF-8
| 2,383
| 2.671875
| 3
|
[
"Apache-2.0"
] |
permissive
|
from threading import Semaphore
from unittest.case import SkipTest
from batchy.runloop import coro_return, runloop_coroutine
from batchy.batch_coroutine import batch_coroutine, class_batch_coroutine
try:
from concurrent.futures import ThreadPoolExecutor
import batchy.futures as batchy_futures
except ImportError:
batchy_futures = None
print('Futures not installed; skipping futures tests.')
from . import BaseTestCase
CALL_COUNT = 0
@batch_coroutine()
def increment(arg_lists):
def increment_single(n):
return n + 1
global CALL_COUNT
CALL_COUNT += 1
coro_return([increment_single(*ar, **kw) for ar, kw in arg_lists])
yield
class FuturesTests(BaseTestCase):
def setup(self):
if not batchy_futures:
raise SkipTest()
self.pool = ThreadPoolExecutor(1)
global CALL_COUNT
CALL_COUNT = 0
def test_simple_futures(self):
sema = Semaphore(0)
def acq():
sema.acquire()
return 1
@runloop_coroutine()
def rel():
sema.release()
coro_return(2)
yield
@runloop_coroutine()
def test():
r1, r2 = yield batchy_futures.submit(self.pool, acq), rel()
coro_return(r1 + r2)
self.assert_equals(3, test())
def test_futures_exceptions(self):
def throw():
raise ValueError()
@runloop_coroutine()
def test():
yield batchy_futures.submit(self.pool, throw)
self.assert_raises(ValueError, test)
def test_batch_with_gevent(self):
def call_increment(i):
return increment(i)
@runloop_coroutine()
def test():
a, b = yield batchy_futures.submit(self.pool, call_increment, 2), increment(3)
coro_return(a + b)
self.assert_equals(7, test())
self.assert_equals(2, CALL_COUNT)
def test_gevent_out_of_order(self):
def acq(s):
s.acquire()
@runloop_coroutine()
def test():
s = Semaphore(0)
future1 = yield batchy_futures.future(self.pool.submit(acq, s))
future2 = yield batchy_futures.future(self.pool.submit(acq, s))
s.release()
yield future1
s.release()
yield future2
test() # shouldn't hang
|
Java
|
UTF-8
| 3,939
| 2.9375
| 3
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.store;
import java.util.Scanner;
/**
*
* @author Bassam Muhammad
*/
public class Customer {
private String name;
private String address;
private String emailAdress;
private String password;
private long phoneNumber;
public Customer(String name, String address, String emailAdress, String password, long phoneNumber) {
this.name = name;
this.address = address;
this.emailAdress = emailAdress;
this.password = password;
this.phoneNumber = phoneNumber;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getEmailAdress() {
return emailAdress;
}
public void setEmailAdress(String emailAdress) {
this.emailAdress = emailAdress;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public long getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(long phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void makeOrder(OnlineStore online){
Order order = new Order();
order.instructions();
Scanner input = new Scanner(System.in);
int orderChoice = Integer.parseInt(input.nextLine());
boolean bought = false;
while(orderChoice != 6){
switch(orderChoice){
//Put products in cart
case 1:
while(true){
System.out.println("Enter product id and quantity");
order.putInCart(Long.parseLong(input.nextLine()), Integer.parseInt(input.nextLine()), online);
System.out.println("Enter next product?\nPress 1 for Yes, 2 for No");
orderChoice = Integer.parseInt(input.nextLine());
if(orderChoice == 2)
break;
}
break;
//Show products added to cart
case 2:
System.out.println("******");
System.out.println("Cart:");
System.out.println("******");
order.showCart();
break;
//Remove product from cart
case 3:
System.out.println("Enter id of product");
order.removeFromCart(Integer.parseInt(input.nextLine()), online);
break;
//emty cart
case 4:
order.emptyCart(online);
break;
//Purchasing
case 5:
System.out.println("*********");
System.out.println("Billing:");
System.out.println("*********");
order.buy();
bought = true;
break;
}
if(bought)
break;
order.instructions();
orderChoice = Integer.parseInt(input.nextLine());
if(orderChoice == 6 && !order.cart.isEmpty()){
for(int i = 0; i < order.cart.size(); i++)
online.insert(order.cart.get(i).getName(), order.cart.get(i).getCost(), order.cart.get(i).getId(), 1, false);
}
}
}
}
|
C
|
UTF-8
| 4,550
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
/* 7-1-2010 MRC-Epid JHZ */
/*
// The code was written for the head circumference analysis
// of EPIC data both as standalone C program (see below) and
// a Stata plugin (see stata_snphwe.do). To facilitate file
// handling for the standalone version, an awk program was
// also written (not shown).
*/
#include "stplugin.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
double SNPHWE(int,int,int) ;
STDLL stata_call(int argc, char *argv[])
{
ST_int j, k ;
ST_double p, aa, ab, bb ;
ST_retcode rc ;
if (SF_nvars() < 3) return(102) ;
for (j = SF_in1(); j <= SF_in2(); j++)
{
if (SF_ifobs(j))
{
if (rc = SF_vdata(1,j,&aa)) return(rc) ;
if (rc = SF_vdata(2,j,&ab)) return(rc) ;
if (rc = SF_vdata(3,j,&bb)) return(rc) ;
p = SNPHWE(ab,aa,bb) ;
if(rc = SF_vstore(SF_nvars(), j, p)) return(rc) ;
}
}
return(0) ;
}
/*
int main(int argc, char **argv)
{
int aa=10,ab=20,bb=30;
double p;
ab=atoi(argv[1]);
aa=atoi(argv[2]);
bb=atoi(argv[3]);
p=SNPHWE(ab,aa,bb);
printf("%.20lf\n",p);
return 0;
}
*/
/*
// This code implements an exact SNP test of Hardy-Weinberg Equilibrium as described in
// Wigginton, JE, Cutler, DJ, and Abecasis, GR (2005) A Note on Exact Tests of
// Hardy-Weinberg Equilibrium. American Journal of Human Genetics. 76: 000 - 000
//
// Written by Jan Wigginton
*/
double SNPHWE(int obs_hets, int obs_hom1, int obs_hom2)
{
if (obs_hom1 < 0 || obs_hom2 < 0 || obs_hets < 0)
{
printf("FATAL ERROR - SNP-HWE: Current genotype configuration (%d %d %d ) includes a"
" negative count", obs_hets, obs_hom1, obs_hom2);
exit(EXIT_FAILURE);
}
int obs_homc = obs_hom1 < obs_hom2 ? obs_hom2 : obs_hom1;
int obs_homr = obs_hom1 < obs_hom2 ? obs_hom1 : obs_hom2;
int rare_copies = 2 * obs_homr + obs_hets;
int genotypes = obs_hets + obs_homc + obs_homr;
double * het_probs = (double *) malloc((size_t) (rare_copies + 1) * sizeof(double));
if (het_probs == NULL)
{
printf("FATAL ERROR - SNP-HWE: Unable to allocate array for heterozygote probabilities" );
exit(EXIT_FAILURE);
}
int i;
for (i = 0; i <= rare_copies; i++)
het_probs[i] = 0.0;
/* start at midpoint */
int mid = rare_copies * (2 * genotypes - rare_copies) / (2 * genotypes);
/* check to ensure that midpoint and rare alleles have same parity */
if ((rare_copies & 1) ^ (mid & 1))
mid++;
int curr_hets = mid;
int curr_homr = (rare_copies - mid) / 2;
int curr_homc = genotypes - curr_hets - curr_homr;
het_probs[mid] = 1.0;
double sum = het_probs[mid];
for (curr_hets = mid; curr_hets > 1; curr_hets -= 2)
{
het_probs[curr_hets - 2] = het_probs[curr_hets] * curr_hets * (curr_hets - 1.0)
/ (4.0 * (curr_homr + 1.0) * (curr_homc + 1.0));
sum += het_probs[curr_hets - 2];
/* 2 fewer heterozygotes for next iteration -> add one rare, one common homozygote */
curr_homr++;
curr_homc++;
}
curr_hets = mid;
curr_homr = (rare_copies - mid) / 2;
curr_homc = genotypes - curr_hets - curr_homr;
for (curr_hets = mid; curr_hets <= rare_copies - 2; curr_hets += 2)
{
het_probs[curr_hets + 2] = het_probs[curr_hets] * 4.0 * curr_homr * curr_homc
/((curr_hets + 2.0) * (curr_hets + 1.0));
sum += het_probs[curr_hets + 2];
/* add 2 heterozygotes for next iteration -> subtract one rare, one common homozygote */
curr_homr--;
curr_homc--;
}
for (i = 0; i <= rare_copies; i++)
het_probs[i] /= sum;
/* alternate p-value calculation for p_hi/p_lo
double p_hi = het_probs[obs_hets];
for (i = obs_hets + 1; i <= rare_copies; i++)
p_hi += het_probs[i];
double p_lo = het_probs[obs_hets];
for (i = obs_hets - 1; i >= 0; i--)
p_lo += het_probs[i];
double p_hi_lo = p_hi < p_lo ? 2.0 * p_hi : 2.0 * p_lo;
*/
double p_hwe = 0.0;
/* p-value calculation for p_hwe */
for (i = 0; i <= rare_copies; i++)
{
if (het_probs[i] > het_probs[obs_hets])
continue;
p_hwe += het_probs[i];
}
p_hwe = p_hwe > 1.0 ? 1.0 : p_hwe;
free(het_probs);
return p_hwe;
}
|
Python
|
UTF-8
| 820
| 2.671875
| 3
|
[] |
no_license
|
##Created by Muhammad Shahriyar Sheikh '_'
## Hatim Ali Asghar .-.
## AbuBakar Sarwar ._.
import csv
import tkMessageBox
import tkSimpleDialog
from Tkinter import *
###################################
root = Tk()
root.withdraw()
noOfPolicies = 0
host1=0
host2=0
macstring = "00:00:00:00:00:0"
###################################
writer = csv.writer(open('firewall.csv','wb'))
writer.writerow(["id","mac_0","mac_1"])
noOfPolicies = tkSimpleDialog.askinteger("Number of Policies","Enter the number of policies you wish to apply on the controller ? ")
for i in range(0,noOfPolicies):
hoststr = tkSimpleDialog.askstring("Traffic Generation Scheme","Type in x,y which means x will not be able to ping y (Like 1,2)")
writer.writerow([str(i+1),macstring+hoststr[0:1],macstring+hoststr[-1:]])
|
Java
|
UTF-8
| 1,716
| 2.171875
| 2
|
[] |
no_license
|
package com.santiago.certificadosdigitales.com.santiago.certificadosdigitales.controller;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.ServerResponse;
import static org.springframework.web.reactive.function.server.RequestPredicates.*;
import static org.springframework.web.reactive.function.server.RequestPredicates.accept;
import static org.springframework.web.reactive.function.server.RouterFunctions.route;
@Configuration
public class Route {
private static final String ROUTE_DIGITAL_CERTIFICATE = "/certificates";
private static final String ROUTE_DIGITAL_CERTIFICATE_BY_ID = "/certificates/{id}";
@Bean
RouterFunction<ServerResponse> routes(Handler handler){
return route(GET(ROUTE_DIGITAL_CERTIFICATE).and(accept(MediaType.APPLICATION_JSON)), handler::getAllCertificates)
.andRoute(GET(ROUTE_DIGITAL_CERTIFICATE_BY_ID).and(accept(MediaType.APPLICATION_JSON)), handler::getCertificate)
.andRoute(POST(ROUTE_DIGITAL_CERTIFICATE).and(accept(MediaType.APPLICATION_JSON)), handler::saveCertificate)
.andRoute(PUT(ROUTE_DIGITAL_CERTIFICATE_BY_ID).and(accept(MediaType.APPLICATION_JSON)), handler::updateCertificate)
.andRoute(DELETE(ROUTE_DIGITAL_CERTIFICATE_BY_ID).and(accept(MediaType.APPLICATION_JSON)), handler::deleteCertification)
.andRoute(DELETE(ROUTE_DIGITAL_CERTIFICATE).and(accept(MediaType.APPLICATION_JSON)), handler::deleteAllCertificates);
}
}
|
Ruby
|
UTF-8
| 389
| 3.53125
| 4
|
[] |
no_license
|
class Unit
attr_reader :health_points, :attack_power
def initialize(health_points=60, attack_power=10)
@health_points = health_points
@attack_power = attack_power
end
# def health_points
# @health_point
# end
def damage(attack_power)
@health_points -= attack_power
end
def attack!(target)
target.damage(attack_power)
end
end
|
Java
|
UTF-8
| 988
| 2.0625
| 2
|
[
"Apache-2.0"
] |
permissive
|
package org.atteo.moonshine.jetty.security;
import java.util.List;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
import org.atteo.config.AbstractConfigurable;
import org.eclipse.jetty.util.security.Constraint;
@XmlRootElement(name = "constraint")
public class ConstraintConfig extends AbstractConfigurable {
@XmlElement
private boolean authenticate = false;
@XmlElementWrapper(name = "roles")
@XmlElement(name = "role")
private List<String> roles;
@XmlElement
private String name;
@XmlElement(name = "data-constraint")
private int dataConstraint;
public Constraint getConstraint() {
Constraint constraint = new Constraint();
constraint.setAuthenticate(authenticate);
if (roles != null) {
constraint.setRoles(roles.toArray(new String[roles.size()]));
}
constraint.setName(name);
constraint.setDataConstraint(dataConstraint);
return constraint;
}
}
|
Markdown
|
UTF-8
| 5,946
| 2.578125
| 3
|
[
"Unlicense"
] |
permissive
|
# El regreso de la zarzuela
Published at: **2019-11-02T03:52:00+00:00**
Author: **Manuela Cano Pulido**
Original: [ELESPECTADOR.COM](https://www.elespectador.com/noticias/noticias-de-cultura/el-regreso-de-la-zarzuela-articulo-889100)
Entre las sillas del teatro que yace detrás de las puertas de la Fundación Jaime Manzur, rodeados por las múltiples historias que han recorrido ese lugar, su fundador nos comentaba, con orgullo, que la zarzuela regresaría al Teatro Colsubsidio Roberto Arias Pérez, de Bogotá. En frente teníamos ese escenario detenido en el tiempo, en el que habían nacido varias de las agrupaciones teatrales bogotanas y donde se encuentra, todavía, uno de los teatros de títeres más importantes del país.
Entonces, Manzur comentaba que el 2 de noviembre sería esa fecha en que obras como La leyenda del beso y Antología de la zarzuela regresarán, después de ocho años de ausencia, a ese teatro situado en la calle 26 con 25. Allí, sentados en esas sillas frente a un escenario de fantasías, Manzur se veía en su hábitat natural, al que siempre ha pertenecido.
Desde muy pequeño el director se interesó por la lírica y el arte. Era un gusto que provenía de su madre, a la que el escritor define como “polifacética”, pues dominaba y disfrutaba todo tipo de expresiones artísticas. Tanto es así que ella había instaurado en su hogar una regla de oro: después del almuerzo todos debían escoger un libro y disponerse a leer. El pequeño Manzur no tenía problema con eso, porque él veía en esos estantes de su hogar todas las posibilidades de viajar por mundos aún desconocidos para sus ojos curiosos.
Además recordaba que su madre le había dicho que el día en que él aprendiera realmente a leer, él se convertiría en director. “Entonces, me pegué a leer y a leer. Teníamos en la biblioteca El tesoro de la juventud, que eran veinte tomos que tenían de todo: geografía, historia, botánica... Yo leía a través de esto a Shakespeare, Moliere, Calderón de la Barca, Lope de Vega y mucho más”, comentaba Manzur.
La lectura había sido una constante en su vida de cambios. Él, de madre colombiana y padre libanés, nació en lo que ahora se conoce como República de Guinea Ecuatorial. Su familia había llegado allí por cosas del destino. Una revolución, la del 36, retuvo a sus padres en ese país, en donde Manzur vivió sus primeros años. Después, vinieron los cambios. El desplazamiento a España, el regreso a Colombia y los múltiples caminos que tuvieron que recorrer le abrieron horizontes y lo llevaron a apreciar lo mejor de la cultura de esos continentes.
Toda esa diversidad de contextos se expresa en dos de sus grandes amores: la lírica y el folklore. Además, todos estos y sus múltiples lecturas lo llevaron a ser ese director que su mamá había presagiado muchos años antes. Manzur se graduó de danza superior y después de años desempeñándose como bailarín, encontró uno de sus mayores objetivos de vida. Supo, entonces, que debía ayudar, a través del arte, a ese país que lo había recibido y acogido. Al respecto, Manzur afirma: “Me propuse crear una compañía que tuviera todo el elenco colombiano. Con eso he podido tener mi compañía propia, fundada en 1992. Esta salió al aire en 1997 y desde entonces no ha parado”.
El director es un convencido de que desde el arte se pueden transformar realidades. Por eso, siempre le ha apostado al talento colombiano. “He creído mucho en el talento nacional y lo que pasa es que falta apoyo nacional para los nacionales”, anota el artista. Piensa que una de las grandes deudas del país es dejar perder jóvenes talentos, que se cansan de esperar a ser conocidos y deciden tomar otros rumbos. Manzur también le atribuye todo esto a una enorme falta de educación en el arte y en la exaltación de nuestras expresiones artísticas por parte de las instituciones colombianas. El director no se ha cansado de repetir que en Colombia somos privilegiados por las mezclas y la diversidad de herencias artísticas que se pasean por todo nuestro territorio.
Por esas razones, Manzur aprecia tanto la zarzuela, pues también es el producto de transformaciones y combinaciones. Provino de las cortes españolas del siglo XVII, migró por toda España y llegó a tierras latinoamericanas. Paso a paso obtuvo variaciones y es así que cada lugar goza de tener un tipo único y diferente. “El mundo es un contagio en todos los sentidos, donde se contagia el uno al otro”, afirma el director, y eso mismo ocurrió con la zarzuela. Para Manzur, rescatarla es recordar una parte de lo que somos como país. Se trata de remontarse en el tiempo y hacer actuales aquellas expresiones que se han perdido en el tiempo.
“El mundo va y vuelve como un reloj: de pronto algo está de moda, luego cambia”, dice Manzur. Es por eso que, con la nueva temporada de zarzuela, el director busca que los bogotanos y sobre todo las nuevas generaciones se acerquen a esa expresión artística que para muchos ha sido enterrada en el pasado, pero en la que Manzur ve una increíble vigencia. Las puertas del Teatro Colsubsidio se abrirán para recibir la zarzuela, esa que como dice Manzur “está dirigida a todas las edades, no tiene estatus social”, hasta el diez de noviembre.
Estrenada en 1924, “La leyenda del beso” es considerada una de las zarzuelas más demandantes en términos de interpretación. Esta, con libreto de Enrique Reoyo, José Silva Aramburu y Antonio Paso y con música de los maestros Reveriano Soutullo y Juan Vert, ha viajado por los escenarios más importantes del mundo. En todos ha deleitado a los espectadores con la historia de amor dramática entre Amapola y el Conde Mario. Por su parte, “Antología de la zarzuela” recoge en todo su acto los coros y las romanzas más complejos de la lírica que han recorrido las zarzuelas.
889100
2019-11-01T22:52:00-05:00
article
2019-11-01T22:52:22-05:00
leorod4@me.com
none
Manuela Cano Pulido
Cultura
El regreso de la zarzuela
25
5824
5849
|
Java
|
UTF-8
| 2,875
| 2.546875
| 3
|
[] |
no_license
|
package uidesign;
import java.awt.EventQueue;
import java.util.Date;
import java.time.format.DateTimeFormatter;
import java.text.SimpleDateFormat;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class GetBalanceFrame extends JFrameDemo{
/**
*
*/
private static final long serialVersionUID = 1L;
//private JPanel contentPane;
private JLabel lblBalance;
private JLabel label0;
private JLabel label1;
private JLabel lblDate;
private String balance;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
GetBalanceFrame window = new GetBalanceFrame();
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public GetBalanceFrame() {
init();
}
public GetBalanceFrame(JFrame pframe) {
super(pframe);
this.parentFrame = pframe;
init();
}
public void init() {
setTitle("查询余额");
setBounds(100, 100, 450, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
getContentPane().setLayout(null);
JPanel contentPane = new JPanel();
contentPane.setBounds(0, 0, 432, 253);
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnReturn = new JButton("返回");
btnReturn.setBounds(305, 213, 113, 27);
btnReturn.addMouseListener(new JButtonReturnListener());
contentPane.add(btnReturn);
lblBalance = new JLabel();
lblBalance.setText("");
lblBalance.setBounds(147, 98, 40, 18);
contentPane.add(lblBalance);
label0 = new JLabel("截至到:");
label0.setBounds(63, 54, 60, 30);
contentPane.add(label0);
lblDate = new JLabel("2017-11-30");
label0.setLabelFor(lblDate);
lblDate.setBounds(137, 54, 135, 30);
contentPane.add(lblDate);
label1 = new JLabel("账户余额:");
label1.setLabelFor(lblBalance);
label1.setBounds(51, 98, 92, 18);
contentPane.add(label1);
this.setBackgroundImg(contentPane);
}
public void setBalance(String balance) {
this.balance = balance;
this.lblBalance.setText(balance);
}
public void setDate(long lo) {
Date da = new Date(lo);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
this.lblDate.setText(sdf.format(da));
}
}
|
Python
|
UTF-8
| 9,084
| 3.34375
| 3
|
[] |
no_license
|
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.tree import DecisionTreeRegressor
from sklearn.linear_model import LinearRegression
class DataManipulator:
def __init__(self, dat: pd.DataFrame, validation_year: int = 2017, test_year: int = 2018):
"""
:param dat: Pandas Dataframe of Fangraphs data
:param validation_year: Integer value of season which should be set aside as validation data. All years prior to
validation_year will be included as part of training data.
:param test_year: Integer value of season which should be set aside as test data. All years after test_year
will be thrown out.
"""
try: # Separate data into training, validation, test
dat2 = dat.copy()
dat2.Season -= 1
self.dat = dat.copy()
dat2 = dat.merge(dat2.loc[:, ['playerid', 'Season']])
self.train = dat2[dat2['Season'] < validation_year]
self.validation = dat2[dat2['Season'] == validation_year]
self.test = dat2[dat2['Season'] == test_year]
except KeyError:
raise KeyError("Data must contain 'Season' field")
def get_data(self, y: str = 'wOBA'):
"""
Return train, validation, and test data after making desired changes
:param y: string indicating which column should be the prediction variable
:return: DataFrames of train, validation, test
"""
try: # Add y value to end of data set and return training, validation, and test
res = self.dat.loc[:, ['playerid', 'Season', y]]
res = res.rename(columns={y: 'y'})
res.Season -= 1
train_out = pd.merge(self.train, res)
validate_out = pd.merge(self.validation, res)
test_out = pd.merge(self.test, res)
return train_out, validate_out, test_out
except KeyError:
raise KeyError(f"Data does not contain {y}. Set parameter y to name of predicted column")
def calculate_z_scores(self, needed_z_scores: list):
"""
Calculate z-scores of the desired features grouped by season
:param needed_z_scores: list of strings indicating which columns should be calculated to z-scores
:return: None
"""
self.means = self.dat.groupby('Season')[needed_z_scores].mean()
self.sds = self.dat.groupby('Season')[needed_z_scores].std()
extra_cols = [col for col in self.dat.columns if col not in needed_z_scores]
temp = self.train.apply(lambda x: (x[needed_z_scores] - self.means.loc[x[1]]) / self.sds.loc[x[1]], axis=1)
self.train = pd.concat([self.train[extra_cols], temp], ignore_index=False, axis=1)
temp = self.validation.apply(lambda x: (x[needed_z_scores] - self.means.loc[x[1]]) / self.sds.loc[x[1]], axis=1)
self.validation = pd.concat([self.validation[extra_cols], temp], ignore_index=False, axis=1)
temp = self.test.apply(lambda x: (x[needed_z_scores] - self.means.loc[x[1]]) / self.sds.loc[x[1]], axis=1)
self.test = pd.concat([self.test[extra_cols], temp], ignore_index=False, axis=1)
temp = self.dat.apply(lambda x: (x[needed_z_scores] - self.means.loc[x[1]]) / self.sds.loc[x[1]], axis=1)
self.dat = pd.concat([self.dat[extra_cols], temp], ignore_index=False, axis=1)
def impute_data(self, train_cols: list, columns_to_impute: list, model: str, dims: int = None):
"""
Impute data for the specified columns using Linear Regression or Decision Trees
:param train_cols: list of strings of column names which should be used to impute data
:param columns_to_impute: list of strings of columns names which should be imputed
:param model: string indicating if linear regression or decision trees should be used
:param dims: PCA dimensions - if None PCA will not be run
:return: None
"""
if model == 'dt':
model = DecisionTreeRegressor()
elif model == 'lr':
model = LinearRegression()
else:
raise NameError("Model must be one of ['lr', 'dt']")
train = self.train.copy() # Avoid modifying in place
cols = train_cols.copy()
cols.extend(columns_to_impute)
train = train.loc[:, cols].dropna()
if dims is None:
model.fit(train.loc[:, train_cols], train.loc[:, columns_to_impute])
self.train.loc[self.train[columns_to_impute[0]].isna(), columns_to_impute] = model.predict( # Impute data to rows missing imputed columns
self.train.loc[self.train[columns_to_impute[0]].isna(), train_cols])
if self.validation[columns_to_impute[0]].isna().sum() > 0:
self.validation.loc[self.validation[columns_to_impute[0]].isna(), columns_to_impute] = model.predict(
self.validation.loc[self.validation[columns_to_impute[0]].isna(), train_cols])
if self.test[columns_to_impute[0]].isna().sum() > 0:
self.test.loc[self.test[columns_to_impute[0]].isna(), columns_to_impute] = model.predict(
self.test.loc[self.test[columns_to_impute[0]].isna(), train_cols])
self.dat.loc[self.dat[columns_to_impute[0]].isna(), columns_to_impute] = model.predict(
self.dat.loc[self.dat[columns_to_impute[0]].isna(), train_cols])
else:
pca = PCA(dims)
pca.fit(self.train.loc[:, train_cols], train.loc[:, columns_to_impute]) # Run PCA on training columns for imputation columns
model.fit(pd.DataFrame(pca.transform(train.loc[:, train_cols])), train.loc[:, columns_to_impute])
self.train.loc[self.train[columns_to_impute[0]].isna(), columns_to_impute] = model.predict(pd.DataFrame( # Impute data to rows missing imputed columns
pca.transform(self.train.loc[self.train[columns_to_impute[0]].isna(), train_cols])))
if self.validation[columns_to_impute[0]].isna().sum() > 0:
self.validation.loc[self.validation[columns_to_impute[0]].isna(), columns_to_impute] = model.predict(pd.DataFrame(
pca.transform(self.validation.loc[self.validation[columns_to_impute[0]].isna(), train_cols])))
if self.test[columns_to_impute[0]].isna().sum() > 0:
self.test.loc[self.test[columns_to_impute[0]].isna(), columns_to_impute] = model.predict(pd.DataFrame(
pca.transform(self.test.loc[self.test[columns_to_impute[0]].isna(), train_cols])))
self.dat.loc[self.dat[columns_to_impute[0]].isna(), columns_to_impute] = model.predict(pd.DataFrame(
pca.transform(self.dat.loc[self.dat[columns_to_impute[0]].isna(), train_cols])))
def generate_past_years(self, years_back: int):
"""
Add columns for multiyear data
:param years_back: Number of years to be added to the training set
:return: None
"""
temp = self.dat.copy()
columns = self.dat.columns
for year in range(years_back):
rename_dict = {}
if year == 0:
temp['Season'] = temp['Season'] + 1
for col in columns:
rename_dict[col] = col + f'-{year + 1}' # Add columns for each old season to rename dict
else:
temp[f'Season-{year}'] = temp[f'Season-{year}'] + 1
for col in columns:
rename_dict[f'{col}-{year}'] = f'{col}-{year + 1}'
temp = temp.rename(columns=rename_dict)
self.train = self.train.merge(temp, how="left", left_on=["playerid", "Season"],
right_on=[f"playerid-{year+1}", f"Season-{year+1}"])
self.validation = self.validation.merge(temp, how="left", left_on=["playerid", "Season"],
right_on=[f"playerid-{year+1}", f"Season-{year+1}"])
self.test = self.test.merge(temp, how="left", left_on=["playerid", "Season"],
right_on=[f"playerid-{year+1}", f"Season-{year+1}"])
self.dat = self.dat.merge(temp, how="left", left_on=["playerid", "Season"],
right_on=[f"playerid-{year+1}", f"Season-{year+1}"])
def get_means(self):
"""Get means used to calculate z-scores"""
try:
return self.means
except NameError:
raise RuntimeError("Must run calculate_z_scores first.")
def get_sds(self):
"""Get standard deviations used to calculate z-scores"""
try:
return self.sds
except NameError:
raise RuntimeError("Must run calculate_z_scores first.")
def pca(self, train_cols: list, y_cols: list):
"""Get the explained variance ratio of PCA on max dimensions"""
pca = PCA(len(train_cols))
pca.fit(self.train.loc[:, train_cols], self.train.loc[:, y_cols])
return pca.explained_variance_ratio_
|
C++
|
UTF-8
| 1,795
| 3.125
| 3
|
[] |
no_license
|
#include <stdlib.h>
#include <stdio.h>
#include <string>
using std::string;
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#include <fstream>
using std::ifstream;
inline string onlyFilename(char *input){
string filenameWithExt = input;
string filenameOnly = filenameWithExt;
size_t foundDot = filenameWithExt.find_last_of(".");
if (foundDot!=string::npos){ // if dot was found
filenameOnly = filenameWithExt.substr(0,foundDot);
}
return filenameOnly;
}
inline string onlyFilename(string input){
string filenameWithExt = input;
string filenameOnly = filenameWithExt;
size_t foundDot = filenameWithExt.find_last_of(".");
if (foundDot!=string::npos){ // if dot was found
filenameOnly = filenameWithExt.substr(0,foundDot);
}
return filenameOnly;
}
inline bool fileexists (const std::string& name) {
ifstream f(name.c_str());
if (f.good()) {
f.close();
return true;
} else {
f.close();
return false;
}
}
inline void ensureIsDirectory(string& results_folder){
if (results_folder.size()!=0){
if (results_folder.at(results_folder.size()-1)!='/') {
results_folder = results_folder+'/';
}
}
}
inline void makeDirectory(string dr_str){
// Make the directory, if it doesn't exist
ensureIsDirectory(dr_str);
DIR* dir;
if((dir=opendir(dr_str.c_str()))==NULL) {
printf("-> Directory '%s' doesn't exist -- creating it now... ",dr_str.c_str());
if(mkdir(dr_str.c_str(),(S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH))!=0) {
printf("Error creating directory\n");
exit(1);
} else {
printf("Directory was created\n");
}
}
}
|
Java
|
UTF-8
| 690
| 1.96875
| 2
|
[] |
no_license
|
/**
*
*/
package xyz.shanmugavel.samples.config;
import javax.annotation.PostConstruct;
import org.apache.camel.spring.javaconfig.CamelConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* @author Shanmugavel
*
*/
@Configuration
@ComponentScan({"xyz.shanmugavel.samples.routes"})
public class SamplesConfiguration extends CamelConfiguration{
public static final Logger LOGGER = LoggerFactory.getLogger(SamplesConfiguration.class);
@PostConstruct
public void afterInit() {
LOGGER.info("Spring Configuration Initialized.");
}
}
|
JavaScript
|
UTF-8
| 1,926
| 3.265625
| 3
|
[] |
no_license
|
const app = {
init: function() {
// je récupère le bouton burger
const menuButton = document.querySelector('.menu-burger-button');
// je lui pose un écouteur d'évenement
menuButton.addEventListener('click', app.handleMenuButtonClick);
},
handleMenuButtonClick: function() {
// je récupère l'élément <body>
const body = document.querySelector('body');
// je lui ajoute la classe "menu-visible" au clic
body.classList.add('menu-visible');
// je récupère la nav et les icônes des réseaux sociaux
// je les clone avec leurs enfants (true)
const navigationClone= document.querySelector('.header .navigation').cloneNode(true);
const socialClone= document.querySelector('.header .social').cloneNode(true);
// j'ajoute une classe au clone de la nav
// (pour cibler le bon bouton de fermeture du menu)
navigationClone.classList.add('copyNav');
// j'ajoute les clones en tant qu'enfant du <body>
body.appendChild(navigationClone);
body.appendChild(socialClone);
// je récupère le bouton de fermeture du menu
const crossButton = document.querySelector('.copyNav .close-menu-button');
crossButton.addEventListener('click', app.handleCloseButtonClick);
},
handleCloseButtonClick: function() {
// je récupère le <body>
const body = document.querySelector('body');
// je lui retire la classe 'menu-visible'
body.classList.remove('menu-visible');
// je retire l'élément <nav> et les icônes directement enfant du <body>
body.querySelector('body > .navigation').remove();
body.querySelector('body > .social').remove();
}
}
// une fois le DOM chargé, j'initialise le module "app" via sa méthode "init"
document.addEventListener("DOMContentLoaded", app.init);
|
Java
|
UTF-8
| 5,010
| 2.1875
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.sg.superherosightings.controller;
import com.sg.superherosightings.dao.SuperheroSightingsDao;
import com.sg.superherosightings.model.HeroVillain;
import com.sg.superherosightings.model.Location;
import com.sg.superherosightings.model.Sighting;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
/**
*
* @author DZ
*/
@Controller
public class SightingsController {
@Inject
SuperheroSightingsDao dao;
Sighting sightView = null;
String error = null;
@GetMapping("/sightings")
public String sightingsPage(HttpServletRequest request, Model model) {
List<Sighting> sightings = dao.getAllSightings();
List<Location> locations = dao.getAllLocations();
List<HeroVillain> heroVillains = dao.getAllHeroVillains();
model.addAttribute("sightings", sightings);
model.addAttribute("locations", locations);
model.addAttribute("heroVillains", heroVillains);
model.addAttribute("sightView", sightView);
model.addAttribute("error", error);
return "/sightings";
}
@PostMapping("/addSighting")
public String addSighting(HttpServletRequest request) {
String stringDate = request.getParameter("date");
if (stringDate.isEmpty()) {
error = "You must choose a sighting date";
return "redirect:/sightings";
}
String location = request.getParameter("location");
if (location.contains("-Select One-")) {
error = "You must choose a sighting location";
return "redirect:/sightings";
}
Sighting sighting = new Sighting();
sighting.setDate(LocalDate.parse(request.getParameter("date")));
sighting.setLocation(dao.getLocationById(Integer.parseInt(request.getParameter("location"))));
String[] selectedHVs = request.getParameterValues("heroVillain");
if (selectedHVs == null) {
error = "You must choose at least one Superhero / Supervillain";
return "redirect:/sightings";
}
List<HeroVillain> sightHVs = new ArrayList<>();
for (String selectedHV : selectedHVs) {
sightHVs.add(dao.getHeroVillainById(Integer.parseInt(selectedHV)));
}
sighting.setHeroVillains(sightHVs);
dao.addSighting(sighting);
error = null;
return "redirect:/sightings";
}
@GetMapping("/viewSighting")
public String viewSighting(HttpServletRequest request, Model model) {
sightView = dao.getSightingById(Integer.parseInt(request.getParameter("id")));
return "redirect:/sightings";
}
@PostMapping("/editSighting")
public String editSighting(HttpServletRequest request) {
String stringDate = request.getParameter("date");
if (stringDate.isEmpty()) {
error = "You must choose a sighting date";
return "redirect:/sightings";
}
String location = request.getParameter("location");
if (location.contains("-Select One-")) {
error = "You must choose a sighting location";
return "redirect:/sightings";
}
sightView.setDate(LocalDate.parse(request.getParameter("date")));
sightView.setLocation(dao.getLocationById(Integer.parseInt(request.getParameter("location"))));
String[] selectedHVs = request.getParameterValues("heroVillain");
if (selectedHVs == null) {
error = "You must choose at least one Superhero / Supervillain";
return "redirect:/sightings";
}
List<HeroVillain> sightHVs = new ArrayList<>();
for (String selectedHV : selectedHVs) {
sightHVs.add(dao.getHeroVillainById(Integer.parseInt(selectedHV)));
}
sightView.setHeroVillains(sightHVs);
dao.updateSighting(sightView);
sightView = null;
error = null;
return "redirect:/sightings";
}
@PostMapping("/cancelEditSighting")
public String cancelEditSighting(HttpServletRequest request) {
sightView = null;
error = null;
return "redirect:/sightings";
}
@GetMapping("/deleteSighting")
public String deleteSighting(HttpServletRequest request) {
dao.deleteSighting(Integer.parseInt(request.getParameter("id")));
sightView = null;
error = null;
return "redirect:/sightings";
}
}
|
Java
|
UTF-8
| 3,873
| 2.296875
| 2
|
[
"MIT"
] |
permissive
|
/** jsierraecg - XliDecompressor.java
* Copyright (c) 2011 Christopher A. Watford
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.sierraecg.codecs;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Arrays;
public class XliDecompressor {
private InputStream in;
public XliDecompressor(InputStream in) {
this.in = in;
}
public int[] readLeadPayload() throws IOException {
byte[] chunkHeader = new byte[8];
if (chunkHeader.length != this.in.read(chunkHeader)) {
return null;
}
// Each chunk begins with an 8 byte header consisting of:
// - 32-bit integer describing the length of the chunk
// - 16-bit integer (unknown payload, seemingly always 1)
// - 16-bit integer describing the first delta code
//
// After this header exists LZW-compressed delta codes, using 10-bit code words:
// 0 2 4 6 8 ...
// +--------+--------+--------+--------+--------+--------+--------+--------+--------+
// | Size | Unk. | Delta | LZW compressed deltas (10-bit codes) |
// +--------+--------+--------+--------+ |
// | ... [Size bytes] |
// +--------+--------+--------+--------+--------+--------+--------+--------+--------+
ByteBuffer header = ByteBuffer.wrap(chunkHeader);
header.order(ByteOrder.LITTLE_ENDIAN);
int size = header.getInt(0);
/*short unknown = header.getShort(4);*/
short start = header.getShort(6);
byte[] chunk = new byte[size];
if (chunk.length != this.in.read(chunk)) {
return null;
}
LzwInputStream lzw = new LzwInputStream(new ByteArrayInputStream(chunk), 10);
int b;
ArrayList<Byte> bytes = new ArrayList<Byte>();
while (-1 != (b = lzw.read())) {
bytes.add((byte)(b & 0xFF));
}
if (bytes.size() % 2 == 1) bytes.add((byte)0);
return this.decodeDeltas(this.unpack(bytes), start);
}
private int[] unpack(ArrayList<Byte> bytes) {
int[] actual = new int[bytes.size() / 2];
for (int ii = 0; ii < actual.length; ++ii) {
int hi = (bytes.get(ii) << 8) & 0xFFFF;
int lo = bytes.get(actual.length + ii) & 0xFF;
actual[ii] = (short)(hi | lo);
}
return actual;
}
private int[] decodeDeltas(int[] input, short initialValue) {
int[] deltas = Arrays.copyOf(input, input.length);
int x = deltas[0];
int y = deltas[1];
int lastValue = initialValue;
for (int ii = 2; ii < deltas.length; ++ii) {
int z = (y + y) - x - lastValue;
lastValue = deltas[ii] - 64;
deltas[ii] = z;
x = y;
y = z;
}
return deltas;
}
}
|
Markdown
|
UTF-8
| 2,583
| 2.640625
| 3
|
[] |
no_license
|
---
layout: post
title: "apt 1.0 - old dog with new tricks"
dek: "The package manager for Debian 'just' got more user friendly"
lede: "If you're a Debian (or Ubuntu) Linux user you can probably use the simpler 'apt'-command and forget about 'apt-get', 'apt-cache' and 'dpkg'."
image:
feature: /assets/6789958972_ca35be7d33_z.jpg
title: "Packaging (Feb '12)"
src: https://www.flickr.com/photos/vfsdigitaldesign/6789958972/
creator-name: VFS Digital Design
creator-url: https://www.flickr.com/people/vfsdigitaldesign/
license: CC BY 2.0
license-url: https://creativecommons.org/licenses/by/2.0
date: 2016-02-28 08:00:00
tags: linux devops package-management debian ubuntu
---
Managing installed packages is a core \*nix-user skill. If you use Debian (or a Debian-derived Linux distro like Ubuntu) on servers you are probably familiar with `apt-get`, `apt-cache` and `dpkg`; or perhaps you have given in and turned to the text-ui of `aptitude`. APT, a tool that was originally released in 1998(!), got to version 1.0 in 2014(!!) and with the 1.0 release came a set of simpler commands for managing packages.
While it takes a little while for new versions of software to update in distros, it seems like it takes a lot longer for obsolete guides to APT to be pushed out of the top spots in the search engines. Of course you can still use the lower level tools (`apt-get`, `apt-cache` or even `dpkg`), but `apt` is probably easier in most cases.
So let's get to the good stuff, here are the new `apt`-commands you need the most:
* `apt search <terms>` -- search for packages, e.g `apt search zsh shell`
* `apt list <pkg> \[--installed\] \[--upgradable\] \[--all-versions\]` -- list packages, optionally installed, outdated or with all versions available locally, e.g. `apt list --upgradeable` or `apt list apache2 --all-versions`
* `apt show <pkg> \[--all-versions\]` -- show package information, e.g `apt show apache2`
* `apt install <pkg> \[\{=pkg_version_number | /target_release\}\]` -- to install packages, _optionally_ a specific version or release (e g `testing` or `stable`), e.g, `apt install zsh/stable`
* `apt edit-sources` -- simple way to get to edit your sources.list
* `apt update` -- update package index files from sources (e.g after `apt edit-sources`)
* `apt upgrade` -- upgrade all installed packages to their latest versions
* `apt full-upgrade` -- do a smart upgrade of packages, taking dependencies into account (might remove dependencies)
* `apt remove <pkg>` -- remove package (but not configuration files), e.g `apt remove apt-doc`
Happy apt-ing!
|
Python
|
UTF-8
| 980
| 3.953125
| 4
|
[] |
no_license
|
ORD_A = ord('a')
class Position:
x: int
y: int
def __init__(self, x: int, y: int):
self.x = int(x)
self.y = int(y)
@classmethod
def from_algebraic_notation(cls, notation: str) -> 'Position':
x = ord(notation[0]) - ORD_A
y = int(notation[1]) - 1
return cls(x, y)
def to_algebraic_notation(self) -> str:
x = chr(self.x + ORD_A)
y = self.y + 1
return f'{x}{y}'
def __str__(self) -> str:
return self.to_algebraic_notation()
@property
def north(self) -> 'Position':
return Position(self.x, self.y + 1)
@property
def south(self) -> 'Position':
return Position(self.x, self.y - 1)
@property
def east(self) -> 'Position':
return Position(self.x + 1, self.y)
@property
def west(self) -> 'Position':
return Position(self.x - 1, self.y)
def is_valid(self):
return 0 <= self.x <= 7 and 0 <= self.y <= 7
|
Java
|
UTF-8
| 584
| 2
| 2
|
[
"Apache-2.0"
] |
permissive
|
package io.nosqlbench.nb.api.markdown.types;
import io.nosqlbench.nb.api.markdown.types.HasDiagnostics;
import java.util.List;
public class Diagnostics {
public static List<String> getDiagnostics(Object o) {
if (o instanceof HasDiagnostics) {
return ((HasDiagnostics)o).getDiagnostics();
}
return List.of();
}
public static List<String> getDiagnostics(Object o, List<String> buffer) {
if (o instanceof HasDiagnostics) {
return ((HasDiagnostics)o).getDiagnostics(buffer);
}
return buffer;
}
}
|
Java
|
UTF-8
| 14,473
| 3.46875
| 3
|
[] |
no_license
|
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* This class provides a shortestPath method for finding routes between two points
* on the map. Start by using Dijkstra's, and if your code isn't fast enough for your
* satisfaction (or the autograder), upgrade your implementation by switching it to A*.
* Your code will probably not be fast enough to pass the autograder unless you use A*.
* The difference between A* and Dijkstra's is only a couple of lines of code, and boils
* down to the priority you use to order your vertices.
*/
public class Router {
/**
* Return a List of longs representing the shortest path from the node
* closest to a start location and the node closest to the destination
* location.
* @param g The graph to use.
* @param stlon The longitude of the start location.
* @param stlat The latitude of the start location.
* @param destlon The longitude of the destination location.
* @param destlat The latitude of the destination location.
* @return A list of node id's in the order visited on the shortest path.
*/
public static List<Long> shortestPath(GraphDB g, double stlon, double stlat,
double destlon, double destlat) {
HashMap<Long, Double> priorities = new HashMap<>();
HashMap<Long, Double> distance = new HashMap<>();
HashMap<Long, Long> nodeParent = new HashMap<>();
PriorityQueue<Long> fringe = new PriorityQueue<>((a, b) -> Double.compare(priorities.get(a),
priorities.get(b)));
HashSet<Long> visited = new HashSet<>();
long s = g.closest(stlon, stlat);
long t = g.closest(destlon, destlat);
//**************************************************
// System.out.println("in Router s and t are" + s + ":" + t);
//**************************************************
distance.put(s, 0.0);
nodeParent.put(s, s);
double priority = g.distance(s, t);
priorities.put(s, priority);
fringe.add(s);
shortPathHelp(priorities, distance, nodeParent, visited, fringe, g, t);
List<Long> shortPath = new ArrayList<>();
long temp = t;
while (temp != s) {
if (nodeParent.get(temp) == null) {
break;
}
shortPath.add(0, temp);
temp = nodeParent.get(temp);
}
shortPath.add(0, temp);
//**************************************************
// System.out.println("in Router shortPath is" + shortPath);
//**************************************************
return shortPath;
}
private static void shortPathHelp(HashMap<Long, Double> priorities, HashMap<Long, Double>
distance, HashMap<Long, Long> nodeParent, HashSet<Long> visited,
PriorityQueue<Long> fringe, GraphDB g, Long t) {
while (!fringe.isEmpty()) {
long vId = fringe.poll();
if (vId == t) {
return;
}
if (!visited.contains(vId)) {
visited.add(vId);
for (long w : g.adjacent(vId)) {
if (w != nodeParent.get(vId)) {
double vToW = g.distance(vId, w); //ed(v, w)
double sToW = distance.get(vId) + vToW; //d(s, v) + ed(v, w)
if (!distance.containsKey(w) || distance.get(w) > sToW) {
distance.put(w, sToW);
nodeParent.put(w, vId);
double priority = (sToW + g.distance(w, t));
priorities.put(w, priority);
fringe.add(w);
}
}
}
}
// d(s, v): best known distance from s to v
// ed(v, w): euclidean distance from v to w
// h(w): euclidean distance from w to goal
// If d(s, v) + ed(v, w) is less than d(s, w) in best:
// update best so that d(s, w) = d(s, v) + ed(v, w)
// add w to the fringe with a priority equal to d(s, v) + ed(v, w) + h(w).
}
}
/**
* Create the list of directions corresponding to a route on the graph.
* @param g The graph to use.
* @param route The route to translate into directions. Each element
* corresponds to a node from the graph in the route.
* @return A list of NavigatiionDirection objects corresponding to the input
* route.
*/
public static List<NavigationDirection> routeDirections2(GraphDB g, List<Long> route) {
// return Collections.emptyList();
List<NavigationDirection> res = new LinkedList<>();
long n1 = route.get(0), n2 = route.get(1);
double bearing = g.bearing(n1, n2);
String name = g.getEdge(n1, n2).getEdgeName();
NavigationDirection direc = new NavigationDirection();
// start on
direc.direction = 0;
direc.way = name;
for (int i = 0; i < route.size() - 1; i++) {
long v1 = route.get(i), v2 = route.get(i+1);
double newbearing = g.bearing(v1, v2);
double bearingdiff = newbearing - bearing;
String newname = g.getEdge(v1, v2).getEdgeName();
if (bearingdiff >= -15 && bearingdiff <= 15) {
// straight
if (newname == name) {
direc.distance += g.distance(v1, v2);
} else {
// straight enter new road
res.add(direc);
direc = new NavigationDirection();
direc.distance = g.distance(v1, v2);
if(newname != "") direc.way = newname;
direc.direction = 1;
}
} else {
// finish current direction or road
res.add(direc);
// init new direction or road
direc = new NavigationDirection();
direc.distance += g.distance(v1, v2);
if(newname != "") direc.way = newname;
if (bearingdiff > 15 && bearingdiff <=30) {
// slight left
direc.direction = 2;
} else if (bearing >= -30 && bearingdiff <-15) {
direc.direction = 3;
} else if (bearingdiff > 15 && bearingdiff <= 100) {
direc.direction = 5;
} else if (bearingdiff >=-15 && bearingdiff < -100) {
direc.direction = 4;
} else if (bearingdiff >100) {
direc.direction = 6;
} else {
direc.direction = 7;
}
}
}
// the last part
res.add(direc);
return res;
}
// should not change direction if on same road even if bearing changes
public static List<NavigationDirection> routeDirections(GraphDB g, List<Long> route) {
// return Collections.emptyList();
List<NavigationDirection> res = new LinkedList<>();
if (route.size() <= 1) {
NavigationDirection direc = new NavigationDirection();
res.add(direc);
return res;
}
long n1 = route.get(0), n2 = route.get(1);
double bearing = g.bearing(n1, n2);
String name = g.getEdge(n1, n2).getEdgeName();
name = (name == null)? "unknown road": name;
NavigationDirection direc = new NavigationDirection();
// start
direc.direction = 0;
direc.way = name;
for (int i = 0; i < route.size() - 1; i++) {
long v1 = route.get(i), v2 = route.get(i+1);
String newname = g.getEdge(v1, v2).getEdgeName();
newname = (newname == null)? "unknown road": newname;
// continue on current road
if (newname.equals(direc.way)) {
direc.distance += g.distance(v1, v2);
bearing = g.bearing(v1, v2);
} else {
// finish current direction or road
res.add(direc);
// init new road
direc = new NavigationDirection();
direc.distance += g.distance(v1, v2);
direc.way = newname;
double newbearing = g.bearing(v1, v2);
double bearingdiff = newbearing - bearing;
if (bearingdiff < -180) bearingdiff += 360;
if (bearingdiff > 180) bearingdiff -= 360;
bearing = newbearing;
if (bearingdiff >= -15 && bearingdiff <= 15) {
// straight enter new road
direc.direction = 1;
} else if (bearingdiff > 15 && bearingdiff <=30) {
// slight left
direc.direction = 3;
} else if (bearingdiff >= -30 && bearingdiff <-15) {
direc.direction = 2;
} else if (bearingdiff > 15 && bearingdiff <= 100) {
direc.direction = 4;
} else if (bearingdiff >=-100 && bearingdiff < -15) {
direc.direction = 5;
} else if (bearingdiff >100) {
direc.direction = 7;
} else {
direc.direction = 6;
}
}
}
// the last part
res.add(direc);
return res;
}
/**
* Class to represent a navigation direction, which consists of 3 attributes:
* a direction to go, a way, and the distance to travel for.
*/
public static class NavigationDirection {
/** Integer constants representing directions. */
public static final int START = 0;
public static final int STRAIGHT = 1;
public static final int SLIGHT_LEFT = 2;
public static final int SLIGHT_RIGHT = 3;
public static final int RIGHT = 4;
public static final int LEFT = 5;
public static final int SHARP_LEFT = 6;
public static final int SHARP_RIGHT = 7;
/** Number of directions supported. */
public static final int NUM_DIRECTIONS = 8;
/** A mapping of integer values to directions.*/
public static final String[] DIRECTIONS = new String[NUM_DIRECTIONS];
/** Default name for an unknown way. */
public static final String UNKNOWN_ROAD = "unknown road";
/** Static initializer. */
static {
DIRECTIONS[START] = "Start";
DIRECTIONS[STRAIGHT] = "Go straight";
DIRECTIONS[SLIGHT_LEFT] = "Slight left";
DIRECTIONS[SLIGHT_RIGHT] = "Slight right";
DIRECTIONS[LEFT] = "Turn left";
DIRECTIONS[RIGHT] = "Turn right";
DIRECTIONS[SHARP_LEFT] = "Sharp left";
DIRECTIONS[SHARP_RIGHT] = "Sharp right";
}
/** The direction a given NavigationDirection represents.*/
int direction;
/** The name of the way I represent. */
String way;
/** The distance along this way I represent. */
double distance;
/**
* Create a default, anonymous NavigationDirection.
*/
public NavigationDirection() {
this.direction = STRAIGHT;
this.way = UNKNOWN_ROAD;
this.distance = 0.0;
}
public String toString() {
return String.format("%s on %s and continue for %.3f miles.",
DIRECTIONS[direction], way, distance);
}
/**
* Takes the string representation of a navigation direction and converts it into
* a Navigation Direction object.
* @param dirAsString The string representation of the NavigationDirection.
* @return A NavigationDirection object representing the input string.
*/
public static NavigationDirection fromString(String dirAsString) {
String regex = "([a-zA-Z\\s]+) on ([\\w\\s]*) and continue for ([0-9\\.]+) miles\\.";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(dirAsString);
NavigationDirection nd = new NavigationDirection();
if (m.matches()) {
String direction = m.group(1);
if (direction.equals("Start")) {
nd.direction = NavigationDirection.START;
} else if (direction.equals("Go straight")) {
nd.direction = NavigationDirection.STRAIGHT;
} else if (direction.equals("Slight left")) {
nd.direction = NavigationDirection.SLIGHT_LEFT;
} else if (direction.equals("Slight right")) {
nd.direction = NavigationDirection.SLIGHT_RIGHT;
} else if (direction.equals("Turn right")) {
nd.direction = NavigationDirection.RIGHT;
} else if (direction.equals("Turn left")) {
nd.direction = NavigationDirection.LEFT;
} else if (direction.equals("Sharp left")) {
nd.direction = NavigationDirection.SHARP_LEFT;
} else if (direction.equals("Sharp right")) {
nd.direction = NavigationDirection.SHARP_RIGHT;
} else {
return null;
}
nd.way = m.group(2);
try {
nd.distance = Double.parseDouble(m.group(3));
} catch (NumberFormatException e) {
return null;
}
return nd;
} else {
// not a valid nd
return null;
}
}
@Override
public boolean equals(Object o) {
if (o instanceof NavigationDirection) {
return direction == ((NavigationDirection) o).direction
&& way.equals(((NavigationDirection) o).way)
&& distance == ((NavigationDirection) o).distance;
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(direction, way, distance);
}
}
}
|
C
|
UTF-8
| 2,561
| 2.671875
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
/* Copyright 2016 The Chromium OS Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
* Copyright 2011 Google Inc.
*
* Tasks for mutexes basic tests.
*/
#include "console.h"
#include "common.h"
#include "cts_common.h"
#include "task.h"
#include "test_util.h"
#include "timer.h"
#include "util.h"
static struct mutex mtx;
/* period between 50us and 3.2ms */
#define PERIOD_US(num) (((num % 64) + 1) * 50)
/* one of the 3 MTX3x tasks */
#define RANDOM_TASK(num) (TASK_ID_MTX3C + (num % 3))
int mutex_random_task(void *unused)
{
char letter = 'A'+(TASK_ID_MTX3A - task_get_current());
/* wait to be activated */
while (1) {
task_wait_event(0);
ccprintf("%c+\n", letter);
mutex_lock(&mtx);
ccprintf("%c=\n", letter);
task_wait_event(0);
ccprintf("%c-\n", letter);
mutex_unlock(&mtx);
}
task_wait_event(0);
return EC_SUCCESS;
}
int mutex_second_task(void *unused)
{
task_id_t id = task_get_current();
ccprintf("\n[Mutex second task %d]\n", id);
task_wait_event(0);
ccprintf("MTX2: locking...");
mutex_lock(&mtx);
ccprintf("done\n");
task_wake(TASK_ID_CTS);
ccprintf("MTX2: unlocking...\n");
mutex_unlock(&mtx);
task_wait_event(0);
return EC_SUCCESS;
}
static enum cts_rc lock_unlock_test(void)
{
task_id_t id = task_get_current();
uint32_t rdelay = (uint32_t)0x0bad1dea;
uint32_t rtask = (uint32_t)0x1a4e1dea;
int i;
ccprintf("\n[Mutex main task %d]\n", id);
/* --- Lock/Unlock without contention --- */
ccprintf("No contention :");
mutex_lock(&mtx);
mutex_unlock(&mtx);
mutex_lock(&mtx);
mutex_unlock(&mtx);
mutex_lock(&mtx);
mutex_unlock(&mtx);
ccprintf("done.\n");
/* --- Serialization to test simple contention --- */
ccprintf("Simple contention :\n");
/* lock the mutex from the other task */
task_set_event(TASK_ID_MTX2, TASK_EVENT_WAKE, 1);
/* block on the mutex */
ccprintf("MTX1: blocking...\n");
mutex_lock(&mtx);
ccprintf("MTX1: get lock\n");
mutex_unlock(&mtx);
/* --- mass lock-unlocking from several tasks --- */
ccprintf("Massive locking/unlocking :\n");
for (i = 0; i < 500; i++) {
/* Wake up a random task */
task_wake(RANDOM_TASK(rtask));
/* next pseudo random delay */
rtask = prng(rtask);
/* Wait for a "random" period */
task_wait_event(PERIOD_US(rdelay));
/* next pseudo random delay */
rdelay = prng(rdelay);
}
return EC_SUCCESS;
}
#include "cts_testlist.h"
void cts_task(void)
{
wait_for_task_started();
cts_main_loop(tests, "Mutex");
task_wait_event(-1);
}
|
Java
|
UTF-8
| 119
| 2.140625
| 2
|
[] |
no_license
|
package httpParsing.http;
import java.util.Map;
public interface HttpCookie {
Map<String, String> getCookies();
}
|
Python
|
UTF-8
| 5,555
| 3
| 3
|
[] |
no_license
|
import utill
import os
import random
rolls = {
'rock': {
'defeats': ['scissors'],
'defeated_by': ['paper']
},
'paper': {
'defeats': ['rock'],
'defeated_by': ['scissors']
},
'scissors': {
'defeats': ['paper'],
'defeated_by': ['rock']
},
}
def main():
utill.print_header('There is no internet and i am suffering')
players = ['Player 1', 'Player 2']
active_player_index = 0
player = players[active_player_index]
# list_players(player, players)
player_name = input('Hello player what is your name? \n')
player = player_name
# print(player)
# list_players(player, players)
first_choose(player, players)
are_you_not_entertained()
# start under here
def first_choose(player, players):
user_input_main_loop = 'EMPTY'
while user_input_main_loop != '3': # and user_input_main_loop:
user_input_main_loop = input(f'Hello {player} the chooses are (1)"play games","(3)EXIT"')
user_input_main_loop = user_input_main_loop.lower().strip()
if user_input_main_loop == "1":
os.system('cls')
print('loading')
game_list(player)
elif user_input_main_loop == '3': # and user_input_main_loop:
print('Thanks for playing')
list_players(player, players)
def end_it_all():
pass
def let_the_games_begin():
pass
def whole_rps(player):
utill.print_header('Rock Paper Scissors')
player_1 = player
player_2 = 'computer'
play_game(player_1, player_2)
def play_game(player_1, player_2):
wins = {player_1: 0, player_2: 0}
roll_names = list(rolls.keys())
while not find_winner(wins, [player_1, player_2]):
roll_1 = get_roll(player_1, roll_names)
# roll_2 = get_roll(player_2, rolls)
# player_2 = 'computer'
roll_2 = random.choice(roll_names)
if not roll_1:
continue
print(f'{player_1} rolls {roll_1}')
print(f'{player_2} rolls {roll_2}')
winner = check_for_winning_throw(player_1, player_2, roll_1, roll_2)
if winner is None:
print('this round was a tie!\n')
else:
print(f'{winner} takes the round!\n')
wins[winner] += 1
print(f'the score is {player_1}: {wins[player_1]} and {player_2}: {wins[player_2]}.\n')
overall_winner = find_winner(wins, wins.keys())
print(f'{overall_winner} wins the game!')
def find_winner(wins, names):
best_of = 3
for name in names:
if wins.get(name, 0) >= best_of: # try without the zero and see if it breaks
return name
def check_for_winning_throw(player_1, player_2, roll_1, roll_2):
winner = None
if roll_1 == roll_2:
print('you tied!')
outcome = rolls.get(roll_1, {})
if roll_2 in outcome.get('defeats'):
return player_1
elif roll_2 in outcome.get('defeated_by'):
return player_2
return winner
def get_roll(player, roll_names):
print("Available rolls:")
for index, r in enumerate(roll_names, start=1): # index is a variable
print(f"{index}. {r}")
text = input(f'\n{player} what is your roll?\n')
selected_index = int(text) - 1
if selected_index < 0 or selected_index >= len(rolls):
print('do you even know what your doing? try again \n')
return None
return roll_names[selected_index]
def guessing_game(player):
player_guess_num = -1
the_number = random.randint(0, 100)
# for player_guess_num in range(1, 7):
# while player_guess_num != the_number:
attempt_limit = 7
attempts = 0
while attempts < attempt_limit:
try:
player_guess_text = input(f'Hello {player} please enter a number between 1 and 100 \n')
player_guess_num = int(player_guess_text)
attempts += 1
if player_guess_num > the_number: # > greater then
print(f'your guess of {player_guess_num} is too high')
elif player_guess_num < the_number: # < less then
print(f'your guess of {player_guess_num} is to low')
else:
break
except ValueError:
print('please enter a number. ')
if player_guess_num == the_number:
print(f'correct! the number was {the_number}!')
# print('Thanks for playing')
else:
print(f'\nNope. The Number I was thinking of was {the_number}\n')
print(f'you took {attempts} guesses.\n')
os.system('cls')
print('play again?')
def are_you_not_entertained():
pass
def list_players(player, players):
print()
print(players)
print(f'the current player is {player}')
print()
def game_list(player):
user_input_main_loop = 'EMPTY'
while user_input_main_loop != '3' and user_input_main_loop:
user_input_main_loop = input('The games are "(1)guess the number" and "(2)RPS" or go (3)back')
user_input_main_loop = user_input_main_loop.lower().strip()
if user_input_main_loop == '1':
os.system('cls')
print('Starting Game \n')
print('You have seven tries')
guessing_game(player)
elif user_input_main_loop == '2':
print('Starting Game \n')
player_1 = player
player_2 = 'computer'
play_game(player, player_2)
elif user_input_main_loop == '3' and user_input_main_loop:
print('Thanks for playing')
# end here
if __name__ == '__main__':
main()
|
Markdown
|
UTF-8
| 1,382
| 2.75
| 3
|
[] |
no_license
|
_This page is about the status effect. For the spell, see [[Transience]]._
| Transience |  |
| --- | --- |
| Particles | Light blue dust |
| Effect type | Beneficial |
| Max. natural level | Transience I |
| Potion ID | `ebwizardry:transience` |
| First appeared in | Wizardry 1.0 |
## Description
Transience is a beneficial status effect which causes players and mobs to become invulnerable to all blockable damage. However, the player or mob will not be able to cause any damage while the effect is active, nor will they be able to break or place blocks. Transience is useful when trying to escape a dangerous situation, as it effectively turns the player into a 'ghost' that cannot interact with the world but is immune to all damage. Players and mobs under the transience effect also emit a subtle dust particle effect. Players with transience also see a bright yellowish 'nova' effect over their screen if they have custom shaders enabled.
## Sources
The transience spell grants the caster transience I (and also invisibility) for 20 seconds without modifiers. The only other source of the effect is via commands.
## Trivia
- The amplifier has no effect for transience, much like fire resistance or water breathing in vanilla _Minecraft_.
|
JavaScript
|
UTF-8
| 896
| 2.921875
| 3
|
[
"MIT",
"ISC"
] |
permissive
|
async function createPatientFormHandler(event) {
first_name = document.getElementById("first_name").value.trim();
last_name = document.getElementById("last_name").value.trim();
dob = document.getElementById("dob").value.trim();
if (first_name && last_name && dob) {
const response = await fetch("/api/patient", {
method: "POST",
body: JSON.stringify({
first_name,
last_name,
dob,
}),
headers: {
"Content-Type": "application/json",
},
});
if (response.ok) {
document.location.reload();
} else {
alert(response.statusText);
}
}
var notification = encodeURIComponent("New patient created succesfully");
window.location.replace("/create-patient?notification=" + notification);
}
document.querySelector(".create-patient-form");
document.addEventListener("submit", createPatientFormHandler);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.