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
|
---|---|---|---|---|---|---|---|
Ruby
|
UTF-8
| 1,225 | 3.578125 | 4 |
[] |
no_license
|
# Module that can be included (mixin) to create and parse TSV data
module TsvBuddy
# @data should be a data structure that stores information
# from TSV or Yaml files. For example, it could be an Array of Hashes.
attr_accessor :data
# take_tsv: converts a String with TSV data into @data
# parameter: tsv - a String in TSV format
def take_tsv(tsv)
survey = []
lines = []
tsv.each_line { |line| lines << line }
keys = lines[0].split("\t")
keys.map!(&:chomp)
lines.shift
lines.each do |line|
values = line.split("\t")
record = {}
keys.each_index { |index| record[keys[index]] = values[index].chomp }
survey.push(record)
end
@data = survey
end
# to_tsv: converts @data into tsv string
# returns: String in TSV format
def to_tsv
line = ''
keys_array = @data[0].keys
line << keys_array[0]
keys_array.shift # maybe there is a better way of implementing this rather than dealing with the first heading value on its own
keys_array.each { |key| line << "\t" + key }
line << "\n"
@data.each do |record|
line << record.map { |_, v| "#{v}" }.join("\t")
line << "\n"
end
line.chomp("\t")
line
end
end
|
Markdown
|
UTF-8
| 1,213 | 3.015625 | 3 |
[] |
no_license
|
---
layout: post
title: The best place to put script tags in HTML
date: '2017-01-17T20:53:00.000+07:00'
tags:
- Frontend
- HTML
---
When browsing a web page, browser will fetch HTML page. It then parses sequentially line by line, and shows HTML
components to user (like title, head...). When encounters a `<script>` tag, browser has to request that script from
URL, and during that time, nothing will be shown to user, not until browser finished requesting that script. It
creates a blocking operation, which is bad in UX.
So we need to solve it, trying to not blocking HTML parser with `<script>` tag.
- Legacy solution: Yahoo! Exceptional Performance team recommends placing scripts **at the bottom** of your page. By
that, all HTML components can be parsed and displayed to user before script started to load.
- Modern approach: modern browsers support the **async** and **defer** attributes on scripts. These attributes tell
the browser it's safe to continue parsing while the scripts are being downloaded. See full answer
[here](http://stackoverflow.com/a/24070373/6445037){:rel="nofollow" target="_blank"}.
- Most correct answer: The best place for it is **just before you need** it and **no sooner**.
|
Markdown
|
UTF-8
| 1,623 | 2.9375 | 3 |
[] |
no_license
|
---
title: Happy new year - New promises for 2016
layout: post
---

Happy New Year! Welcome to 2016
I've been away over the festive period focusing on my family and trying desperately to unwind for the 9-5 grind. During the run up to christmas I wasn't feeling particularly festive. I'm a Christian but have not been going to church over the last year. Christmas to me has always been about my faith; celebrating new life and new hope. However, because I'm not actively participating in Church life, events like the annual nativity and outreach in the local community are not currently a part of my life. As such things felt quite hollow. <!--more-->
I chose to focus on my family, trying to iron out day-to-day life to the point where I'm able to enjoy time together with my daughter and get along with my husband.
I feel truly blessed and optimistic for 2016. I also feel quite nervous as there were so many disappointments in 2015 and I don't want to repeat any of them this year.
I'll keep this nice and short and say thank you so much for subscribing or visiting my blog over 2015. It's been an eventful year. Stay tuned next week for the start of my 30 day blogging challenge. The goal is to build on the foundation I started in mid 2015 when I made my blog public. Juggling a full-time job, a 2-year-old daughter, and all the other responsibilities that come with the grown up world, I'm hoping that this challenge will encourage me to find my writing voice and build something respectable and truly reflective of my personality.
See you again soon
|
Shell
|
UTF-8
| 1,316 | 2.8125 | 3 |
[] |
no_license
|
#!/bin/sh
SERVERS=(iodine passenger puma Rhebok thin unicorn)
# stop servers
pkill -f ruby &> /dev/null
# seeds
ruby ./setup.rb &> /dev/null
# clear old performance data
rm -R performance
# run servers
for i in "${!SERVERS[@]}"; do
mkdir -p "performance/${SERVERS[$i]}"
bundler exec rackup -s ${SERVERS[$i]} --port "300$i" -E production config.ru &> /dev/null &
done
sleep 10
# warm
for i in "${!SERVERS[@]}"; do
curl -s -o /dev/null -I -w "%{http_code}\n" "http://localhost:300$i/"
done
# test
echo active_record
for i in "${!SERVERS[@]}"; do
wrk -c 10 -d 10s -t 10 "http://localhost:300$i/active_record" > "performance/${SERVERS[$i]}/active_record.txt" 2>&1
done
echo pi
for i in "${!SERVERS[@]}"; do
wrk -c 10 -d 10s -t 10 "http://localhost:300$i/pi" > "performance/${SERVERS[$i]}/pi.txt" 2>&1
done
echo random
for i in "${!SERVERS[@]}"; do
wrk -c 10 -d 10s -t 10 "http://localhost:300$i/random" > "performance/${SERVERS[$i]}/random.txt" 2>&1
done
echo server
for i in "${!SERVERS[@]}"; do
wrk -c 10 -d 10s -t 10 "http://localhost:300$i/server" > "performance/${SERVERS[$i]}/server.txt" 2>&1
done
echo sleep
for i in "${!SERVERS[@]}"; do
wrk -c 10 -d 10s -t 10 "http://localhost:300$i/sleep" > "performance/${SERVERS[$i]}/sleep.txt" 2>&1
done
# stop servers
pkill -f ruby &> /dev/null
|
C++
|
UTF-8
| 3,781 | 3.78125 | 4 |
[] |
no_license
|
///
/// @file multimap.cc
/// @author bigfei775655478@qq.com)
/// @date 2019-01-23 20:16:13
///
#include <math.h>
#include <map>
#include <string>
#include <iostream>
using std::cout;
using std::multimap;
using std::string;
using std::endl;
template <class Container>
void display(const Container & c)
{
for(auto & elem : c)
cout << elem.first << "---->" << elem.second << endl;
}
void test0()
{
//multimap能存放关键字相同的元素,默认情况下按升序方式进行排列
multimap<int, string> cities{
std::pair<int, string>(1, "北京"),
std::pair<int, string>(2, "上海"),
std::pair<int, string>(3, "武汉"),
std::pair<int, string>(2, "深圳"),
std::pair<int, string>(4, "广州")
};
display(cities);
//访问multimap中的元素,不可以使用下标访问运算符
//cout << "cites[1] = " << cities[1] << endl; O(logN)
//cities[0] = "长沙" ; //error
}
class Point
{
public:
Point(int ix = 0, int iy = 0)
: _ix(ix)
, _iy(iy)
{}
double getDistance() const
{
return sqrt(_ix * _ix + _iy * _iy);
}
friend std::ostream & operator<<(std::ostream & os, const Point & rhs);
friend bool operator<(const Point & lhs, const Point & rhs);
friend bool operator>(const Point & lhs, const Point & rhs);
friend class PointComparator;
private:
int _ix;
int _iy;
};
std::ostream & operator<<(std::ostream & os, const Point & rhs)
{
os << "(" << rhs._ix
<< "," << rhs._iy
<< ")" ;
return os;
}
bool operator<(const Point & lhs, const Point & rhs)
{
cout << "operator<(const Point & lhs, const Point & rhs)" << endl;
if(lhs.getDistance() < rhs.getDistance())
return true;
else if(lhs.getDistance() == rhs.getDistance())
return lhs._ix < rhs._ix;
else
return false;
}
bool operator>(const Point & lhs, const Point & rhs)
{
cout << "operator>(const Point & lhs, const Point & rhs)" << endl;
if(lhs.getDistance() > rhs.getDistance())
return true;
else if(lhs.getDistance() == rhs.getDistance())
return lhs._ix > rhs._ix;
else
return false;
}
void test1()
{
//map不能存放关键字相同的元素,默认情况下按升序方式进行排列
multimap<string, Point> points{
std::pair<string, Point>("1:", Point(1, 2)),
std::pair<string, Point>("2:", Point(-1, -2)),
std::pair<string, Point>("3:", Point(1, 2)),
std::pair<string, Point>("4:", Point(3, 2)),
std::pair<string, Point>("2:", Point(2, 3)),
};
display(points);
//访问multimap中的元素,不支持下标访问运算符
//下标访问运算符功能:
//1. 可以查找相应关键字对应的值;如果pair存在,则直接输出对应的值;
// 如果不存在,则创建一个相应关键字的pair,对应的value会调用相应
// 类型的默认构造函数创建对象
//
//2. 可以修改相应关键字对应的value
//cout << "cites[1] = " << points["1:"] << endl;
//cout << "cites[0] = " << points["0:"] << endl;
//points["5:"] = Point(9, 9);
//display(points);
auto ret = points.count("5:");
if(ret)
cout << "查找成功!" << endl;
else
cout << "查找成功!" << endl;
auto it = points.find("3:");
if(it != points.end())
cout << "查找成功!" << it->second << endl << endl;
else
cout << "查找失败!" << endl;
//std::pair<multimap<string, Point>::iterator, bool> ret2 =
//points.insert(std::make_pair("6:", Point(6, 6)));
auto ret2 = points.insert(std::make_pair("6:", Point(8, 8)));
cout << ret2->first << "---> " << ret2->second << endl;
display(points);
//if(ret2.second){
// cout << "添加元素成功。" << ret2.first->first<< "---->" << ret2.first->second << endl;
//}
//else
// cout << "已存在相同关键字的元素。" << ret2.first->first<< "---->" << ret2.first->second << endl;
}
int main(void)
{
test0();
//test1();
}
|
C#
|
UTF-8
| 670 | 2.515625 | 3 |
[] |
no_license
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WallSpikes : MonoBehaviour {
[SerializeField]
private bool isActive;
[SerializeField]
private int damageToGive;
private Animator anim;
void Start()
{
anim = GetComponent<Animator> ();
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
{
if (!isActive)
{
anim.SetBool ("Active", true);
isActive = true;
}
if (isActive)
{
Debug.Log ("You got hit!");
}
}
}
void OnTriggerExit2D(Collider2D other)
{
if (other.tag == "Player")
{
anim.SetBool ("Active", false);
isActive = false;
}
}
}
|
Go
|
UTF-8
| 3,529 | 3.578125 | 4 |
[
"Apache-2.0"
] |
permissive
|
package rstack
import (
"fmt"
"strings"
"testing"
)
var cases = []struct {
name string
initialStackSlice []interface{}
action func(s *RStack) (*RStack, interface{}, error)
expectedStackString string
expectedValue string
}{
{
name: "Push one on empty",
initialStackSlice: []interface{}{},
action: func(s *RStack) (*RStack, interface{}, error) {
return s.Push("one"), "", nil
},
expectedStackString: "one",
},
{
name: "Push one on one",
initialStackSlice: []interface{}{"one"},
action: func(s *RStack) (*RStack, interface{}, error) {
return s.Push("two"), "", nil
},
expectedStackString: "one, two",
},
{
name: "Push two on one",
initialStackSlice: []interface{}{"one", "two"},
action: func(s *RStack) (*RStack, interface{}, error) {
return s.Push("three"), "", nil
},
expectedStackString: "one, two, three",
},
{
name: "Push two on three",
initialStackSlice: []interface{}{"one", "two", "three"},
action: func(s *RStack) (*RStack, interface{}, error) {
return s.Push("four").Push("five"), "", nil
},
expectedStackString: "one, two, three, four, five",
},
{
name: "Pop two from five",
initialStackSlice: []interface{}{"one", "two", "three", "four", "five"},
action: func(s *RStack) (*RStack, interface{}, error) {
sFour, five, err := s.Pop()
if err != nil {
return nil, "", err
}
sThree, four, err := sFour.Pop()
if err != nil {
return nil, "", err
}
return sThree, strings.Join([]string{four.(string), five.(string)}, ", "), nil
},
expectedStackString: "one, two, three",
expectedValue: "four, five",
},
{
name: "Pop two from three",
initialStackSlice: []interface{}{"one", "two", "three"},
action: func(s *RStack) (*RStack, interface{}, error) {
sTwo, three, err := s.Pop()
if err != nil {
return nil, "", err
}
sOne, two, err := sTwo.Pop()
if err != nil {
return nil, "", err
}
return sOne, strings.Join([]string{two.(string), three.(string)}, ", "), nil
},
expectedStackString: "one",
expectedValue: "two, three",
},
{
name: "Pop one from two",
initialStackSlice: []interface{}{"one", "two"},
action: func(s *RStack) (*RStack, interface{}, error) {
sOne, two, err := s.Pop()
if err != nil {
return nil, "", err
}
return sOne, two.(string), nil
},
expectedStackString: "one",
expectedValue: "two",
},
{
name: "Pop one from one",
initialStackSlice: []interface{}{"one"},
action: func(s *RStack) (*RStack, interface{}, error) {
sNil, one, err := s.Pop()
if err != nil {
return nil, "", err
}
return sNil, one.(string), nil
},
expectedStackString: "",
expectedValue: "one",
},
}
func TestRStack(t *testing.T) {
for i, tc := range cases {
desc := fmt.Sprintf("Test Case %d: %s", i, tc.name)
t.Run(desc, func(t *testing.T) {
initialStack := NewFromSlice(tc.initialStackSlice)
got, v, err := tc.action(initialStack)
if err != nil {
t.Errorf("%s: Cannot action(). Error: %s", desc, err)
} else {
gotString := got.Join(", ")
if gotString != tc.expectedStackString {
t.Errorf("%s:\n\texp: %s\n\tgot: %s", desc, tc.expectedStackString, gotString)
}
}
if tc.expectedValue != "" {
if tc.expectedValue != v {
t.Errorf("%s:\n\texp Value: %s\n\tgot Value: %s", desc, tc.expectedValue, v)
}
}
})
}
}
|
JavaScript
|
UTF-8
| 1,677 | 3.46875 | 3 |
[] |
no_license
|
var ImageManager = function(){
//Holds all your loaded images
this.library = {};
}
//TODO: make it so that the names is extracted from the paths?
//Takes an array of pathnames or a single path, a name array/single
//name and a callback fnction to run after images has loaded
ImageManager.prototype.load = function(paths, names, callback){
/*if((typeof path) == String){
console.log("Loading just one image.");
}*/
// console.log("Names array length: " + names.length);
var alreadyLoaded = function(name){
if(this.library[name]){
// console.log("Image with name: " + name + " already exists.");
return true;
}
else{
return false;
}
}.bind(this);
var loadImage = function(imgPath, imgName, cb){
if(!alreadyLoaded(imgName)){
var img = new Image();
img.onload = function() {
// console.log("Loaded image named " + imgName);
cb(imgName, img);
};
img.src = imgPath;
}
};
var imgLoadCount = 0;
var thisArg = this;
for(var i = 0; i < paths.length; i++){
var nm = names[i];
var pth = paths[i];
loadImage(pth, nm, function(imgName, img){
thisArg.library[imgName] = img;
imgLoadCount++;
if(imgLoadCount >= paths.length){
// console.log("Done loading images!");
callback();
}
});
}
};
ImageManager.prototype.getImage = function(name){
if(this.library[name]){
return this.library[name];
}
else{
//console.log("The image of name: " + name + " doesn't exist yet.");
return null;
}
};
|
Java
|
UTF-8
| 898 | 3.71875 | 4 |
[] |
no_license
|
import java.util.regex.Matcher;
public class StringCalculator {
private final int NUMBER_LIMITER = 1000;
/*
* Sum the numbers present in the string
*/
public int add(String number) {
int sum = 0;
int temp = 0;
if(number.length() == 0) {
return 0;
}
Matcher m = RegexUtil.getNumberByRegex(number);
while(m.find()) {
temp = Integer.parseInt(m.group());
if(this.isNumberNegative(temp)) {
throw new NegativeNumberIsNotAllowException("Negatives not allowed: " + temp);
}
if(!this.isBiggerThanLimiter(temp)) {
sum += temp;
}
}
return sum;
}
/*
* Check if a number is negative
*/
private boolean isNumberNegative(int number) {
return number < 0;
}
/*
* Check if a number is bigger than NUMBER_LIMITER
*/
private boolean isBiggerThanLimiter(int number) {
return number > NUMBER_LIMITER;
}
}
|
Markdown
|
ISO-8859-1
| 1,537 | 2.890625 | 3 |
[
"MIT"
] |
permissive
|
# asw-655-docker-composizione
Questo progetto contiene alcune applicazioni che esemplificano
il rilascio di applicazioni composte da uno o pi servizi,
da eseguire su un nodo [docker](../../environments/docker/)
oppure in un cluster [docker-swarm](../../environments/docker-swarm/).
In particolare, le applicazioni sono delle varianti di quelle mostrate
nel progetto [asw-885-spring-cloud/](../asw-885-spring-cloud/).
Gli esempi sono relativi a due applicazioni principali, mostrate in pi versioni:
* l'applicazione **lucky-word**
* l'applicazione **sentence**
### Applicazione **lucky-word**
L'applicazione **lucky-word**, in questo caso, formata da un solo servizio.
Dopo essere stata compilata, pu essere eseguita creando ed avviando un contenitore Docker.
### Applicazione **sentence**
L'applicazione **sentence** invece formata da pi servizi, e realizzata in pi versioni:
* **b-sentence** pu essere eseguita in un nodo Docker ([docker](../../environments/docker/)), con *Docker* oppure con *Docker Compose*
* **c-sentence-swarm-eureka-zuul** pu essere eseguita in un cluster Docker ([docker-swarm](../../environments/docker-swarm/)), come *stack Docker*
* anche **d-sentence-swarm-zuul** pu essere eseguita in un cluster Docker ([docker-swarm](../../environments/docker-swarm/)), come *stack Docker*
### Ambiente di esecuzione
Queste applicazioni vanno eseguite negli ambienti
[docker](../../environments/docker/)
oppure [docker-swarm](../../environments/docker-swarm/).
|
Java
|
UTF-8
| 918 | 2.03125 | 2 |
[] |
no_license
|
package weimakeji.pojo;
public class LinkMan {
private Integer linkid;
private String lkmName;
private String lkmGender;
private String lkmPhone;
private String lkmMobile;
private Integer clid;
public Integer getLinkid() {
return linkid;
}
public void setLinkid(Integer linkid) {
this.linkid = linkid;
}
public String getLkmName() {
return lkmName;
}
public void setLkmName(String lkmName) {
this.lkmName = lkmName;
}
public String getLkmGender() {
return lkmGender;
}
public void setLkmGender(String lkmGender) {
this.lkmGender = lkmGender;
}
public String getLkmPhone() {
return lkmPhone;
}
public void setLkmPhone(String lkmPhone) {
this.lkmPhone = lkmPhone;
}
public String getLkmMobile() {
return lkmMobile;
}
public void setLkmMobile(String lkmMobile) {
this.lkmMobile = lkmMobile;
}
public Integer getClid() {
return clid;
}
public void setClid(Integer id) {
this.clid = id;
}
}
|
Python
|
UTF-8
| 519 | 2.921875 | 3 |
[] |
no_license
|
result=[]
ls=[]
instruct=[]
n=int(input())
for i in range(n):
instruct.append(input().split(" "))
if instruct[i][0]=="Q":
instruct[i][1]=int(instruct[i][1])-1
elif instruct[i][0]=="U":
instruct[i][1]=int(instruct[i][1])
for i in range(n):
if instruct[i][0]=="T":
ls.append(instruct[i][1])
elif instruct[i][0]=="Q":
result.append(ls[instruct[i][1]])
elif instruct[i][0]=="U":
ls=ls[:len(ls)-instruct[i][1]]
for i in range(len(result)):
print(result[i])
|
Markdown
|
UTF-8
| 5,160 | 3.15625 | 3 |
[
"MIT"
] |
permissive
|
# Ekko
[](https://packagist.org/packages/laravelista/ekko)
[](https://packagist.org/packages/laravelista/ekko)
[](https://packagist.org/packages/laravelista/ekko)
[](https://travis-ci.org/laravelista/Ekko)
[](http://forthebadge.com)
[](http://forthebadge.com)
Ekko is a Laravel helper package. It helps you mark currently active menu item in your navbar.
## Installation
From the command line:
```bash
composer require laravelista/ekko
```
Laravel 5.5+ will use the auto-discovery function.
If using 5.4 (or if you are not using auto-discovery) you will need to include the service providers / facade in `config/app.php`:
```php
'providers' => [
...,
Laravelista\Ekko\EkkoServiceProvider::class
];
```
And add a facade alias to the same file at the bottom:
```php
'aliases' => [
...,
'Ekko' => Laravelista\Ekko\Facades\Ekko::class
];
```
## Overview
To mark a menu item active in [Bootstrap](http://getbootstrap.com/components/#navbar), you need to add a `active` CSS class to the `<li>` tag:
```html
<ul class="nav navbar-nav">
<li class="active"><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
</ul>
```
You could do it manually with Laravel, but you will end up with a sausage:
```html
<ul class="nav navbar-nav">
<li class="@if(URL::current() == URL::to('/')) active @endif"><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
</ul>
```
With Ekko your code will look like this:
```html
<ul class="nav navbar-nav">
<li class="{{ isActiveURL('/') }}"><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
</ul>
```
What if you are not using Bootstrap, but some other framework or a custom design? Instead of returning `active` CSS class, you can make Ekko return anything you want including boolean `true` or `false`:
```html
<ul class="nav navbar-nav">
<li class="{{ isActiveURL('/', 'highlight') }}"><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
</ul>
```
Using boolean `true` or `false` is convenient if you need to display some content depending on which page you are in your layout view:
```html
@if(isActiveRoute('home', true))
<p>Something that is only visible on the `home` route.</p>
@endif
```
## API
There are two ways of using Ekko in your application, by using a facade `Ekko::isActiveURL('/about')` or by using a helper function `isActiveURL('/about')` or `is_active_route('/about')`.
### isActiveRoute, is_active_route
Compares given route name with current route name.
```php
isActiveRoute($routeName, $output = "active")
```
```php
is_active_route($routeName, $output = "active")
```
**Examples:**
If the current route is `home`, function `isActiveRoute('home')` would return *string* `active`.
_The `*` wildcard can be used for resource routes._
Function `isActiveRoute('user.*')` would return *string* `active` for any current route which begins with `user`.
### isActiveURL, is_active_url
Compares given URL path with current URL path.
```php
isActiveURL($url, $output = "active")
```
```php
is_active_url($url, $output = "active")
```
**Examples:**
If the current URL path is `/about`, function `isActiveURL('/about')` would return *string* `active`.
### isActiveMatch, is_active_match
Detects if the given string is found in the current URL.
```php
isActiveMatch($string, $output = "active")
```
```php
is_active_match($string, $output = "active")
```
**Examples:**
If the current URL path is `/about` or `/insideout`, function `isActiveMatch('out')` would return *string* `active`.
### areActiveRoutes, are_active_routes
Compares given array of route names with current route name.
```php
areActiveRoutes(array $routeNames, $output = "active")
```
```php
are_active_routes(array $routeNames, $output = "active")
```
**Examples:**
If the current route is `product.index` or `product.show`, function `areActiveRoutes(['product.index', 'product.show'])` would return *string* `active`.
_The `*` wildcard can be used for resource routes, including nested routes._
Function `areActiveRoutes(['user.*', 'product.*'])` would return *string* `active` for any current route which begins with `user` or `product`.
### areActiveURLs, are_active_urls
Compares given array of URL paths with current URL path.
```php
areActiveURLs(array $urls, $output = "active")
```
```php
are_active_urls(array $urls, $output = "active")
```
**Examples:**
If the current URL path is `/product` or `/product/create`, function `areActiveURLs(['/product', '/product/create'])` would return *string* `active`.
## Credits
Many thanks to:
- [@Jono20201](https://github.com/Jono20201) for implementing helper functions
- [@judgej](https://github.com/judgej) for implementing route wildcards
|
C++
|
UTF-8
| 2,940 | 3.265625 | 3 |
[] |
no_license
|
#include <iostream>
#include <random>
#include <ctime>
int main(){
int turnScore = 0;
int roll;
int compScore;
int playerScore;
int running = 0;
srand(time(NULL));
int selection;
int whatever;
int game = 1;
//game turn
while (game == 1)
{
while (running == 0)
{
roll = (rand() %6)+1;
//std::cout << roll << std::endl;
if (roll == 1){
std::cout << "CPU rolled a Pig! Turn over" << std::endl;
turnScore = 0;
running = 1;
}
else
{
std::cout << "CPU rolled ";
std::cout << roll << std::endl;
turnScore = turnScore + roll;
std::cout << "turn total: ";
std::cout << turnScore << std::endl;
if (turnScore >= 20)
{
compScore = compScore + turnScore;
if (compScore >= 100)
{
running = 2;
}
else
{
turnScore = 0;
running = 1;
}
}
}
}
while (running == 1)
{
std::cout << "Your turn, type a number and then enter to roll" << std::endl;
std::cin >> whatever;
roll = (rand() %6) + 1;
if (roll == 1){
std::cout << "You rolled a Pig! Turn over" << std::endl;
turnScore = 0;
running = 0;
}
else
{
std::cout << "You rolled ";
std::cout << roll << std::endl;
turnScore = turnScore + roll;
std::cout << "turn total: ";
std::cout << turnScore << std::endl;
std::cout << "Would you like to roll again? 1-yes, 2-no" << std::endl;
std::cin >> selection;
if (selection == 2)
{
playerScore = playerScore + turnScore;
if (playerScore >= 100)
{
running = 3;
}
else
{
turnScore = 0;
running = 0;
}
}
if (selection == 1)
{
running = 1;
}
}
}
while (running == 2)
{
std::cout<< "CPU WINS!!!!" << std::endl;
break;
}
while (running == 3)
{
std::cout << "You Win!" << std::endl;
break;
}
}
}
|
C#
|
UTF-8
| 506 | 2.90625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _09抽象类特点
{
class Program
{
static void Main(string[] args)
{
}
}
abstract class Person
{
public abstract int SayHello(string name);
// public abstract void Test();
}
class Student : Person
{
public override int SayHello(string name)
{
return 0;
}
}
}
|
Java
|
UTF-8
| 6,242 | 2.03125 | 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 mappers;
import beans.programaEsBean;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
*
* @author pedro
*/
public class descargaProgramasMapper3 implements Mapper{
public Object mapRow(ResultSet rs) throws SQLException {
programaEsBean dat = new programaEsBean();
if (rs.getString("NOM_CARRERA") != null) {
dat.setNOM_CARRERA(rs.getString("NOM_CARRERA").trim());
} else {
dat.setNOM_CARRERA(rs.getString("NOM_CARRERA"));
}
if (rs.getString("CVE_PLAN_EST") != null) {
dat.setCVE_PLAN_EST(rs.getString("CVE_PLAN_EST").trim());
} else {
dat.setCVE_PLAN_EST(rs.getString("CVE_PLAN_EST"));
}
if (rs.getString("ENFASIS") != null) {
dat.setENFASIS(rs.getString("ENFASIS").trim());
} else {
dat.setENFASIS(rs.getString("ENFASIS"));
}
if (rs.getString("VERSION") != null) {
dat.setVERSION(rs.getString("VERSION").trim());
} else {
dat.setVERSION(rs.getString("VERSION"));
}
if (rs.getString("NOMBRE_MATERIA") != null) {
dat.setNOMBRE_MATERIA(rs.getString("NOMBRE_MATERIA").trim());
} else {
dat.setNOMBRE_MATERIA(rs.getString("NOMBRE_MATERIA"));
}
if (rs.getString("NUMERO_PERIODO") != null) {
dat.setNUMERO_PERIODO(rs.getString("NUMERO_PERIODO").trim());
} else {
dat.setNUMERO_PERIODO(rs.getString("NUMERO_PERIODO"));
}
if (rs.getString("COMPETENCIA") != null) {
dat.setCOMPETENCIA(rs.getString("COMPETENCIA").trim());
} else {
dat.setCOMPETENCIA(rs.getString("COMPETENCIA"));
}
if (rs.getString("ACTIVIDAD") != null) {
dat.setACTIVIDAD(rs.getString("ACTIVIDAD").trim());
} else {
dat.setACTIVIDAD(rs.getString("ACTIVIDAD"));
}
if (rs.getString("ID_CCT_PLAN") != null) {
dat.setID_CCT_PLAN(rs.getString("ID_CCT_PLAN").trim());
} else {
dat.setID_CCT_PLAN(rs.getString("ID_CCT_PLAN"));
}
if (rs.getString("ID_MATERIA") != null) {
dat.setID_MATERIA(rs.getString("ID_MATERIA").trim());
} else {
dat.setID_MATERIA(rs.getString("ID_MATERIA"));
}
if (rs.getString("ID_COMPETENCIA") != null) {
dat.setID_COMPETENCIA(rs.getString("ID_COMPETENCIA").trim());
} else {
dat.setID_COMPETENCIA(rs.getString("ID_COMPETENCIA"));
}
if (rs.getString("ID_ACTIVIDAD") != null) {
dat.setID_ACTIVIDAD(rs.getString("ID_ACTIVIDAD").trim());
} else {
dat.setID_ACTIVIDAD(rs.getString("ID_ACTIVIDAD"));
}
if (rs.getString("DES_ACTIVIDAD") != null) {
dat.setDES_ACTIVIDAD(rs.getString("DES_ACTIVIDAD").trim());
} else {
dat.setDES_ACTIVIDAD(rs.getString("DES_ACTIVIDAD"));
}
if (rs.getString("VALIDAR") != null) {
dat.setVALIDAR(rs.getString("VALIDAR").trim());
} else {
dat.setVALIDAR(rs.getString("VALIDAR"));
}
if (rs.getString("NO_PASA") != null) {
dat.setNO_PASA(rs.getString("NO_PASA").trim());
} else {
dat.setNO_PASA(rs.getString("NO_PASA"));
}
if (rs.getString("INCLUIDA") != null) {
dat.setINCLUIDA(rs.getString("INCLUIDA").trim());
} else {
dat.setINCLUIDA(rs.getString("INCLUIDA"));
}
if (rs.getString("ID_LUGAR") != null) {
dat.setID_LUGAR(rs.getString("ID_LUGAR").trim());
} else {
dat.setID_LUGAR(rs.getString("ID_LUGAR"));
}
if (rs.getString("ID_HORA") != null) {
dat.setID_HORA(rs.getString("ID_HORA").trim());
} else {
dat.setID_HORA(rs.getString("ID_HORA"));
}
if (rs.getString("PLAN_ROTACION") != null) {
dat.setPLAN_ROTACION(rs.getString("PLAN_ROTACION").trim());
} else {
dat.setPLAN_ROTACION(rs.getString("PLAN_ROTACION"));
}
if (rs.getString("FECHA_REG") != null) {
dat.setFECHA_REG(rs.getString("FECHA_REG").trim());
} else {
dat.setFECHA_REG(rs.getString("FECHA_REG"));
}
if (rs.getString("ID_ACT_EVALUA") != null) {
dat.setID_ACT_EVALUA(rs.getString("ID_ACT_EVALUA").trim());
} else {
dat.setID_ACT_EVALUA(rs.getString("ID_ACT_EVALUA"));
}
if (rs.getString("EVIDENCIAS") != null) {
dat.setEVIDENCIAS(rs.getString("EVIDENCIAS").trim());
} else {
dat.setEVIDENCIAS(rs.getString("EVIDENCIAS"));
}
if (rs.getString("ID_ESCALA") != null) {
dat.setID_ESCALA(rs.getString("ID_ESCALA").trim());
} else {
dat.setID_ESCALA(rs.getString("ID_ESCALA"));
}
return dat;
}
}
|
PHP
|
UTF-8
| 285 | 2.671875 | 3 |
[] |
no_license
|
<?php
class SpeSkillTest{
function find($a) {
$odds = [];
$evens = [];
foreach ($a as $n) {
if ($n % 2) array_push($odds, $n);
else array_push($evens, $n);
}
return count($evens) === 1 ? $evens[0] : $odds[0];
}
}
?>
|
Java
|
UTF-8
| 1,214 | 3.28125 | 3 |
[] |
no_license
|
package modelo.juego;
import java.util.Comparator;
import static java.lang.Math.abs;
import static java.lang.Math.max;
public class Coordenada {
int row;
int col;
public Coordenada(int row, int col){
this.row = row;
this.col = col;
}
public int getCol() {
return col;
}
public int getRow() {
return row;
}
public int distanciaA(Coordenada unaCoordenada){
return max(abs(unaCoordenada.getRow() - row),abs(unaCoordenada.getCol() - col) );
}
public Coordenada sumar(Coordenada otraCoordenada){
return new Coordenada(this.row + otraCoordenada.getRow(),this.col + otraCoordenada.getCol());
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Coordenada that = (Coordenada) o;
if (row != that.row) return false;
return col == that.col;
}
@Override
public int hashCode() {
int result = row;
result = 31 * result + col;
return result;
}
@Override
public String toString() {
return "Coordenada [row=" + row + ", col=" + col + "]";
}
}
|
Python
|
UTF-8
| 3,871 | 2.609375 | 3 |
[] |
no_license
|
#!/bin/env python
import pandas as pd
from sqlalchemy import create_engine
import scipy.stats as stats
import sys
import pylab
import matplotlib.pyplot as plt
# ---- IMPORT CONSTANTS
UN, PW, H, DB, PORT = "", "", "", "", ""
WRITE_PATH = ""
try:
from settings import *
from bias.scripts import trimmed_mean
except ImportError as ex:
sys.stderr.write("Error: failed to import custom module ({})".format(ex))
pass
conn = create_engine("postgresql://" + UN + ":" + PW + "@" + H + ":" + PORT + "/" + DB, echo=False)
print("Created engine")
# ---- PULL GOE AND CALCULATE TRIMMED MEAN
goe_sql = """SELECT g.*, c.elt_type
FROM goe g
LEFT JOIN calls c
ON g.elt_id = c.elt_id
WHERE g.category = 'Sr';"""
goe_df = pd.read_sql(goe_sql, conn, index_col="line_id")
for disc in ["Men", "Ladies"]:
disc_df = goe_df.loc[goe_df["discipline"] == disc]
disc_tmeans = disc_df.groupby(["elt_type", "elt_id"]).apply(trimmed_mean, "goe").reset_index()
disc_tmeans.rename(columns={0: "trimmed_mean"}, inplace=True)
disc_tmeans.to_csv(WRITE_PATH + disc + "_goe_means.csv", mode="w", encoding="utf-8", header=True)
n_tot = disc_tmeans["trimmed_mean"].count()
print("Sr {0} overall: Shapiro (W, p-value), n = {1}".format(disc, n_tot), stats.shapiro(disc_tmeans["trimmed_mean"]))
print("Sr {0} overall: KS (W, p-value), n = {1}".format(disc, n_tot), stats.kstest(disc_tmeans["trimmed_mean"]
.astype('float'), 'norm'))
print("Sr {0} overall: Anderson-Darling (W, critical values, p-value), n = {1}".format(disc, n_tot),
stats.anderson(disc_tmeans["trimmed_mean"].astype('float'), 'norm'))
stats.probplot(disc_tmeans["trimmed_mean"].astype('float'), dist="norm", plot=pylab)
pylab.show()
plt.hist(disc_tmeans["trimmed_mean"].astype('float'), bins=20, normed=True)
plt.title("Sr " + disc + ", all elements")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.show()
jumps = disc_tmeans.loc[(disc_tmeans["elt_type"] == "jump")]
n_j = jumps["trimmed_mean"].count()
print("Sr {0} jumps: Shapiro (W, p-value), n = {1}".format(disc, n_j),
stats.shapiro(jumps["trimmed_mean"].astype('float')))
print("Sr {0} jumps: Kolmogorov-Smirnov (W, p-value), n = {1}".format(disc, n_j),
stats.kstest(jumps["trimmed_mean"].astype('float'), 'norm'))
print("Sr {0} jumps: Anderson-Darling (W, critical values, p-value), n = {1}".format(disc, n_j),
stats.anderson(jumps["trimmed_mean"].astype('float'), 'norm'))
stats.probplot(jumps["trimmed_mean"].astype('float'), dist="norm", plot=pylab)
pylab.show()
plt.hist(jumps["trimmed_mean"].astype('float'), bins=20, normed=True)
plt.title("Sr " + disc + ", jumps")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.show()
non_jumps = disc_tmeans.loc[(disc_tmeans["elt_type"] == "non_jump")]
n_nj = non_jumps["trimmed_mean"].count()
print("Sr {0} non jumps: Shapiro (W, p-value), n = {1}".format(disc, n_nj),
stats.shapiro(non_jumps["trimmed_mean"].astype('float')))
print("Sr {0} non jumps: KS (W, p-value), n = {1}".format(disc, n_nj),
stats.kstest(non_jumps["trimmed_mean"].astype('float'), 'norm'))
print("Sr {0} non jumps: Anderson-Darling (W, critical values, p-value), n = {1}".format(disc, n_nj),
stats.anderson(non_jumps["trimmed_mean"].astype('float'), 'norm'))
stats.probplot(non_jumps["trimmed_mean"].astype('float'), dist="norm", plot=pylab)
pylab.show()
stats.probplot(jumps["trimmed_mean"].astype('float'), dist="norm", plot=pylab)
pylab.show()
plt.hist(non_jumps["trimmed_mean"].astype('float'), bins=20, normed=True)
plt.title("Sr " + disc + ", non jumps")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.show()
|
Java
|
UTF-8
| 316 | 2.015625 | 2 |
[] |
no_license
|
public class TrocaDeSalas extends SistemadeCurso{
public static void main(String[] args) {
}
// private String;
private static String troca() {
if (x % 2 == 0) {
sala2[y] = sala1[x];
} else {
if (y % 2 == 1) {
sala1[x] = sala2[y];
}
}
return null;
}
}
|
Java
|
UTF-8
| 631 | 1.835938 | 2 |
[] |
no_license
|
package com.jd.cms.dao.appManagement;
import com.jd.cms.domain.appManagement.ArrCountObj;
import com.jd.cms.domain.clientmanager.SalerActive;
import com.jd.cms.domain.clientmanager.SalerActiveParameter;
import java.util.List;
/**
* Created by YYF on 14-5-9.
*/
public interface SalerActiveDao {
/**
* 促销员活跃度
*
* @param salerActiveParameter
* @return
*/
List<SalerActive> salerActive(SalerActiveParameter salerActiveParameter);
Integer salerCounts(SalerActiveParameter salerActiveParameter);
List<ArrCountObj> salerArrStat(SalerActiveParameter salerActiveParameter);
}
|
Python
|
UTF-8
| 9,414 | 2.734375 | 3 |
[] |
no_license
|
#Cube using primitives and truncation
#Made by:- Vandit Sheth
import sys
from OpenGL.GLUT import *
from OpenGL.GL import *
from OpenGL.GLU import *
#Flag for mode switching
flag=0
#Here the value of sets how deep th cut will be
a = 1
b = 0.3
c = a - b
#Setting defaults for rotation and truncation
press = 0
press1 = 0
xrot = 0.0
yrot = 0.0
zrot = 0.0
#Setting all the vertices(including the ones introduced on truncation)
v0 = [0,0,0]
v1 = [a,0,0]
v2 = [0,a,0]
v3 = [a,a,0]
v4 = [0,0,a]
v5 = [a,0,a]
v6 = [0,a,a]
v7 = [a,a,a]
v01 = [b,0,0]
v02 = [0,b,0]
v04 = [0,0,b]
v10 = [c,0,0]
v13 = [a,b,0]
v15 = [a,0,b]
v20 = [0,c,0]
v23 = [b,a,0]
v26 = [0,a,b]
v31 = [a,c,0]
v32 = [c,a,0]
v37 = [a,a,b]
v40 = [0,0,c]
v45 = [b,0,a]
v46 = [0,b,a]
v51 = [a,0,c]
v54 = [c,0,a]
v57 = [a,b,a]
v62 = [0,a,c]
v64 = [0,c,a]
v67 = [b,a,a]
v73 = [a,a,c]
v75 = [a,c,a]
v76 = [c,a,a]
#Front Face (which vertexes to include is decided based on press number)
def face0():
glBegin(GL_LINE_LOOP)
if press>=8:
glVertex3fv(v02)
else:
glVertex3fv(v0)
if press>=7:
glVertex3fv(v13)
else:
glVertex3fv(v1)
if press>=5:
glVertex3fv(v31)
else:
glVertex3fv(v3)
if press>=6:
glVertex3fv(v20)
else:
glVertex3fv(v2)
glEnd()
#Left side Face (which vertexes to include is decided based on press number)
def face1():
glBegin(GL_LINE_LOOP)
if press>=8:
glVertex3fv(v04)
glVertex3fv(v02)
else:
glVertex3fv(v0)
if press>=6:
glVertex3fv(v20)
glVertex3fv(v26)
else:
glVertex3fv(v2)
if press>=2:
glVertex3fv(v62)
glVertex3fv(v64)
else:
glVertex3fv(v6)
if press>=4:
glVertex3fv(v46)
glVertex3fv(v40)
else:
glVertex3fv(v4)
glEnd()
#Bottom face (which vertexes to include is decided based on press number)
def face2():
glBegin(GL_LINE_LOOP)
if press>=8:
glVertex3fv(v04)
else:
glVertex3fv(v0)
if press>=7:
glVertex3fv(v15)
else:
glVertex3fv(v1)
if press>=3:
glVertex3fv(v51)
else:
glVertex3fv(v5)
if press>=4:
glVertex3fv(v40)
else:
glVertex3fv(v4)
glEnd()
#Back Face (which vertexes to include is decided based on press number)
def face3():
glBegin(GL_LINE_LOOP)
if press>=1:
glVertex3fv(v75)
else:
glVertex3fv(v7)
if press>=2:
glVertex3fv(v64)
else:
glVertex3fv(v6)
if press>=4:
glVertex3fv(v46)
else:
glVertex3fv(v4)
if press>=3:
glVertex3fv(v57)
else:
glVertex3fv(v5)
glEnd()
#Right Side Face (which vertexes to include is decided based on press number)
def face4():
glBegin(GL_LINE_LOOP)
if press>=1:
glVertex3fv(v73)
glVertex3fv(v75)
else:
glVertex3fv(v7)
if press>=3:
glVertex3fv(v57)
glVertex3fv(v51)
else:
glVertex3fv(v5)
if press>=7:
glVertex3fv(v15)
glVertex3fv(v13)
else:
glVertex3fv(v1)
if press>=5:
glVertex3fv(v31)
glVertex3fv(v37)
else:
glVertex3fv(v3)
glEnd()
#Top Face (which vertexes to include is decided based on press number)
def face5():
glBegin(GL_LINE_LOOP)
if press>=1:
glVertex3fv(v73)
else:
glVertex3fv(v7)
if press>=2:
glVertex3fv(v62)
else:
glVertex3fv(v6)
if press>=6:
glVertex3fv(v26)
else:
glVertex3fv(v2)
if press>=5:
glVertex3fv(v37)
else:
glVertex3fv(v3)
glEnd()
#Front Face (which vertexes to include is decided based on press number)
def face01():
glBegin(GL_LINE_LOOP)
if press1>=8:
glVertex3fv(v02)
glVertex3fv(v01)
else:
glVertex3fv(v0)
if press1>=7:
glVertex3fv(v10)
glVertex3fv(v13)
else:
glVertex3fv(v1)
if press1>=5:
glVertex3fv(v31)
glVertex3fv(v32)
else:
glVertex3fv(v3)
if press1>=6:
glVertex3fv(v23)
glVertex3fv(v20)
else:
glVertex3fv(v2)
glEnd()
#Left Side Face (which vertexes to include is decided based on press number)
def face11():
glBegin(GL_LINE_LOOP)
if press1>=8:
glVertex3fv(v04)
glVertex3fv(v02)
else:
glVertex3fv(v0)
if press1>=6:
glVertex3fv(v20)
glVertex3fv(v26)
else:
glVertex3fv(v2)
if press1>=2:
glVertex3fv(v62)
glVertex3fv(v64)
else:
glVertex3fv(v6)
if press1>=4:
glVertex3fv(v46)
glVertex3fv(v40)
else:
glVertex3fv(v4)
glEnd()
#Bottom Face (which vertexes to include is decided based on press number)
def face21():
glBegin(GL_LINE_LOOP)
if press1>=8:
glVertex3fv(v04)
glVertex3fv(v01)
else:
glVertex3fv(v0)
if press1>=7:
glVertex3fv(v10)
glVertex3fv(v15)
else:
glVertex3fv(v1)
if press1>=3:
glVertex3fv(v51)
glVertex3fv(v54)
else:
glVertex3fv(v5)
if press1>=4:
glVertex3fv(v45)
glVertex3fv(v40)
else:
glVertex3fv(v4)
glEnd()
#Back Face (which vertexes to include is decided based on press number)
def face31():
glBegin(GL_LINE_LOOP)
if press1>=1:
glVertex3fv(v75)
glVertex3fv(v76)
else:
glVertex3fv(v7)
if press1>=2:
glVertex3fv(v67)
glVertex3fv(v64)
else:
glVertex3fv(v6)
if press1>=4:
glVertex3fv(v46)
glVertex3fv(v45)
else:
glVertex3fv(v4)
if press1>=3:
glVertex3fv(v54)
glVertex3fv(v57)
else:
glVertex3fv(v5)
glEnd()
#Right Side Face (which vertexes to include is decided based on press number)
def face41():
glBegin(GL_LINE_LOOP)
if press1>=1:
glVertex3fv(v73)
glVertex3fv(v75)
else:
glVertex3fv(v7)
if press1>=3:
glVertex3fv(v57)
glVertex3fv(v51)
else:
glVertex3fv(v5)
if press1>=7:
glVertex3fv(v15)
glVertex3fv(v13)
else:
glVertex3fv(v1)
if press1>=5:
glVertex3fv(v31)
glVertex3fv(v37)
else:
glVertex3fv(v3)
glEnd()
#Top Face (which vertexes to include is decided based on press number)
def face51():
glBegin(GL_LINE_LOOP)
if press1>=1:
glVertex3fv(v73)
glVertex3fv(v76)
else:
glVertex3fv(v7)
if press1>=2:
glVertex3fv(v67)
glVertex3fv(v62)
else:
glVertex3fv(v6)
if press1>=6:
glVertex3fv(v26)
glVertex3fv(v23)
else:
glVertex3fv(v2)
if press1>=5:
glVertex3fv(v32)
glVertex3fv(v37)
else:
glVertex3fv(v3)
glEnd()
#cube and cube1 act as data structure abstractions as faces are defined inside them
#Cube for rectangle truncate mode
def cube():
face0()
face1()
face2()
face3()
face4()
face5()
#Cube for triangle truncate mode
def cube1():
face01()
face11()
face21()
face31()
face41()
face51()
def display():
global flag
glClear (GL_COLOR_BUFFER_BIT)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glFrustum(-1.0, 1.0, -1.0, 1.0, 1, 5.0)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
gluLookAt (0.0, 0.0, 2.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0)
glColor3f (1.0, 1.0, 1.0)
#Rotating the cube in all 3 directions
glRotatef(xrot, 1.0, 0.0, 0.0)
glRotatef(yrot, 0.0, 1.0, 0.0)
glRotatef(zrot, 0.0, 0.0, 1.0)
glTranslatef(-0.5, -0.5, -0.5)
#Making cube based on the mode
if(flag==0):
cube()
else:
cube1()
glFlush ()
def keyboard(key, x, y):
global press, press1, flag, xrot, yrot, zrot
#Quit on Esc
if key == chr(27):
import sys
sys.exit(0)
#Cube rotation in x-direction
elif key == 'z':
xrot = xrot - 10.0
elif key == 'Z':
xrot = xrot + 10.0
#Cube rotation in y-direction
elif key == 'x':
yrot = yrot - 10.0
elif key == 'X':
yrot = yrot + 10.0
#Cube rotation in z-direction
elif key == 'c':
zrot = zrot - 10.0
elif key == 'C':
zrot = zrot + 10.0
#Incrementing key press to cut the edge/vertex of the cube(decided based on mode)
elif key == 'a':
if press1 < 8 and flag==1:
press1 = press1 + 1.0
if press < 8 and flag==0:
press = press + 2.0
elif key == 'A':
if press1 > 0 and flag==1:
press1 = press1 - 1.0
if press > 0 and flag==0:
press = press - 2.0
#Mode swithcing
elif key == 's':
press = 0
press1 = 0
if(flag==0):
flag=1
else:
flag=0
glutPostRedisplay()
glutInit(sys.argv)
glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB)
glutInitWindowSize (500, 500)
glutInitWindowPosition (0, 0)
glutCreateWindow ('Cube Edge/Corner Truncate')
glClearColor(0.0,0.0,0.0,0.0)
glutDisplayFunc(display)
glutKeyboardFunc(keyboard)
glutMainLoop()
|
Java
|
UTF-8
| 5,062 | 2 | 2 |
[] |
no_license
|
package com.bdtd.card.generator.web.config;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.DataSourceConfig;
import com.baomidou.mybatisplus.generator.config.GlobalConfig;
import com.baomidou.mybatisplus.generator.config.PackageConfig;
import com.baomidou.mybatisplus.generator.config.StrategyConfig;
import com.baomidou.mybatisplus.generator.config.TemplateConfig;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.engine.BeetlTemplateEngine;
import com.bdtd.card.common.util.FileUtil;
import com.bdtd.card.common.web.util.ToolUtil;
import com.bdtd.card.generator.web.engine.SimpleTemplateEngine;
import com.bdtd.card.generator.web.engine.base.GunsTemplateEngine;
import com.bdtd.card.generator.web.engine.config.ContextConfig;
import com.bdtd.card.generator.web.engine.config.SqlConfig;
/**
* 代码生成的抽象配置
*
* @author
* @date 2017-10-28-下午8:22
*/
public abstract class AbstractGeneratorConfig {
/**
* mybatis-plus代码生成器配置
*/
GlobalConfig globalConfig = new GlobalConfig();
DataSourceConfig dataSourceConfig = new DataSourceConfig();
StrategyConfig strategyConfig = new StrategyConfig();
PackageConfig packageConfig = new PackageConfig();
TableInfo tableInfo = null;
/**
* Guns代码生成器配置
*/
ContextConfig contextConfig = new ContextConfig();
SqlConfig sqlConfig = new SqlConfig();
protected abstract void config();
public void init() {
config();
packageConfig.setService(contextConfig.getDaoPackage() + ".service");
packageConfig.setServiceImpl(contextConfig.getDaoPackage() + ".service.impl");
//controller没用掉,生成之后会自动删掉
packageConfig.setController("TTT");
if (!contextConfig.getEntitySwitch()) {
packageConfig.setEntity("TTT");
}
if (!contextConfig.getDaoSwitch()) {
packageConfig.setMapper("TTT");
packageConfig.setXml("TTT");
}
if (!contextConfig.getServiceSwitch()) {
packageConfig.setService("TTT");
packageConfig.setServiceImpl("TTT");
}
}
/**
* 删除不必要的代码
*/
public void destory() {
String outputDir = globalConfig.getOutputDir() + "/TTT";
FileUtil.deleteDir(new File(outputDir));
}
public AbstractGeneratorConfig() {
}
public void doMpGeneration() {
init();
AutoGenerator autoGenerator = new AutoGenerator();
autoGenerator.setGlobalConfig(globalConfig);
autoGenerator.setDataSource(dataSourceConfig);
autoGenerator.setStrategy(strategyConfig);
autoGenerator.setPackageInfo(packageConfig);
autoGenerator.setTemplateEngine(new BeetlTemplateEngine());
TemplateConfig templateConfig = new TemplateConfig()
.setEntity("templates/entity.java").setXml("templates/mapper.xml");
autoGenerator.setTemplate(templateConfig);
InjectionConfig injectionConfig = new InjectionConfig() {
//自定义属性注入:abc
//在.ftl(或者是.vm)模板中,通过${cfg.abc}获取属性
@Override
public void initMap() {
Map<String, Object> map = new HashMap<>();
map.put("mapperFields", ToolUtil.getColumns(this.getConfig().getTableInfoList().get(0).getFields()));
map.put("mapperPrefixFields", ToolUtil.getPrefixColumns(this.getConfig().getTableInfoList().get(0).getFields()));
map.put("insertAllItems", ToolUtil.getInsertAllItems(this.getConfig().getTableInfoList().get(0).getFields()));
map.put("constructFields", ToolUtil.getConstractFields(this.getConfig().getTableInfoList().get(0).getFields()));
map.put("toString", ToolUtil.getToString(contextConfig.getEntityName(), this.getConfig().getTableInfoList().get(0).getFields()));
this.setMap(map);
}
};
//配置自定义属性注入
autoGenerator.setCfg(injectionConfig);
autoGenerator.execute();
destory();
//获取table信息,用于guns代码生成
List<TableInfo> tableInfoList = autoGenerator.getConfig().getTableInfoList();
if (tableInfoList != null && tableInfoList.size() > 0) {
this.tableInfo = tableInfoList.get(0);
}
}
public void doGunsGeneration() {
GunsTemplateEngine GunsTemplateEngine = new SimpleTemplateEngine();
GunsTemplateEngine.setContextConfig(contextConfig);
sqlConfig.setConnection(dataSourceConfig.getConn());
GunsTemplateEngine.setSqlConfig(sqlConfig);
GunsTemplateEngine.setTableInfo(tableInfo);
GunsTemplateEngine.start();
}
}
|
Markdown
|
UTF-8
| 7,235 | 3.15625 | 3 |
[] |
no_license
|
# **FindFlix**
[FindFlix](https://ariannasantiago.github.io/SES-app/) helps moviewatchers find film information and details. Users can view search results in the form of a set of movie cards/posters.
This website pulls data about movies using the [OMDB API](https://www.omdbapi.com), was bootstrapped with [Create React App](https://github.com/facebook/create-react-app), and meets the following deliverables:
1. After running a title search, users can view movie options through a responsive and mobile-friendly user interface, as well as the total number of results and pages available .
2. Movie options are presented with their release date, runtime, genre, and director. If available, a movie poster is displayed; if not, a generic blank poster is displayed.
3. Pagination features allowing users to view multiple pages of results returned by API.
4. "Show More" feature allows users to view more than 10 results at a time.
## **Instructions**
1. Enter a keyword or phrase into the search bar. As you input into the textbox, the _Search Term_ field will populate. All non-blank search terms are valid.
- 
2. Next, click **"Submit."** The results for search term _"Matilda"_ are shown below. For each movie card, a poster, movie title, release date, runtime, genre, director, and IMDB rating are displayed.
- <img src="https://media3.giphy.com/media/gbEvKQZ4bDBwj7zGNr/giphy.gif?cid=790b76119794c652e9817407ab2032bce0b15a090f818691&rid=giphy.gif&ct=g" >
3. To view the next/previous page of options, click **"Next Page"** or **"Previous Page"** above the search results. The next/previous set of 10 (or fewer) results are shown, and the _Current Page_ field is updated.
- <img src="https://media1.giphy.com/media/mPcNYfGvMbGnaD61Du/giphy.gif?cid=790b76110eccb37f894103aefc7da270c3d19a2739a8d1fa&rid=giphy.gif&ct=g" >
4. Another way to view more options is to click the **"Load More"** button at the bottom of the search results grid. The button text will change to **"Loading..."** while the results are rendered. The next 10 (or fewer) movies are added to the existing results, and _Current Page_ is updated.
- <img src="https://media2.giphy.com/media/P17bIOXLSDm5ZQoK7q/giphy.gif?cid=790b7611dafbbd6f449c6546439094eb7fdfb8834607ec8c&rid=giphy.gif&ct=g" >
5. If the last movie option has been reached, the **"Load More"** button is not shown.
- <img src="https://media2.giphy.com/media/rvDTCVIKBxR2EmUgMn/giphy.gif?cid=790b7611d78a8e836c2e77d1813ca611df5a2bdb0b368211&rid=giphy.gif&ct=g" >
6. Clicking either **"Previous Page"** or **"Next Page"** resets the number of movies displayed to 10.
- <img src="https://media4.giphy.com/media/zpR0kjJcQObDpcVs1X/giphy.gif?cid=790b76118c88e80d979726ea0dec4953a3dc3e2a01335694&rid=giphy.gif&ct=g" >
7. To search another term, simply scroll up and change your input. Search results are reset to 10 movies on page 1.
- <img src="https://media1.giphy.com/media/C7KxKvy30Mc9Mjde3E/giphy.gif?cid=790b7611dea6e9bd30c14d00a1d25df19f59664e2694f8d6&rid=giphy.gif&ct=g" >
## **Tools Used**
#### Languages and Frameworks
- ReactJS Framework (with Bootstrap)
- HTML
- CSS
- [OMDB (Open Movie DataBase) API](https://www.omdbapi.com)
- GitHub Pages
- Visual Studio Code
#### Resources
- OMDB-API app demo, Kristen Koyanagi
- C1 Office Hours
- Stack Overflow
- [Responsive Layouts Using CSS Grid](https://css-tricks.com/look-ma-no-media-queries-responsive-layouts-using-css-grid/#top-of-site) tutorial from css-tricks.com
- React Bootstrap Documentation (Cards and Grids)
## **Challenges Encountered**
- Figuring out the format with which to store my API key and "Now Playing" custom poster URL. It took some trial and error before I realized how simple it was.
- Learning how to re-query API for each individual movie title via its unique IMDB-ID. 2 main problems were encountered:
- I spent a long time figuring out how grab the actual 'Search' array from the .json response and using it to fill my 'movies' state array. I ended up rewriting much of my fetch function from scratch by following Kristen's tutorial. It turned out that I was missing a set of quotation marks!
- I had to think through the process of passing each individual movie's ID to my MovieCard component (minimizing unecessary information), and then set up the necessary state hooks.
- Through use of my network request log, I realized that a given search would query the API several times, resulting in multiple requests for each ID. Writing my asynch fetch function inside useEffect solved this.
- Understanding how grids work with Bootstrap, and figuring out how to make my card grid responsive beyond what the standard Card template was giving me.
- Learning how to position cards in my grid. Issue of uncentered cards still needs to be resolved.
- A one-step-behind issue with my pagination, in which the pageNum state was updated internally, but output did not change until re-rendering. After a lot of program tracing through my async functions, console logging, outputting state to the actual page, I was unable to find a fix. Thanks to help from C1's office hour, the solution was to write a useEffect function with a dependency array containing pageNum.
- Creating a GitHub respository and doing commits/pushes for the first time was quite intimidating, but I received some excellent guidance from C1 office hours.
- Note: first commit is attributed to a friend who was logged into her git on my computer. Her computer had crashed while working on a project, so she used my machine to rewrite and submit it. I didn't know to check the active git user before doing my first commit, but fixed it afterwards.
## **What I Learned**
This project was my first foray into web development, and seemed very overwhelming at first. However, I thoroughly enjoyed immersing myself in through online tutorials and the C1 SES office hours, and building upon my existing knowledge of basic program design and data structures. It was fun to utilize an API for the first time, and I'm excited to apply my new skills in other contexts. It was a fun challenge to learn how to use .json responses, especially with the nested arrays. I also learned how use GitHub and gain a decent grasp of Git commands, and I thought it was cool to deploy my first GitHub page! I look forward to continually improving upon this website, and implementing more features and functionality.
## **To Dos/Action Items**
- Allow users to input a date range and return corresponding results (potentially via a second "moviesFiltered" state array which is populated from general "movies" state array via a modification of LoadMore's fetch branch)
- Add more comments to improve code clarity, remove console.log()s once development is finished
- Improve error catch of MovieCard component
- Finish "Loading" status feature of MovieCard component
- Improve UI/UX of website, specifically responsive grid resizing and un-centered grid layout
## **Deployment**
A live demo of this app can be viewed here: [FindFlix](https://ariannasantiago.github.io/SES-app/)
### Notes:
- Fonts used: Playfair Display and Source Sans Pro
- Color Palette developed from header image
|
C#
|
UTF-8
| 3,242 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
using System;
using System.Collections;
using System.Reflection;
using System.Text;
using Google.Protobuf;
using UnityEngine;
namespace ETModel
{
public static class Dumper
{
private static readonly StringBuilder _text = new StringBuilder("", 1024);
private static void AppendIndent(int num)
{
_text.Append(' ', num);
}
private static void DoDump(object obj)
{
if (obj == null)
{
_text.Append("null");
_text.Append(",");
return;
}
Type t = obj.GetType();
//repeat field
if (obj is IList)
{
/*
_text.Append(t.FullName);
_text.Append(",");
AppendIndent(1);
*/
_text.Append("[");
IList list = obj as IList;
foreach (object v in list)
{
DoDump(v);
}
_text.Append("]");
}
else if (t.IsValueType)
{
_text.Append(obj);
_text.Append(",");
AppendIndent(1);
}
else if (obj is string)
{
_text.Append("\"");
_text.Append(obj);
_text.Append("\"");
_text.Append(",");
AppendIndent(1);
}
else if (obj is ByteString)
{
_text.Append("\"");
_text.Append(((ByteString) obj).bytes.Utf8ToStr());
_text.Append("\"");
_text.Append(",");
AppendIndent(1);
}
else if (t.IsArray)
{
Array a = (Array) obj;
_text.Append("[");
for (int i = 0; i < a.Length; i++)
{
_text.Append(i);
_text.Append(":");
DoDump(a.GetValue(i));
}
_text.Append("]");
}
else if (t.IsClass)
{
_text.Append($"<{t.Name}>");
_text.Append("{");
var fields = t.GetProperties(BindingFlags.Public | BindingFlags.Instance);
if (fields.Length > 0)
{
foreach (PropertyInfo info in fields)
{
_text.Append(info.Name);
_text.Append(":");
object value = info.GetGetMethod().Invoke(obj, null);
DoDump(value);
}
}
_text.Append("}");
}
else
{
Debug.LogWarning("unsupport type: " + t.FullName);
_text.Append(obj);
_text.Append(",");
AppendIndent(1);
}
}
public static string DumpAsString(object obj, string hint = "")
{
_text.Clear();
_text.Append(hint);
DoDump(obj);
return _text.ToString();
}
}
}
|
Java
|
UTF-8
| 1,321 | 2.234375 | 2 |
[] |
no_license
|
package com.root.wishlist.adapters;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.root.wishlist.pojo.search.SearchResult;
import com.root.wishlist.R;
import java.util.List;
public class HotSearcAdapter extends BaseAdapter {
List<SearchResult> CompanyDetails;
Context context;
private android.widget.TextView companyname;
public HotSearcAdapter(Context context, List<SearchResult> CompanyDetails) {
this.context = context;
this.CompanyDetails = CompanyDetails;
}
@Override
public int getCount() {
return CompanyDetails.size();
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View view, ViewGroup viewGroup) {
view = (LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.hotsearchcompany, viewGroup, false));
this.companyname = (TextView) view.findViewById(R.id.company_name);
companyname.setText(CompanyDetails.get(position).getTitle().toString());
return view;
}
}
|
PHP
|
UTF-8
| 985 | 2.6875 | 3 |
[] |
no_license
|
<?php
namespace spec\DesignPatterns\Builder;
use DesignPatterns\Builder\CurlCommand;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
class CurlBuilderSpec extends ObjectBehavior
{
function let()
{
$this->beConstructedWithUrl('google.com');
}
function it_can_build_a_CurlCommand()
{
$this->build()->shouldHaveType(CurlCommand::class);
}
function it_can_build_with_data()
{
$this->withData(['foo' => 'bar'])->shouldReturn($this);
$command = $this->build();
$command->options()->shouldBeLike(['data' => ['foo' => 'bar'], 'method' => 'GET']);
}
function it_can_change_the_request_method()
{
$this->withMethod('POST')->shouldReturn($this);
$command = $this->build();
$command->options()->shouldContain('POST');
}
function it_can_build_an_immutable_curl_command()
{
$command1 = $this->build();
$this->build()->shouldNotEqual($command1);
}
}
|
Java
|
UTF-8
| 2,111 | 3.046875 | 3 |
[
"MIT"
] |
permissive
|
package matrix;
import datastructures.util.InputUtil;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertArrayEquals;
public class TestCircularMatrix {
private static String inputFile = "input_files/matrix/circular_matrix/test_case";
private static String[] input = null;
@BeforeClass
public static void setup() {
input = InputUtil.readContents(inputFile);
}
@AfterClass
public static void teardown() {
input = null;
}
@Test
public void testCircularMatrixTestCase1() {
String[] values = input[0].split(" ");
assertCircularMatrix(values, new int[][]{new int[]{1, 2, 3, 4}, new int[]{12, 13, 14, 5},
new int[]{11, 16, 15, 6}, new int[]{10, 9, 8, 7}});
}
@Test
public void testCircularMatrixTestCase2() {
String[] values = input[1].split(" ");
assertCircularMatrix(values,
new int[][]{new int[]{1, 2, 3, 4}, new int[]{10, 11, 12, 5}, new int[]{9, 8, 7, 6}});
}
@Test
public void testCircularMatrixTestCase3() {
String[] values = input[2].split(" ");
assertCircularMatrix(values, new int[][]{new int[]{1}});
}
@Test
public void testCircularMatrixTestCase4() {
String[] values = input[3].split(" ");
assertCircularMatrix(values,
new int[][]{new int[]{1, 2, 3, 4}, new int[]{24, 25, 26, 5}, new int[]{23, 40, 27, 6},
new int[]{22, 39, 28, 7}, new int[]{21, 38, 29, 8}, new int[]{20, 37, 30, 9},
new int[]{19, 36, 31, 10}, new int[]{18, 35, 32, 11}, new int[]{17, 34, 33, 12},
new int[]{16, 15, 14, 13}});
}
private void assertCircularMatrix(String[] values, int[][] expected) {
int m = Integer.parseInt(values[0]);
int n = Integer.parseInt(values[1]);
int[][] output = CircularMatrix.constructMatrix(m, n);
for (int i = 0; i < output.length; i++) {
assertArrayEquals(expected[i], output[i]);
}
}
}
|
Markdown
|
UTF-8
| 1,681 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
<!-- Source: https://github.com/kiloforce/markdowntest/README.md -->
# This is an h1 level tag
## This is an h2 level tag
###### This is an h6 level tag
<!-- This is a
comment, has to be on a new line! -->
<!-- line breaks are merged -->
Roses are Red
Violets are Blue
Text Styles:
*This text will be italic*
_This will also be italic_
**This text will be bold**
__This will also be bold__
___This will be combined bold and italic___
***This will also be combined bold and italic***
Unordered Lists:
* Item 1
* Item 2
* Item 2a
* Item 2b
Ordered Lists:
<!-- make sure to have a line seperation -->
1. Item 1
2. Item 2
3. Item 3
* Item 3a
* Item 3b
Images:

Format: 
Links:
http://github.com - automatic!
[GitHub](http://github.com)
Blockquotes:
As Kanye West said:
> We're living the future so
> the present is our past.
Syntax highlighting:
```javascript
function fancyAlert(arg) {
if(arg) {
$.facebox({div:'#foo'})
}
}
```
```
This is how you do
preformatted text
XX
XX XX
```
Here is a Python code example
without syntax highlighting:
<!-- Make sure to have 4 spaces in front -->
def foo:
if not bar:
return true
`
I am in a box, but I am not preformatted
XX
XX XX
`
Task Lists:
- [ ] a task list item
- [ ] list syntax required
- [ ] normal **formatting**,
@mentions, #1234 refs
- [ ] incomplete
- [x] completed
I think you should use an
`<addr>` element here instead.
|
Python
|
UTF-8
| 2,471 | 3.421875 | 3 |
[] |
no_license
|
"""
Dungeon setup file
"""
from modules import Room, Enemy, Friend, Item, RPGInfo
def init():
room_objects = {}
room_data = {
"Kitchen": {
"description": "A dank and dirty room buzzing with flies"
,
"links": {"Dining Hall": "south"}
},
"Ballroom": {
"description": ("A vast room with a shiny wooden floor; huge "
"candlesticks guard the entrance")
,
"links": {"Dining Hall": "east"}
},
"Dining Hall": {
"description": ("A large room with ornate golden decorations "
"on each wall")
,
"links": {"Kitchen": "north", "Ballroom": "west"}
}
}
# For every room, generate a Room object and apply data from room_data
# dictionary
for key in room_data.keys():
room_objects[key] = Room(key)
room_objects[key].set_description(room_data[key]["description"])
# For every room, check for links with other rooms and apply
for room in room_data.keys():
if room in room_data[key]["links"].keys():
room_objects[key].link_room(room, room_data[key]["links"][room])
# Items setup
cheese = Item("Cheese")
candle = Item("Candleabre")
sword = Item("Sword Of Vengeance")
ring = Item("Ring Of Ultimate Power")
cheese.set_description("Glibberish; Smells like old socks")
candle.set_description("A massive device with six candles")
sword.set_description("A mighty blade of dark metal")
ring.set_description("A heavy ring with a blue glowing jewel")
room_objects["Kitchen"].add_item(cheese)
room_objects["Kitchen"].add_item(candle)
room_objects["Dining Hall"].add_item(ring)
room_objects["Ballroom"].add_item(sword)
# Enemy/NPC setup
dave = Enemy("Dave", "A smelly zombie")
dave.set_conversation("Brrlgrh... rgrhl... brains...")
dave.set_weakness("Cheese")
sarah = Friend("Sarah", "The farmers' lost daughter")
sarah.set_conversation("Please, can you help me escape? It's so dark in "
"this place.")
sarah.set_weakness("Candleabre")
room_objects["Ballroom"].set_character(sarah)
room_objects["Dining Hall"].set_character(dave)
# Game setup
my_game = RPGInfo("Mini Dungeon")
my_game.welcome()
RPGInfo.info()
RPGInfo.author = "BM"
RPGInfo.credits()
return room_objects["Kitchen"]
|
Java
|
UTF-8
| 16,584 | 1.5 | 2 |
[
"MIT"
] |
permissive
|
/*
* oxTrust is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
*
* Copyright (c) 2014, Gluu
*/
package org.gluu.oxtrust.ldap.service;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.inject.Named;
import javax.mail.AuthenticationFailedException;
import javax.mail.MessagingException;
import org.apache.commons.lang.StringUtils;
import org.gluu.oxtrust.model.GluuAppliance;
import org.gluu.oxtrust.model.GluuCustomAttribute;
import org.gluu.oxtrust.model.GluuMetadataSourceType;
import org.gluu.oxtrust.model.GluuSAMLTrustRelationship;
import org.gluu.oxtrust.model.OrganizationalUnit;
import org.gluu.oxtrust.util.MailUtils;
import org.gluu.oxtrust.util.OxTrustConstants;
import org.gluu.site.ldap.persistence.LdapEntryManager;
import org.slf4j.Logger;
import org.xdi.config.oxtrust.AppConfiguration;
import org.xdi.ldap.model.GluuStatus;
import org.xdi.ldap.model.InumEntry;
import org.xdi.model.GluuAttribute;
import org.xdi.model.TrustContact;
import org.xdi.service.XmlService;
import org.xdi.util.INumGenerator;
import org.xdi.util.StringHelper;
import com.unboundid.ldap.sdk.Filter;
/**
* Provides operations with trust relationships
*
* @author Pankaj
* @author Yuriy Movchan Date: 11.05.2010
*
*/
@Stateless
@Named("trustService")
public class TrustService implements Serializable {
private static final long serialVersionUID = -8128546040230316737L;
@Inject
private Logger log;
@Inject
private LdapEntryManager ldapEntryManager;
@Inject
private AttributeService attributeService;
@Inject
private ApplianceService applianceService;
@Inject
private XmlService xmlService;
public static final String GENERATED_SSL_ARTIFACTS_DIR = "ssl";
@Inject
private AppConfiguration appConfiguration;
public void addTrustRelationship(GluuSAMLTrustRelationship trustRelationship) {
log.info("Creating TR " + trustRelationship.getInum());
String[] clusterMembers = appConfiguration.getClusteredInums();
String applianceInum = appConfiguration.getApplianceInum();
if (clusterMembers == null || clusterMembers.length == 0) {
log.debug("there is no cluster configuration. Assuming standalone appliance.");
clusterMembers = new String[] { applianceInum };
}
String dn = trustRelationship.getDn();
for (String clusterMember : clusterMembers) {
String clusteredDN = StringHelper.replaceLast(dn, applianceInum, clusterMember);
trustRelationship.setDn(clusteredDN);
GluuSAMLTrustRelationship tr = new GluuSAMLTrustRelationship();
tr.setDn(trustRelationship.getDn());
if(! containsTrustRelationship(tr)){
log.debug("Adding TR" + clusteredDN);
OrganizationalUnit ou = new OrganizationalUnit();
ou.setDn(getDnForTrustRelationShip(null));
if(! ldapEntryManager.contains(ou)){
ldapEntryManager.persist(ou);
}
ldapEntryManager.persist(trustRelationship);
}else{
ldapEntryManager.merge(trustRelationship);
}
}
trustRelationship.setDn(dn);
}
public void updateTrustRelationship(GluuSAMLTrustRelationship trustRelationship) {
log.debug("Updating TR " + trustRelationship.getInum());
String[] clusterMembers = appConfiguration.getClusteredInums();
String applianceInum = appConfiguration.getApplianceInum();
if (clusterMembers == null || clusterMembers.length == 0) {
log.debug("there is no cluster configuration. Assuming standalone appliance.");
clusterMembers = new String[] { applianceInum };
}
String dn = trustRelationship.getDn();
for (String clusterMember : clusterMembers) {
String clusteredDN = StringHelper.replaceLast(dn, applianceInum, clusterMember);
trustRelationship.setDn(clusteredDN);
GluuSAMLTrustRelationship tr = new GluuSAMLTrustRelationship();
tr.setDn(trustRelationship.getDn());
if(containsTrustRelationship(tr)){
log.trace("Updating TR" + clusteredDN);
ldapEntryManager.merge(trustRelationship);
}else{
OrganizationalUnit ou = new OrganizationalUnit();
ou.setDn(getDnForTrustRelationShip(null));
if(! ldapEntryManager.contains(ou)){
ldapEntryManager.persist(ou);
}
ldapEntryManager.persist(trustRelationship);
}
}
trustRelationship.setDn(dn);
}
public void removeTrustRelationship(GluuSAMLTrustRelationship trustRelationship) {
log.info("Removing TR " + trustRelationship.getInum());
String[] clusterMembers = appConfiguration.getClusteredInums();
String applianceInum = appConfiguration.getApplianceInum();
if (clusterMembers == null || clusterMembers.length == 0) {
log.debug("there is no cluster configuration. Assuming standalone appliance.");
clusterMembers = new String[] { applianceInum };
}
String dn = trustRelationship.getDn();
for (String clusterMember : clusterMembers) {
String clusteredDN = StringHelper.replaceLast(dn, applianceInum, clusterMember);
trustRelationship.setDn(clusteredDN);
GluuSAMLTrustRelationship tr = new GluuSAMLTrustRelationship();
tr.setDn(trustRelationship.getDn());
if(containsTrustRelationship(tr)){
log.debug("Removing TR" + clusteredDN);
ldapEntryManager.remove(trustRelationship);
}
}
trustRelationship.setDn(dn);
}
public GluuSAMLTrustRelationship getRelationshipByInum(String inum) {
return ldapEntryManager.find(GluuSAMLTrustRelationship.class, getDnForTrustRelationShip(inum));
}
public GluuSAMLTrustRelationship getRelationshipByDn(String dn) {
if (StringHelper.isNotEmpty(dn)) {
return ldapEntryManager.find(GluuSAMLTrustRelationship.class, dn);
}
return null;
}
/**
* This is a LDAP operation as LDAP and IDP will always be in sync. We can
* just call LDAP to fetch all Trust Relationships.
*/
public List<GluuSAMLTrustRelationship> getAllTrustRelationships() {
return ldapEntryManager.findEntries(getDnForTrustRelationShip(null), GluuSAMLTrustRelationship.class, null);
}
public List<GluuSAMLTrustRelationship> getAllActiveTrustRelationships() {
GluuSAMLTrustRelationship trustRelationship = new GluuSAMLTrustRelationship();
trustRelationship.setBaseDn(getDnForTrustRelationShip(null));
trustRelationship.setStatus(GluuStatus.ACTIVE);
return ldapEntryManager.findEntries(trustRelationship);
}
public List<GluuSAMLTrustRelationship> getAllFederations() {
List<GluuSAMLTrustRelationship> result = new ArrayList<GluuSAMLTrustRelationship>();
for (GluuSAMLTrustRelationship trust : getAllActiveTrustRelationships()) {
if (trust.isFederation()) {
result.add(trust);
}
}
return result;
}
public List<GluuSAMLTrustRelationship> getAllOtherFederations(String inum) {
List<GluuSAMLTrustRelationship> result = getAllFederations();
result.remove(getRelationshipByInum(inum));
return result;
}
/**
* Check if LDAP server contains trust relationship with specified
* attributes
*
* @return True if trust relationship with specified attributes exist
*/
public boolean containsTrustRelationship(GluuSAMLTrustRelationship trustRelationship) {
return ldapEntryManager.contains(trustRelationship);
}
/**
* Generate new inum for trust relationship
*
* @return New inum for trust relationship
*/
public String generateInumForNewTrustRelationship() {
InumEntry entry = new InumEntry();
String newDn = appConfiguration.getBaseDN();
entry.setDn(newDn);
String newInum;
do {
newInum = generateInumForNewTrustRelationshipImpl();
entry.setInum(newInum);
} while (ldapEntryManager.contains(entry));
return newInum;
}
/**
* Generate new inum for trust relationship
*
* @return New inum for trust relationship
*/
private String generateInumForNewTrustRelationshipImpl() {
return getApplianceInum() + OxTrustConstants.inumDelimiter + "0006" + OxTrustConstants.inumDelimiter + INumGenerator.generate(2);
}
/**
* Return current organization inum
*
* @return Current organization inum
*/
private String getApplianceInum() {
return appConfiguration.getApplianceInum();
}
/**
* Get all metadata source types
*
* @return Array of metadata source types
*/
public GluuMetadataSourceType[] getMetadataSourceTypes() {
return GluuMetadataSourceType.values();
}
/**
* Build DN string for trust relationship
*
* @param inum
* Inum
* @return DN string for specified trust relationship or DN for trust
* relationships branch if inum is null
*/
public String getDnForTrustRelationShip(String inum) {
String applianceDN = applianceService.getDnForAppliance();
if (StringHelper.isEmpty(inum)) {
return String.format("ou=trustRelationships,%s", applianceDN);
}
return String.format("inum=%s,ou=trustRelationships,%s", inum, applianceDN);
}
public void updateReleasedAttributes(GluuSAMLTrustRelationship trustRelationship) {
List<String> releasedAttributes = new ArrayList<String>();
String mailMsg = "";
for (GluuCustomAttribute customAttribute : trustRelationship.getReleasedCustomAttributes()) {
if (customAttribute.isNew()) {
mailMsg += "\nAttribute name: " + customAttribute.getName() + " Display name: "
+ customAttribute.getMetadata().getDisplayName() + " Attribute value: " + customAttribute.getValue();
customAttribute.setNew(false);
}
releasedAttributes.add(customAttribute.getMetadata().getDn());
}
// send email notification
if (!StringUtils.isEmpty(mailMsg)) {
try {
GluuAppliance appliance = applianceService.getAppliance();
if (appliance.getContactEmail() == null || appliance.getContactEmail().isEmpty())
log.warn("Failed to send the 'Attributes released' notification email: unconfigured contact email");
else if (appliance.getSmtpHost() == null || appliance.getSmtpHost().isEmpty())
log.warn("Failed to send the 'Attributes released' notification email: unconfigured SMTP server");
else {
String preMsg = "Trust RelationShip name: " + trustRelationship.getDisplayName() + " (inum:" + trustRelationship.getInum()
+ ")\n\n";
String subj = "Attributes with Privacy level 5 are released in a Trust Relationaship";
MailUtils mail = new MailUtils(appliance.getSmtpHost(), appliance.getSmtpPort(), appliance.isRequiresSsl(),
appliance.isRequiresAuthentication(), appliance.getSmtpUserName(), applianceService.getDecryptedSmtpPassword(appliance));
mail.sendMail(appliance.getSmtpFromName() + " <" + appliance.getSmtpFromEmailAddress() + ">", appliance.getContactEmail(),
subj, preMsg + mailMsg);
}
} catch (AuthenticationFailedException ex) {
log.error("SMTP Authentication Error: ", ex);
} catch (MessagingException ex) {
log.error("SMTP Host Connection Error", ex);
} catch (Exception ex) {
log.error("Failed to send the notification email: ", ex);
}
}
if (!releasedAttributes.isEmpty()) {
trustRelationship.setReleasedAttributes(releasedAttributes);
} else {
trustRelationship.setReleasedAttributes(null);
}
}
public List<TrustContact> getContacts(GluuSAMLTrustRelationship trustRelationship) {
List<String> gluuTrustContacts = trustRelationship.getGluuTrustContact();
List<TrustContact> contacts = new ArrayList<TrustContact>();
if (gluuTrustContacts != null) {
for (String contact : gluuTrustContacts) {
contacts.add(xmlService.getTrustContactFromXML(contact));
}
}
return contacts;
}
public void saveContacts(GluuSAMLTrustRelationship trustRelationship, List<TrustContact> contacts) {
if (contacts != null && !contacts.isEmpty()) {
List<String> gluuTrustContacts = new ArrayList<String>();
for (TrustContact contact : contacts) {
gluuTrustContacts.add(xmlService.getXMLFromTrustContact(contact));
}
trustRelationship.setGluuTrustContact(gluuTrustContacts);
}
}
// public List<DeconstructedTrustRelationship>
// getDeconstruction(GluuSAMLTrustRelationship trustRelationship) {
// List<String> gluuTrustDeconstruction =
// trustRelationship.getGluuTrustDeconstruction();
// List<DeconstructedTrustRelationship> deconstruction = new
// ArrayList<DeconstructedTrustRelationship>();
// if(gluuTrustDeconstruction != null){
// for (String deconstructedTR : gluuTrustDeconstruction){
// deconstruction.add(xmlService.getDeconstructedTrustRelationshipFromXML(deconstructedTR));
// }
// }
// return deconstruction;
// }
//
// public void saveDeconstruction(GluuSAMLTrustRelationship
// trustRelationship,
// List<DeconstructedTrustRelationship> deconstruction) {
// List<String> gluuTrustDeconstruction = new ArrayList<String>();
// for (DeconstructedTrustRelationship deconstructedTR : deconstruction){
// gluuTrustDeconstruction.add(xmlService.getXMLFromDeconstructedTrustRelationship(deconstructedTR));
// }
// trustRelationship.setGluuTrustDeconstruction(gluuTrustDeconstruction);
// }
public List<GluuSAMLTrustRelationship> getDeconstructedTrustRelationships(GluuSAMLTrustRelationship trustRelationship) {
List<GluuSAMLTrustRelationship> result = new ArrayList<GluuSAMLTrustRelationship>();
for (GluuSAMLTrustRelationship trust : getAllTrustRelationships()) {
if (trustRelationship.equals(trust.getContainerFederation())) {
result.add(trust);
}
}
return result;
}
public GluuSAMLTrustRelationship getTrustByUnpunctuatedInum(String unpunctuated) {
for (GluuSAMLTrustRelationship trust : getAllTrustRelationships()) {
if (StringHelper.removePunctuation(trust.getInum()).equals(unpunctuated)) {
return trust;
}
}
return null;
}
public List<GluuSAMLTrustRelationship> searchSAMLTrustRelationships(String pattern, int sizeLimit) {
String[] targetArray = new String[] { pattern };
Filter displayNameFilter = Filter.createSubstringFilter(OxTrustConstants.displayName, null, targetArray, null);
Filter descriptionFilter = Filter.createSubstringFilter(OxTrustConstants.description, null, targetArray, null);
Filter inameFilter = Filter.createSubstringFilter(OxTrustConstants.iname, null, targetArray, null);
Filter inumFilter = Filter.createSubstringFilter(OxTrustConstants.inum, null, targetArray, null);
Filter searchFilter = Filter.createORFilter(displayNameFilter, descriptionFilter, inameFilter, inumFilter);
List<GluuSAMLTrustRelationship> result = ldapEntryManager.findEntries(getDnForTrustRelationShip(null), GluuSAMLTrustRelationship.class, searchFilter, 0, sizeLimit);
return result;
}
public List<GluuSAMLTrustRelationship> getAllSAMLTrustRelationships(int sizeLimit) {
return ldapEntryManager.findEntries(getDnForTrustRelationShip(null), GluuSAMLTrustRelationship.class, null, 0, sizeLimit);
}
/**
* Remove attribute
*
* @param attribute
* Attribute
*/
public boolean removeAttribute(GluuAttribute attribute) {
log.info("Attribute removal started");
log.trace("Removing attribute from trustRelationships");
List<GluuSAMLTrustRelationship> trustRelationships = getAllTrustRelationships();
log.trace(String.format("Iterating '%d' trustRelationships", trustRelationships.size()));
for (GluuSAMLTrustRelationship trustRelationship : trustRelationships) {
log.trace("Analyzing '%s'.", trustRelationship.getDisplayName());
List<String> customAttrs = trustRelationship.getReleasedAttributes();
if (customAttrs != null) {
for (String attrDN : customAttrs) {
log.trace("'%s' has custom attribute '%s'", trustRelationship.getDisplayName(), attrDN);
if (attrDN.equals(attribute.getDn())) {
log.trace("'%s' matches '%s'. deleting it.", attrDN, attribute.getDn());
List<String> updatedAttrs = new ArrayList<String>();
updatedAttrs.addAll(customAttrs);
updatedAttrs.remove(attrDN);
if (updatedAttrs.size() == 0) {
trustRelationship.setReleasedAttributes(null);
} else {
trustRelationship.setReleasedAttributes(updatedAttrs);
}
updateTrustRelationship(trustRelationship);
break;
}
}
}
}
attributeService.removeAttribute(attribute);
return true;
}
}
|
Python
|
UTF-8
| 7,528 | 2.71875 | 3 |
[] |
no_license
|
import unittest
from Supervisor import BaseSupervisor
from Agent import BaseAgent
from mesa.time import RandomActivation
import numpy as np
from MeasurementGen import *
from DecisionLogic import *
from RewardLogic import *
from EvaluationLogic import *
class TestBaseSupervisor(unittest.TestCase):
"""
This class testes the base supervisor
"""
def __init__(self, *args, **kwargs):
super(TestBaseSupervisor, self).__init__(*args, **kwargs)
self.N=np.random.randint(1,100)
#self.N=5
self.s=BaseSupervisor(self.N,evaluation_fct=EmptyEvaluationLogic)
def test_init_population(self):
"""
Test that the population is initialized correctly
"""
self.assertIsInstance(self.s.schedule,RandomActivation) # test that the scheduler is initialized
self.assertEqual(len(self.s.schedule.agents),self.N) # test that the population has the right length
ids=[]
for a in self.s.schedule.agents:
self.assertIsInstance(a,BaseAgent) # test that agents have the right type
self.assertNotEqual(a.decision_fct,None)
ids.append(a.unique_id)
self.assertTrue(len(np.unique(ids)),self.N) # test that agents are different instances
def test_init_emptypopulation_fail(self):
"""
Test that the program fails if the population is initialized empty
"""
N=0
self.assertRaises(AssertionError,lambda: BaseSupervisor(N))
def test_init_measurements(self):
class TestMeasurementGen(BaseMeasurementGen):
def get_measurements(self,pop,i):
return [{1:2}]*len(pop)
self.assertNotEqual(self.s.measurement_fct,None)
self.s.measurement_fct=TestMeasurementGen()
measurements=self.s.measurements(0)
self.assertEqual(len(measurements),self.N)
for i in measurements:
self.assertEqual(i,{1:2})
def test_perceptionDict(self):
"""
Test that perception dictionaries are generated correctly
"""
T=np.random.randint(1,100)
pdict=self.s.perception_dict(T)
self.assertIsInstance(pdict,list)
self.assertEqual(len(pdict),self.N)
for i,d in zip(range(len(pdict)),pdict):
self.assertIsInstance(d,dict)
self.assertEqual(d["agentID"],i) # update is correct
def test_perception(self):
"""
Test how perceptions are given to the agents
"""
T=np.random.randint(1,100)
perceptions=self.s.perception_dict(T) # generate measurements
self.s.perception(perceptions)
for i,a in zip(range(self.N),self.s.schedule.agents):
val=a.current_state["perception"]
self.assertEqual(val["agentID"],i)
self.assertEqual(val["timestep"],T)
def test_update_measurement(self):
"""
Tests that the measurements are updated at each step
"""
self.s.measurement_fct=MeasurementGenTesting()
self.s.step()
ms=self.s.current_state["perception"]
self.assertTrue(all([m["value"]==0 for m in ms]))
self.s.step()
self.s.step()
ms=self.s.current_state["perception"]
self.assertTrue(all([m["value"]==2 for m in ms]))
def test_update_measurements_agents(self):
"""
Tests that the perceptions of all agents are updated at each step
"""
self.s.measurement_fct=MeasurementGenTesting()
self.s.step()
ms=[a.current_state["perception"] for a in self.s.schedule.agents]
self.assertTrue(all([m["value"]==0 for m in ms]))
self.s.step()
self.s.step()
ms=[a.current_state["perception"] for a in self.s.schedule.agents]
self.assertTrue(all([m["value"]==2 for m in ms]))
def test_update_feedback(self):
"""
Tests that the decision function obtains the feedback after each step
"""
self.s.decision_fct=DecisionLogicTesting() # update the decision logic
self.s.measurement_fct=MeasurementGenTesting()
self.s.step()
self.assertNotEqual(self.s.decision_fct.last_actions,None) # actions have been updated
self.assertEqual(self.s.current_state["perception"],self.s.decision_fct.values["p"]) # perception has been updated
self.assertEqual(self.s.current_state["reward"],self.s.decision_fct.values["r"]) # rewards have been updated
def test_decisions(self):
"""
Test that the supervisor collects decisions correctly from the agents
"""
for a in self.s.schedule.agents:
a.decision_fct=DecisionLogicTestingDynamic(a) # update decision fcts of agents
self.s.decision_fct=DecisionLogicSupervisorTesting(self.s) # update supervisor's decision fct
percs=[{j:j for j in range(i)} for i in range(len(self.s.schedule.agents))] # create perceptions
decs=self.s.decisions(percs)
self.assertEqual(len(decs["agents"]),self.s.N)
self.assertEqual(decs["agents"],list(range(self.s.N)))
# check that the decision is correctly updated after every timestep
self.s.step()
self.s.step()
decs=self.s.decisions(percs)
self.assertEqual(decs["agents"],list(range(self.s.N))) # actions do not change
self.assertEqual(decs["timestep"],2) # timestamp is updated
class DecisionLogicTesting(BaseDecisionLogic):
def __init__(self):
self.values={}
def feedback(self,perceptions,reward):
self.values={"p":perceptions,"r":reward}
class DecisionLogicTestingDynamic(BaseDecisionLogic):
"""
Returns a constant decision
"""
def get_decision(self,perceptions):
self.last_actions=len(perceptions)
return self.last_actions
class DecisionLogicSupervisorTesting(BaseDecisionLogic):
"""
Returns a constant decision
"""
def get_decision(self,perceptions):
decs={"timestep":self.model.schedule.steps,"agents":[a.decisions(perceptions[n]) for a,n in zip(self.model.schedule.agents,range(self.model.N))]} # call each agent's decision fct with the appropriate perception
return decs
class MeasurementGenTesting():
def __init__(self):
self.counter=0
def get_measurements(self,population,timestep):
"""
Returns a list of dictionaries containing the measurements: the state of each agent at the current timestep
"""
ret=[{"value":self.counter,"timestep":timestep,"agentID":i} for i in range(len(population))]
self.counter+=1
return ret
class EmptyEvaluationLogic(BaseEvaluationLogic):
def get_evaluation(self,decisions,rewards,threshold):
return []
class TestBaseMeasurementGen(unittest.TestCase):
"""
This class testes the base measurement generation
"""
def __init__(self, *args, **kwargs):
super(TestBaseMeasurementGen, self).__init__(*args, **kwargs)
self.N=np.random.randint(1,100)
self.s=BaseSupervisor(self.N)
def test_dict(self):
"""
Tests that the measurement dictionary is properly formatted
"""
a=BaseMeasurementGen()
measurements=a.get_measurements(self.s.population,0)
self.assertIsInstance(measurements,list)
self.assertEqual(len(measurements),self.N)
for m in measurements:
self.assertIsInstance(m,dict)
self.assertEqual(len(m),len(measurements[0])) # all of the same lenght
|
Go
|
UTF-8
| 990 | 3.375 | 3 |
[] |
no_license
|
package lex
import (
"bufio"
"fmt"
"github.com/vyevs/gojson/tok"
)
// attempts to read "true" or "false" and returns the corresponding token
// if not successful in reading the bool literal, returns an invalid token
// with the literal encountered instead
func readBoolToken(r *bufio.Reader) tok.Token {
literal, ok := readBoolLiteral(r)
tokenType := tok.Boolean
if !ok {
tokenType = tok.Invalid
}
return tok.Token{TokenType: tokenType, Literal: literal}
}
// attempts to read either "true" or "false" from the reader
// bool return value indicates whether this was successful
// upon success consumes only the bytes of "true"/"false"
func readBoolLiteral(r *bufio.Reader) (string, bool) {
str, err := readNByteStr(r, 4)
if err != nil {
return str, false
}
if str == "true" {
return "true", true
}
b, err := r.ReadByte()
if err != nil {
return str, false
}
str = fmt.Sprintf("%s%c", str, b)
if str == "false" {
return "false", true
}
return str, false
}
|
Markdown
|
UTF-8
| 2,554 | 3.0625 | 3 |
[] |
no_license
|
# IDEA2020.3详细破解教程
以下为自己破解教程记录
教程参考博主:(包含补丁下载)
https://www.exception.site/essay/idea-reset-eval
## 1.安装IDEA
选择试用期运行IDEA
新建一个普通项目
然后将ide-eval-resetter-2.1.6.zip拖到IDEA中

插件安装成功后,会提示如下:

## 2.关于使用
- 一般来说,在IDE窗口切出去或切回来时(窗口失去/得到焦点)会触发事件,检测是否长达`25`天都没有重置,会给出通知让你选择。(初次安装因为无法获取上次重置时间,会直接给予提示)
- 也可以手动唤出插件的主界面:
- 如果IDE没有打开项目,在`Welcome`界面点击菜单:`Get Help` -> `Eval Reset`
- 如果IDE打开了项目,点击菜单:`Help` -> `Eval Reset`


唤出的插件主界面中包含了一些显示信息,`2`个按钮,`1`个勾选项:
- 按钮:`Reload` 用来刷新界面上的显示信息。
- 按钮:`Reset` 点击会询问是否重置试用30天并**重启IDE**。选择`Yes`则执行重置操作并**重启IDE生效**,选择`No`则什么也不做。(此为手动重置方式)

勾选项:`Auto reset before per restart` 如果勾选了,则自勾选后**每次重启/退出IDE时会自动重置试用信息**,你无需做额外的事情。(此为自动重置方式)
## 3.查看试用期
进入 IDEA 界面后,点击 `Help` -> `Register` 查看:

可以看到,试用期还剩余30天:

## 4.说明
- 重置30天试用期需要**重启IDE生效**!
- 本插件默认不会显示其主界面,如果你需要,参考本文:`如何使用`小节。
- 市场付费插件的试用信息也会**一并重置**。
- 如果长达`25`天不曾有任何重置动作,IDE会有**通知询问**你是否进行重置。
- 如果勾选:`Auto reset before per restart` ,重置是静默无感知的。
- 简单来说:勾选了`Auto reset before per restart`则无需再管,一劳永逸。d
|
Swift
|
UTF-8
| 4,454 | 2.515625 | 3 |
[
"Apache-2.0"
] |
permissive
|
//
// UserDataSetting.swift
// PetClump
//
// Created by admin on 4/22/18.
// Copyright © 2018 PetClump. All rights reserved.
//
import UIKit
import Firebase
class SettingVC: GeneralVC{
// Title Labels
@IBOutlet weak var titleNameLabel: UILabel!
@IBOutlet weak var titleMyPetLabel: UILabel!
@IBOutlet weak var titleGenderLabel: UILabel!
@IBOutlet weak var titleBirthdayLabel: UILabel!
@IBOutlet weak var titleMatchRangeLabel: UILabel!
// Image view
@IBOutlet weak var pet0ImageView: UIImageView!
@IBOutlet weak var pet1ImageView: UIImageView!
@IBOutlet weak var pet2ImageView: UIImageView!
// Information display
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var genderLabel: UILabel!
@IBOutlet weak var matchSlider: UISlider!
@IBOutlet weak var birthdayLabel: UILabel!
var profile: OwnerProfile?
override func viewDidLoad() {
super.viewDidLoad()
guard let _ = Auth.auth().currentUser?.uid else {
self.dismiss(animated: true, completion: nil)
return
}
setupUI()
}
override func viewWillAppear(_ animated: Bool) {
guard let uid = Auth.auth().currentUser?.uid else {
self.dismiss(animated: true, completion: nil)
return
}
profile = OwnerProfile(id: uid) { profile in
// Gets user information
self.nameLabel.text = profile.name
self.genderLabel.text = profile.gender
self.birthdayLabel.text = profile.birthday.getBirthdayString()
// Gets match perference and updates the slider
self.matchSlider.minimumValue = 0
self.matchSlider.maximumValue = Float(OwnerSettingVC.matchValues.count - 1)
let indexAsValue = Float(OwnerSettingVC.matchValues.index(of: profile.distancePerference) ?? 0)
self.matchSlider.setValue(indexAsValue, animated: true)
self.titleMatchRangeLabel.text = OwnerSettingVC.getRangeDisplayText(actualValue: profile.distancePerference)
}
let _ = PetProfile(uid: uid, sequence: 0) { (pet) in
self.pet0ImageView.load(url: pet.getPhotoUrl(key: PetProfile.PetPhotoUrlKey.main))
}
let _ = PetProfile(uid: uid, sequence: 1) { (pet) in
self.pet1ImageView.load(url: pet.getPhotoUrl(key: PetProfile.PetPhotoUrlKey.main))
}
let _ = PetProfile(uid: uid, sequence: 2) { (pet) in
self.pet2ImageView.load(url: pet.getPhotoUrl(key: PetProfile.PetPhotoUrlKey.main))
}
}
func setupUI(){
let range = 25
hideKeyboardWhenTappedAround()
titleNameLabel.text = NSLocalizedString("Name", comment: "This is the title for specifying the name of the user")
titleMyPetLabel.text = NSLocalizedString("My Pet", comment: "This is the tile for specifying the section of the pet for the user")
titleGenderLabel.text = NSLocalizedString("Gender", comment: "This is the tile for specifying the gender of the user. It's not the sex of the user.")
titleMatchRangeLabel.text = NSLocalizedString("Match Range: \(range)", comment: "This is the label to show the match range from the user to other users. (range) is a computed value and should not be changed")
for view in self.view.subviews as [UIView] {
if let imageView = view as? UIImageView {
imageView.setRounded()
let tap = UITapGestureRecognizer(target: self, action: #selector(enterPetView(sender:)))
imageView.isUserInteractionEnabled = true
imageView.addGestureRecognizer(tap)
}
}
}
@objc private func enterPetView(sender: UITapGestureRecognizer){
// Present Pet data view
guard let uid = Auth.auth().currentUser?.uid else { return }
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let pdv = storyBoard.instantiateViewController(withIdentifier: "PetSettingVC") as! PetSettingVC
pdv.petProfile = PetProfile()
pdv.petProfile!.ownerId = uid
pdv.petProfile!.sequence = sender.view!.tag
self.present(pdv, animated: true, completion: nil)
}
// Dismisses the view
@IBAction func tapCancel(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
}
|
Java
|
UTF-8
| 6,926 | 2.03125 | 2 |
[] |
no_license
|
package com.beck.beck_app.controller;
import com.beck.beck_app.facade.NoticeFacade;
import com.beck.beck_app.model.Notice;
import com.beck.beck_app.util.JsfUtil;
import com.beck.beck_app.util.JsfUtil.PersistAction;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
@Named("noticeController")
@SessionScoped
public class NoticeController implements Serializable {
@EJB
private com.beck.beck_app.facade.NoticeFacade ejbFacade;
private List<Notice> items = null;
private Notice selected;
private Notice selectedSave;
private List<Notice> allNotice;
private List<String> filteredNotice;
private List<Notice> filteredItems;
public NoticeController() {
}
public Notice getSelected() {
return selected;
}
public void setSelected(Notice selected) {
this.selected = selected;
}
protected void setEmbeddableKeys() {
}
protected void initializeEmbeddableKey() {
}
private NoticeFacade getFacade() {
return ejbFacade;
}
@PostConstruct
public void init() {
selected = new Notice();
selectedSave = new Notice();
}
public void getByTitle()
{
selectedSave = getFacade().findByTitle(selected.getTitle());
}
public Notice prepareCreate() {
selected = new Notice();
initializeEmbeddableKey();
return selected;
}
public void setSelectedFromSelectedSave() {
selected=selectedSave;
}
public void create() {
persist(PersistAction.CREATE, ResourceBundle.getBundle("/Bundle").getString("NoticeCreated"));
if (!JsfUtil.isValidationFailed()) {
items = null; // Invalidate list of items to trigger re-query.
}
}
public void update() {
persist(PersistAction.UPDATE, ResourceBundle.getBundle("/Bundle").getString("NoticeUpdated"));
}
public void destroy() {
persist(PersistAction.DELETE, ResourceBundle.getBundle("/Bundle").getString("NoticeDeleted"));
if (!JsfUtil.isValidationFailed()) {
selected = null; // Remove selection
items = null; // Invalidate list of items to trigger re-query.
}
}
public List<Notice> getItems() {
if (items == null) {
items = getFacade().findAll();
}
return items;
}
public void setItems( List<Notice> items) {
this.items=items;
}
private void persist(PersistAction persistAction, String successMessage) {
if (selected != null) {
setEmbeddableKeys();
try {
if (persistAction != PersistAction.DELETE) {
getFacade().edit(selected);
} else {
getFacade().remove(selected);
}
JsfUtil.addSuccessMessage(successMessage);
} catch (EJBException ex) {
String msg = "";
Throwable cause = ex.getCause();
if (cause != null) {
msg = cause.getLocalizedMessage();
}
if (msg.length() > 0) {
JsfUtil.addErrorMessage(msg);
} else {
JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
} catch (Exception ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
}
}
public Notice getNotice(java.lang.Integer id) {
return getFacade().find(id);
}
public List<Notice> getItemsAvailableSelectMany() {
return getFacade().findAll();
}
public List<Notice> getItemsAvailableSelectOne() {
return getFacade().findAll();
}
public List<String> completeText(String query) {
allNotice = getFacade().findAll();
filteredNotice = new ArrayList<String>();
filteredItems = new ArrayList<Notice>();
for (int i = 0; i < allNotice.size(); i++) {
Notice notice = allNotice.get(i);
if(notice.getTitle().toLowerCase().contains(query.toLowerCase())) {
filteredNotice.add(notice.getTitle());
filteredItems.add(notice);
}
}
items=filteredItems;
return filteredNotice;
}
public String processListNotice(){
return "/guest_views/notice/ListNotice";
}
/**
* @return the selToSave
*/
public Notice getSelectedSave() {
return selectedSave;
}
/**
* @param selectedSave the selToSave to set
*/
public void setSelectedSave(Notice selectedSave) {
this.selectedSave = selectedSave;
}
@FacesConverter(forClass = Notice.class)
public static class NoticeControllerConverter implements Converter {
@Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
NoticeController controller = (NoticeController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "noticeController");
return controller.getNotice(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
@Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Notice) {
Notice o = (Notice) object;
return getStringKey(o.getId());
} else {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, "object {0} is of type {1}; expected type: {2}", new Object[]{object, object.getClass().getName(), Notice.class.getName()});
return null;
}
}
}
}
|
C#
|
UTF-8
| 1,255 | 3.4375 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace Task4
{
class Program
{
static void Main(string[] args)
{
string fileName = "test.txt"; // имя файла которого мы будем создавать
string PathString = @"C:\hello"; // путь который указывает на папку в которой будет храниться файл
PathString = Path.Combine(PathString, fileName); //объединяет две строки в путь
FileStream fs = File.Create(PathString); // создает новый файл
fs.Close(); // закроет файл для того чтобы прекратить работу с файлом
string PathString2 = @"C:\SomeDir"; //указываем на новый путь
string destFile = System.IO.Path.Combine(PathString2, fileName); // объединяет две строки в путь
File.Copy(PathString, destFile, true); // скопирует файл
File.Delete(PathString); // и удаляет первый файл
}
}
}
|
C++
|
UTF-8
| 5,126 | 2.6875 | 3 |
[] |
no_license
|
#include "SpecialCollectable.h"
#include "Constants.h"
#include "Stage.h"
using namespace cocos2d;
static int totalNumberOfCollectables = 20;
static int currentCollectableIndex = 0;
SpecialCollectable::SpecialCollectable(Stage const& stage){
_origin = Director::getInstance()->getVisibleOrigin();
_visibleSize = Director::getInstance()->getVisibleSize();
initPatterns(stage.getDifficulty());
random_shuffle(_specialCollectableTypes.begin(), _specialCollectableTypes.end());
}
void SpecialCollectable::populatePatterns(int difficultyLevel, int life, int floatingBomb, int invisibility, int magnetEffect, int gaps) {
// Floating Bomb: 8
for (int i = 0; i < floatingBomb; ++i) {
_specialCollectableTypes.push_back(CATEGORY_BITMASK_COLLECT_BOMB);
}
// Life: 16
for (int i = 0; i < life; ++i) {
_specialCollectableTypes.push_back(CATEGORY_BITMASK_COLLECT_LIFE);
}
// Invisibility: 32
for (int i = 0; i < invisibility; ++i) {
_specialCollectableTypes.push_back(CATEGORY_BITMASK_INVISIBILITY);
}
// Magnet Effect: 128
for (int i = 0; i < magnetEffect; ++i) {
_specialCollectableTypes.push_back(CATEGORY_BITMASK_MAGNET);
}
// gaps: give some gap (blank floating item)
for (int i = 0; i < gaps; ++i) {
_specialCollectableTypes.push_back(CATEGORY_BITMASK_NOTHING);
}
}
void SpecialCollectable::initPatterns(int difficultyLevel) {
switch (difficultyLevel) {
case 1: // no special collectables
break;
case 2: // no special collectables
break;
case 3: // introducint "life"
populatePatterns(difficultyLevel, totalNumberOfCollectables * 0.5, 0, 0, 0, totalNumberOfCollectables * 0.5);
break;
case 4: // life(65) + floating bomb(35%)
populatePatterns(difficultyLevel, totalNumberOfCollectables * 0.4, totalNumberOfCollectables * 0.3, 0, 0, totalNumberOfCollectables * 0.3);
break;
case 5: // life(45%) + floating bomb(25%) + invisibility(0) + magnet effect(30%)
populatePatterns(difficultyLevel, totalNumberOfCollectables * 0.4, totalNumberOfCollectables * 0.2, 0, totalNumberOfCollectables * 0.3, totalNumberOfCollectables * 0.1);
break;
case 6: // life(40%) + floating bomb(30%) + invisibility(20%) + magnet effect(0)
populatePatterns(difficultyLevel, totalNumberOfCollectables * 0.4, totalNumberOfCollectables * 0.3, totalNumberOfCollectables * 0.2, 0, totalNumberOfCollectables * 0.1);
break;
case 7: // Infinite Stage (life + floating bomb + invisibility + magnet effect (20% each))
populatePatterns(difficultyLevel, totalNumberOfCollectables * 0.25, totalNumberOfCollectables * 0.15, totalNumberOfCollectables * 0.2, totalNumberOfCollectables * 0.2, totalNumberOfCollectables * 0.2);
break;
default:
break;
}
}
void SpecialCollectable::spawn(cocos2d::Layer* layer, std::vector<Sprite*>& specialCollectables) {
if (not layer) { return; }
if (_specialCollectableTypes.empty()) { return; }
int type = _specialCollectableTypes.at(currentCollectableIndex++ % _specialCollectableTypes.size());
if (type == 0) {
// give some gap (blank floating item)
return;
}
Sprite* bonusCollectable = Sprite::create(String::createWithFormat("specialcollectable%i.png", type)->getCString());
if (not bonusCollectable) { return; }
bonusCollectable->setAnchorPoint(Vec2(0.5f, 1.0f));
bonusCollectable->setTag(type); // used as type:: 8:flying_bomb 16:life
int positionX = RandomHelper::random_int((int)(_visibleSize.width * 0.65), (int)(_visibleSize.width * 0.80));
int positionY = _visibleSize.height + bonusCollectable->getContentSize().height;
bonusCollectable->setPosition(Vec2(positionX, positionY));
auto body = PhysicsBody::createCircle(bonusCollectable->getContentSize().width * 0.5, PhysicsMaterial(0.1, 1.0, 0.0));
body->setCategoryBitmask(type); // set collectable type as category_bitmask (8:flying_bomb 16:life)
// body->setCollisionBitmask(1);
body->setContactTestBitmask(CATEGORY_BITMASK_CHICKEN);
body->setDynamic(false);
if (type == CATEGORY_BITMASK_COLLECT_LIFE) {
// push up the p_body for floating balloon (life) with tail
body->setPositionOffset(Vec2(0, bonusCollectable->getContentSize().height * 0.25));
}
bonusCollectable->setPhysicsBody(body);
layer->addChild(bonusCollectable, BackgroundLayer::layerChicken);
{ // Swinging animation
auto easeSwing = Sequence::create(EaseInOut::create(RotateTo::create(0.8f, -10), 2),
EaseInOut::create(RotateTo::create(0.8f, 10), 2),
nullptr);
Action* _floatAnimation = RepeatForever::create( (ActionInterval*) easeSwing );
bonusCollectable->runAction(_floatAnimation);
}
specialCollectables.push_back(bonusCollectable);
}
|
Java
|
UTF-8
| 1,650 | 2.21875 | 2 |
[] |
no_license
|
package com.experis.formacion.alexa.poc.service.dto;
import java.io.Serializable;
import java.util.List;
import java.util.Objects;
public class FormacionesSugeridasDTO extends FormacionesDTO implements Serializable {
private List<String> habilidadesRelacionadas;
private List<String> interesesRelacionados;
public List<String> getHabilidadesRelacionadas() {
return habilidadesRelacionadas;
}
public void setHabilidadesRelacionadas(List<String> habilidadesRelacionadas) {
this.habilidadesRelacionadas = habilidadesRelacionadas;
}
public List<String> getInteresesRelacionados() {
return interesesRelacionados;
}
public void setInteresesRelacionados(List<String> interesesRelacionados) {
this.interesesRelacionados = interesesRelacionados;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
FormacionesSugeridasDTO that = (FormacionesSugeridasDTO) o;
return Objects.equals(habilidadesRelacionadas, that.habilidadesRelacionadas) &&
Objects.equals(interesesRelacionados, that.interesesRelacionados);
}
@Override
public int hashCode() {
return Objects
.hash(habilidadesRelacionadas,interesesRelacionados);
}
@Override
public String toString() {
return "FormacionesSugeridasDTO{" +
", habilidadesRelacionadas=" + habilidadesRelacionadas +
", interesesRelacionados=" + interesesRelacionados +
'}';
}
}
|
Markdown
|
UTF-8
| 466 | 3.375 | 3 |
[] |
no_license
|
# Pattern 20
1. You are given a number n.
2. You've to write code to print the pattern given in output format below.
## Input Format
A number n
## Output Format

## Constraints
1 <= n <= 10
Also, n is odd.
## Sample Input
5
## Sample Output

|
C#
|
UTF-8
| 492 | 2.515625 | 3 |
[] |
no_license
|
using System;
using System.Windows.Forms;
namespace Assignment_4
{
public partial class OrderView : UserControl
{
public OrderView()
{
InitializeComponent();
}
private void OrderView_Load(object sender, EventArgs e)
{
labelTimer.Text = DateTime.Now.ToString();
Random rd = new Random();
int rand_num = rd.Next(100, 999);
labelOrderNumber.Text = "#" + rand_num;
}
}
}
|
Java
|
UTF-8
| 638 | 2.109375 | 2 |
[] |
no_license
|
package com.boot.springboot.controller;
import io.micrometer.core.instrument.MeterRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @Author: Michael J H Duan
* @Date: 2022-06-02
* @Version: V1.0
* @Description: Actuator监控
*/
@RestController
public class ActuatorController {
@Autowired
private MeterRegistry meterRegistry;
@GetMapping("/visit")
public String visitCount(){
meterRegistry.counter("visit.count");
return "visit Actuator Restful";
}
}
|
PHP
|
UTF-8
| 2,308 | 2.875 | 3 |
[] |
no_license
|
<?php
namespace App\Services;
use App\Http\Resources\ApiError;
use App\Repositories\PokemonRepository;
use App\Http\Resources\PokemonDetail;
use App\Http\Resources\Pokemon as PokemonCollection;
use App\Repositories\Interfaces\PokemonRepositoryInterface;
class PokemonService implements Interfaces\PokemonServiceInterface
{
private $pokemonRepository;
/** Use object compostion to inject the PokemonRepository class */
public function __construct(PokemonRepositoryInterface $pokemonRepository)
{
$this->pokemonRepository = $pokemonRepository;
}
/** return a collection of pokemon, give all the details as well, why not? */
public function index($name, $description)
{
return PokemonDetail::collection($this->pokemonRepository->index($name, $description));
}
/** Return a collection of pokemon with little detail. */
public function allIndex()
{
return PokemonCollection::collection($this->pokemonRepository->allIndex());
}
/** Show a single pokemon, if not there, return an api error */
public function show($id)
{
$res = $this->pokemonRepository->show($id);
if ($res)
return new PokemonDetail($res);
return ApiError::error(404, "Failed to find the pokemon with id of " . $id . ".");
}
/** Search by type, if none, return an api error */
public function type($type)
{
$res = $this->pokemonRepository->type($type);
if ($res) {
return PokemonDetail::collection($res);
}
return response()->json(["data" => [], "meta" => ["last_page" => 1]]);
}
/** Search by ability, if none, return an api error */
public function ability($ability)
{
$res = $this->pokemonRepository->ability($ability);
if ($res) {
return PokemonDetail::collection($res);
}
return response()->json(["data" => [], "meta" => ["last_page" => 1]]);
}
/** Search by egg_group, if none, return an api error */
public function egg_group($egg_group)
{
$res = $this->pokemonRepository->egg_group($egg_group);
if ($res) {
return PokemonDetail::collection($res);
}
return response()->json(["data" => [], "meta" => ["last_page" => 1]]);
}
}
|
Java
|
UTF-8
| 3,048 | 2.625 | 3 |
[] |
no_license
|
package entu.timer.timers;
import static entu.timer.timers.Timer.currentRunId;
import static java.time.LocalDateTime.ofInstant;
import static java.time.ZoneId.systemDefault;
import entu.timer.output.Output;
import entu.timer.persistence.Json;
import java.io.IOException;
import java.time.Instant;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
public class Timetable {
private transient Output output;
private final int version;
private final Map<Long, List<Timer>> timers;
public Timetable(Output output) {
this.output = output;
final Timetable loaded = Json.deserialize();
version = loaded.version;
timers = loaded.timers;
}
public <T> Timetable(int version, List<Timer> timers) {
this.version = version;
this.timers = new LinkedHashMap<>();
timers.forEach(this::addRecord);
}
public void persist() {
try {
Json.serialize(this);
} catch (IOException e) {
output.print("Unable to save timetable history: " + e.getMessage());
}
}
void addRecord(final Timer timer) {
timers.computeIfAbsent(currentRunId(), ignored -> new ArrayList<>());
timers.get(currentRunId()).add(timer);
}
public void print() {
timers.forEach((runId, timers) -> {
output.print("Run: " + runId);
timers.forEach(timer -> output.print(timer.toString()));
});
}
public List<Timer> last(final int amount) {
final List<Timer> currentRun = getRun();
final int recordsAmount = currentRun.size();
int fromIndex = recordsAmount - amount - 1;
if (fromIndex <= 0) {
return currentRun;
}
return currentRun.subList(fromIndex, recordsAmount);
}
public int lastDuration() {
final List<Timer> run = getRun();
if (run.isEmpty()) {
return Timer.NOT_A_DURATION;
}
return run.get(run.size() - 1).getDurationSeconds();
}
public int lastIncrement() {
final List<Timer> run = getRun();
if (run.size() < 2) {
return lastDuration();
}
return run.get(run.size() - 1).getDurationSeconds() - run.get(run.size() - 2)
.getDurationSeconds();
}
public Stream<Timer> get() {
return timers.entrySet().stream().flatMap(entry -> entry.getValue().stream());
}
public List<Timer> getRun() {
final long runId = currentRunId();
return timers.computeIfAbsent(runId, ignored -> new ArrayList<>());
}
private static boolean today(final Instant instant) {
return ofInstant(instant, systemDefault())
.isAfter(LocalDate.now().atStartOfDay());
}
public Stream<Timer> getToday() {
return get().filter(timer -> today(timer.getStart()));
}
public int getVersion() {
return version;
}
}
|
Python
|
UTF-8
| 1,602 | 2.71875 | 3 |
[] |
no_license
|
import tensorflow as tf
import select
import sys
def isIterableNotString(o):
if isinstance(o, str):
return False
try:
for e in o:
return True
except TypeError:
return False
def cartesian_product(a, b):
len_a = tf.shape(a)
len_b = tf.shape(b)
new_a = tf.reshape(tf.tile(a, [1, len_b[0]]), [-1, len_a[1]])
new_b = tf.tile(b, [len_a[0],1])
return tf.concat((new_a, new_b), axis=1)
import warnings
import functools
def deprecated(func):
"""This is a decorator which can be used to mark functions
as deprecated. It will result in a warning being emmitted
when the function is used."""
@functools.wraps(func)
def new_func(*args, **kwargs):
warnings.simplefilter('always', DeprecationWarning) #turn off filter
warnings.warn("Call to deprecated function {}.".format(func.__name__), category=DeprecationWarning, stacklevel=2)
warnings.simplefilter('default', DeprecationWarning) #reset filter
return func(*args, **kwargs)
return new_func
def cartesian(tensors):
try:
if (len(tensors) < 2): raise Exception()
except:
raise Exception("The length of domains must be >= 2")
tensor = tensors[0]
for i in range(1, len(tensors)):
tensor = cartesian_product(tensor, tensors[i])
return tensor
def heardEnter():
''' Listen for the user pressing ENTER '''
i,o,e = select.select([sys.stdin],[],[],0.0001)
for s in i:
if s == sys.stdin:
input = sys.stdin.readline()
return True
return False
|
Python
|
UTF-8
| 103 | 2.546875 | 3 |
[] |
no_license
|
import sys
sys.stdout=open("code.in","w")
print(1)
print(1,200000)
for i in range(200000):
print(1,1)
|
Markdown
|
UTF-8
| 889 | 2.984375 | 3 |
[] |
no_license
|
## 63. 오류를 놓치지 않도록 조심하라.
nodejs를 사용한다면 다음과 같이 아래 체크를 하자. ( 콜백헬 @.@;; )
```js
function onError(error){
console.error( 'Error : ' + error );
}
downloadAsync('a.txt', function(a){
downloadAsync('b.txt', function(b){
downloadAsync('c.txt', function(c){
console.log('contents : ' + a + b + c );
}, onError);
}, onError);
}, onError);
```
혹은,
```js
downloadAllAsync(['a.txt','b.txt','c.txt'],function(error, abc){
if( error ){
console.log('Error : ' + error);
return;
}
console.log( 'Contents : ' + abc[0] + abc[1] + abc[2] );
});
```
> __기억할 점___
> * 오류 처리 코드를 복사하여 붙여 넣지 말고 공유된 오류 처리 함수를 작성하라.
> * 오류를 놓치지 않기 위해 모든 오류 조건을 명시적으로 처리하는지 확인하라.
|
Java
|
UTF-8
| 655 | 2.234375 | 2 |
[] |
no_license
|
package com.llk.therapist.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
@Configuration
public class ConfigUtility {
@Autowired
private Environment env;
public String getProperty(String pPropertyKey) {
return env.getProperty(pPropertyKey);
}
public boolean isDevActiveProfle() {
String[] profiles = env.getActiveProfiles();
for (String profile : profiles) {
if (profile != null && profile.equalsIgnoreCase(Constants.PROFILE_DEV)) {
return true;
}
}
return false;
}
}
|
C++
|
UTF-8
| 1,934 | 2.578125 | 3 |
[
"BSD-2-Clause-Views"
] |
permissive
|
#include <MCSInputWidget.h>
#include <QLineEdit>
#include <QComboBox>
#include <QVBoxLayout>
#include <QLabel>
#include <QValidator>
#include <QJsonObject>
MCSInputWidget::MCSInputWidget(QWidget *parent)
: UQ_MethodInputWidget(parent)
{
auto layout = new QGridLayout();
// create layout label and entry for # samples
numSamples = new QLineEdit();
numSamples->setValidator(new QIntValidator);
numSamples->setToolTip("Specify the number of samples");
layout->addWidget(new QLabel("# Samples"), 0, 0);
layout->addWidget(numSamples, 0, 1);
// create label and entry for seed to layout
// srand(time(NULL));
// int randomNumber = rand() % 1000 + 1;
// randomSeed = new QLineEdit();
// randomSeed->setText(QString::number(randomNumber));
// randomSeed->setValidator(new QIntValidator);
// randomSeed->setToolTip("Set the seed");
verbose = new QComboBox();
verbose->addItem(tr("True"));
verbose->addItem(tr("False"));
layout->addWidget(new QLabel("Verbose"), 1, 0);
layout->addWidget(verbose, 1, 1);
layout->setRowStretch(2, 1);
layout->setColumnStretch(2, 1);
this->setLayout(layout);
}
MCSInputWidget::~MCSInputWidget()
{
}
bool
MCSInputWidget::outputToJSON(QJsonObject &jsonObj){
bool result = true;
jsonObj["samples"]=numSamples->text().toInt();
// jsonObj["seed"]=randomSeed->text().toDouble();
return result;
}
bool
MCSInputWidget::inputFromJSON(QJsonObject &jsonObject){
bool result = false;
if (jsonObject.contains("samples") && jsonObject.contains("seed")) {
int samples=jsonObject["samples"].toInt();
// double seed=jsonObject["seed"].toDouble();
numSamples->setText(QString::number(samples));
// randomSeed->setText(QString::number(seed));
result = true;
}
return result;
}
void
MCSInputWidget::clear(void)
{
}
int
MCSInputWidget::getNumberTasks()
{
return numSamples->text().toInt();
}
|
Markdown
|
UTF-8
| 2,639 | 3.140625 | 3 |
[] |
no_license
|
PACKAGE DOCUMENTATION
package acfmgr
import "./acfmgr"
Package acfmgr is a package to manage entries in an AWS credentials file
Sample AWS creds file format:
[default]
output = json
region = us-east-1
aws_access_key_id = QOWIASOVNALKNVCIE
aws_secret_access_key = zgylMqe64havoaoinweofnviUHqQKYHMGzFMA8CI
aws_session_token = FQoDYXdzEGYaDNYfEnCsHW/8rG3zpiKwAfS8T...
[dev-default]
output = json
region = us-west-1
aws_access_key_id = QOWIAADFEGKNVCIE
aws_secret_access_key = zgylMqaoivnawoeenweofnviUHqQKYHMGzFMA8CI
aws_session_token = FQoDYXdzEGYaDNYfEnCsanv;oaiwe\iKwAfS8T...
Adding and removing entries manually is a pain so this package was
created to assist in programattically adding them once you have sessions
built from the Golang AWS SDK.
Calling AssertEntries will delete all entries of that name and only
rewrite the given entry with the given contents.
Calling DeleteEntries will delete all entries of that name.
Sample
c, err := acfmgr.NewCredFileSession("~/.aws/credentials")
check(err)
c.NewEntry("[dev-account-1]", []string{"output = json", "region = us-east-1", "...", ""})
c.NewEntry("[dev-account-2]", []string{"output = json", "region = us-west-1", "...", ""})
err = c.AssertEntries()
Yields:
[dev-account-1]
output = json
region = us-east-1
...
[dev-account-2]
output = json
region = us-west-1
...
While:
c, err := acfmgr.NewCredFileSession("~/.aws/credentials")
check(err)
c.NewEntry("[dev-account-2]", []string{"output = json", "region = us-west-1", "...", ""})
err = c.DeleteEntries()
Yields:
[dev-account-2]
output = json
region = us-west-1
...
TYPES
type CredFile struct {
// contains filtered or unexported fields
}
CredFile should be built with the exported NewCredFileSession function.
func NewCredFileSession(filename string) (*CredFile, error)
NewCredFileSession creates a new interactive credentials file session.
Needs target filename and returns CredFile obj and err.
func (c *CredFile) AssertEntries() (err error)
AssertEntries loops through all of the credEntry objs attached to
CredFile obj and makes sure there is an occurrence with the
credEntry.name and contents. Existing entries of the same name with
different contents will be clobbered.
func (c *CredFile) DeleteEntries() (err error)
DeleteEntries loops through all of the credEntry objs attached to
CredFile obj and makes sure entries with the same credEntry.name are
removed. Will remove ALL entries with the same name.
func (c *CredFile) NewEntry(entryName string, entryContents []string)
NewEntry adds a new credentials entry to the queue to be written or
deleted with the AssertEntries or DeleteEntries method.
|
C++
|
UTF-8
| 963 | 3.25 | 3 |
[] |
no_license
|
#include "Vector.h"
namespace triangles
{
float crossProduct(const Vector<2>& lhs, const Vector<2>& rhs)
{
return lhs[0] * rhs[1] - lhs[1] * rhs[0];
}
float crossProductN(const Vector<2>& lhs, const Vector<2>& rhs)
{
return crossProduct(lhs, rhs) / lhs.getLength() / rhs.getLength();
}
bool isCollinear(const Vector<2>& lhs, const Vector<2>& rhs, float eps)
{
return std::abs(crossProductN(lhs, rhs)) <= eps;
}
Vector<3> operator*(const Vector<3>& lhs, const Vector<3>& rhs)
{
return Vector<3>{ std::array<float, 3>{ lhs[1] * rhs[2] - rhs[1] * lhs[2],
rhs[0] * lhs[2] - lhs[0] * rhs[2],
lhs[0] * rhs[1] - rhs[0] * lhs[1] } };
}
Vector<3> operator*(const Vector<2>& lhs, const Vector<2>& rhs)
{
// Just orthogonal to lhs and rhs
return Vector<3>{ std::array<float, 3>{ 0.0f, 0.0f, lhs[0] * rhs[1] - rhs[0] * lhs[1] } };
}
}
|
Python
|
UTF-8
| 190 | 2.734375 | 3 |
[] |
no_license
|
from enum import IntEnum, Enum
class Pieces(IntEnum):
EMPTY = 0
WHITE = 1
WHITE_PROMOTED = 2
BLACK = 3
BLACK_PROMOTED = 4
class Color(Enum):
WHITE = 1
BLACK = 2
|
Shell
|
UTF-8
| 1,047 | 3.640625 | 4 |
[] |
no_license
|
#!/bin/bash
#bclient <machine> <port> <file> <N-threads> <N-cycles>
#Indicates the name or IP address where the server is running
MACHINE=$1
#The port number of the corresponding server
PORT=$2
#The path to the file that is going to be transferred
#(it could be a text file or an image of any size)
FILE=$3
#Number of threads that are to be created to send requests to the corresponding server.
THREADS=$4
#Number of cycles that each thread is going to repeat the request.
CYCLES=$5
#Report CSV format that summarize:
#Test;Requests;Initial request time;Kind of file;Size of file;Response time;Amount of requests;Average response time
#compiles the library of mypthreads
gcc -o mypthread.o -c myPthreads/mypthread.c
#compiles the c file that is going measure the times and link the library mypthreads
gcc bclient.c mypthread.o -o bclient.out
#gcc bclient.c -pthread -o bclient.out
#TODO: Remember to use the file pthreads if you want to use the other library
#execute the script
sudo ./bclient.out $MACHINE $PORT $FILE $THREADS $CYCLES
|
Python
|
UTF-8
| 738 | 2.59375 | 3 |
[] |
no_license
|
import selenium
from selenium.webdriver.support.select import Select
print("001_Exercise")
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
driver = webdriver.Chrome(executable_path="C:\Selenium Browser driver\chromedriver.exe")
driver.get("https://letskodeit.teachable.com/p/practice")
driver.maximize_window()
current=driver.current_window_handle
driver.find_element_by_id("opentab").click()
windows =driver.window_handles
for handle in windows:
if handle not in current:
driver.switch_to.window(handle)
driver.get_screensh
#Dropdown
# dropdown = Select(driver.find_element_by_id("exampleFormControlSelect1"))
# dropdown.select_by_index(1)
# driver.close()
|
Java
|
UTF-8
| 1,274 | 2.078125 | 2 |
[] |
no_license
|
package com.example.mdevt;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Header;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
public interface UploadApi {
@Multipart
@POST("sub_agent_signup/")
Call<RequestBody> uploadImage(@Header("Authorization") String token,
@Part MultipartBody.Part idPart,
@Part MultipartBody.Part addressPart,
@Part("mobile_number") RequestBody mobile_number,
@Part ("name") RequestBody name,
@Part ("surname") RequestBody surname,
@Part ("id_passport_expiry") RequestBody id_passport_expiry,
@Part ("id_passport_number") RequestBody id_passport_number,
@Part ("address1") RequestBody address1,
@Part ("address2") RequestBody address2,
@Part ("address3") RequestBody address3,
@Part ("postal_code") RequestBody postal_code
);
}
|
Java
|
UTF-8
| 888 | 3.90625 | 4 |
[] |
no_license
|
//Robert Roche
package module3_roche_assignment1;
import java.util.Stack;
/**
*
* @author Bobby
*/
public class Module3_Roche_Assignment1 {
public static void main(String[] args) {
System.out.println("The first 50 numbers in the fibbonaci sequence are: \n");
Stack <Long> fib = new Stack <Long>();//creates stack
long num;
for(int i =0; i<50; i++){//sets limit to 50 elements
num = getFibonacci(i);//calls method to get the number
fib.push(num);//adds the number to the stack
}
long num1;
for(int i = 50; i > 0; i--){
num1 = fib.pop();
System.out.print(num1 + " ");
}
}
public static long getFibonacci(int n) {
if(n == 0)
return 0;
else if(n == 1)
return 1;
else
return getFibonacci(n - 1) + getFibonacci(n - 2);
}
}
|
Java
|
UTF-8
| 1,165 | 3.25 | 3 |
[] |
no_license
|
package JDBC_test.Exer;
import JDBC_test.Utils.CommonUtil;
import JDBC_test.Utils.JDBC_Utils;
import org.junit.Test;
import java.util.Scanner;
import java.sql.Date;
/**
* 题目1:从控制台向数据库的表customers中插入一条数据,表结构如下
*/
public class Topic01 {
public static void main(String[] args) {
// 1. 获取控制台输入的信息
Scanner scanner = new Scanner(System.in);
System.out.print("请输入名字:");
String name = scanner.next();
System.out.print("请输入邮箱:");
String email = scanner.next();
System.out.print("请输入生日日期(如:1997-01-12):");
String birth = scanner.next();
// 将日期转为java.sql.Date格式
long dateMillis = CommonUtil.getDateMillis(birth);
Date date = new Date(dateMillis);
// 2. 将信息插入到customers数据表中
String update_sql = "insert into customers(name,email,birth) values(?,?,?)";
boolean status = JDBC_Utils.updateSqlTable(update_sql, name, email, date);
System.out.println(status?"新增成功":"新增失败");
}
}
|
Python
|
UTF-8
| 1,310 | 3.921875 | 4 |
[] |
no_license
|
class Player(object):
def __init__(self, name, turn, score, numOfPlayer):
if isinstance(name, str) and isinstance(turn, bool) and isinstance(score and numOfPlayer, int or float):
self.name = name
self.turn = turn
self.score = score
self.numOfPlayer = numOfPlayer
else:
raise TypeError("One or more arguments don't match the corresponding type")
def addScore(self, score):
if isinstance(score, int or float):
self.score += score
else:
raise TypeError("The score must be int of float")
def setScore(self, score):
if isinstance(score, int or float):
self.score = score
else:
raise TypeError("The score must be int of float")
def changeTurn(self, turn):
if isinstance(turn, bool):
self.turn = turn
else:
raise TypeError("Turn must be a boolean")
def changeName(self, name):
if isinstance(name, str):
self.name = name
else:
raise TypeError("Name must be a string")
def _print(self):
print("Name: " + self.name + " Turn: " + str(self.turn) + " Score: " + str(self.score))
def changeNumOfPlayer(self, num):
self.numOfPlayer = num
|
SQL
|
UTF-8
| 4,583 | 3.125 | 3 |
[] |
no_license
|
-- phpMyAdmin SQL Dump
-- version 4.5.5.1
-- http://www.phpmyadmin.net
--
-- Client : 127.0.0.1
-- Généré le : Jeu 25 Août 2016 à 22:46
-- Version du serveur : 5.7.11
-- Version de PHP : 5.6.19
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de données : `stickmanbdd`
--
-- --------------------------------------------------------
--
-- Structure de la table `champion`
--
CREATE TABLE `champion` (
`id_champion` int(11) NOT NULL,
`id_compte` int(11) NOT NULL,
`Name` varchar(45) NOT NULL,
`Strengh` int(11) NOT NULL,
`Life` int(11) NOT NULL,
`Point` int(11) NOT NULL,
`ActionPoint` int(11) NOT NULL,
`MovePoint` int(11) NOT NULL,
`Victories` int(11) NOT NULL,
`Defeats` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Contenu de la table `champion`
--
INSERT INTO `champion` (`id_champion`, `id_compte`, `Name`, `Strengh`, `Life`, `Point`, `ActionPoint`, `MovePoint`, `Victories`, `Defeats`) VALUES
(1, 3, 'Patrick', 100, 100, 100, 0, 0, 100, 100),
(3, 2, 'Robert', 100, 100, 100, 0, 0, 100, 100);
-- --------------------------------------------------------
--
-- Structure de la table `compte`
--
CREATE TABLE `compte` (
`idCompte` int(11) NOT NULL,
`Username` varchar(45) NOT NULL,
`Password` varchar(45) NOT NULL,
`Pseudo` varchar(45) NOT NULL,
`Email` varchar(45) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Contenu de la table `compte`
--
INSERT INTO `compte` (`idCompte`, `Username`, `Password`, `Pseudo`, `Email`) VALUES
(1, 'test', 'test', 'test1', 'test@ggrgrfgr'),
(3, 'test3', '3ebfa301dc59196f18593c45e519287a23297589', 'test3', 'test3@gmail.com'),
(5, 'test2', 'zrertzert', 'test2', 'test2@ggrgrfgr'),
(6, 'adminc', '6f1bdb83ff15dbd1870998fa59801e0a', 'Funkeal', 'adminc@adminc'),
(16, 'ben', '73675debcd8a436be48ec22211dcf44fe0df0a64', 'ben', 'ben@gmail.com');
-- --------------------------------------------------------
--
-- Structure de la table `inventory`
--
CREATE TABLE `inventory` (
`idInventory` int(11) NOT NULL,
`idCompte` int(11) NOT NULL,
`nbStorage` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Structure de la table `items`
--
CREATE TABLE `items` (
`idItem` int(11) NOT NULL,
`Name` varchar(45) NOT NULL,
`Value` int(11) NOT NULL,
`Effect` int(11) NOT NULL,
`Description` varchar(2500) NOT NULL,
`type` varchar(50) CHARACTER SET utf8 COLLATE utf8_bin DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Contenu de la table `items`
--
INSERT INTO `items` (`idItem`, `Name`, `Value`, `Effect`, `Description`, `type`) VALUES
(1, 'Health Potion', 100, 1, '+100 Hp', 'weed'),
(2, 'Action Potion', 200, 2, '+5 Pa', 'weed'),
(3, 'Movement Potion', 200, 3, '+5 Pm', 'weed');
-- (4, 'Broken Sword', 50, 50, 'A cute useless broken sword that make you thing that you\'re a true warrior but... your not ! ', 'weapon');
-- --------------------------------------------------------
--
-- Structure de la table `item_inventory`
--
CREATE TABLE `item_inventory` (
`idItem` int(11) NOT NULL,
`idInventoyCompte` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Index pour les tables exportées
--
--
-- Index pour la table `champion`
--
ALTER TABLE `champion`
ADD PRIMARY KEY (`id_champion`);
--
-- Index pour la table `compte`
--
ALTER TABLE `compte`
ADD PRIMARY KEY (`idCompte`);
--
-- Index pour la table `inventory`
--
ALTER TABLE `inventory`
ADD PRIMARY KEY (`idInventory`);
--
-- Index pour la table `items`
--
ALTER TABLE `items`
ADD PRIMARY KEY (`idItem`);
--
-- AUTO_INCREMENT pour les tables exportées
--
--
-- AUTO_INCREMENT pour la table `champion`
--
ALTER TABLE `champion`
MODIFY `id_champion` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
--
-- AUTO_INCREMENT pour la table `compte`
--
ALTER TABLE `compte`
MODIFY `idCompte` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=18;
--
-- AUTO_INCREMENT pour la table `inventory`
--
ALTER TABLE `inventory`
MODIFY `idInventory` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT pour la table `items`
--
ALTER TABLE `items`
MODIFY `idItem` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
Java
|
UTF-8
| 869 | 3.4375 | 3 |
[] |
no_license
|
package com.oracle.section8;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class ArrayTest {
public static void main(String[] args) throws FileNotFoundException{
int [] a = new int[4];
a[0] = 10;
a[1] = 20;
a[2] = 30;
a[3] = 40;
for(int i = 0; i < a.length ; i++) {
System.out.print(a[i] + " ");
}
System.out.println();
// enhanced for loop / for-each
for (int xxx : a) {
System.out.print(xxx + " ");
}
System.out.println();
System.out.println(a[4]);
System.out.println("Goodbye");
// try {
FileInputStream fis = new FileInputStream("abc.txt");
// } catch (Exception e) {
//
// }
}
}
|
Markdown
|
UTF-8
| 13,531 | 2.921875 | 3 |
[] |
no_license
|
---
author:
name: tyleryoung
picture: 110161
body: Here is my latest brainstorm on the navigation metaphor that Reveleare has created.
The three screens represent three hypothetical levels of the site, in the order
they appear. <BR> <BR>The small logo on the second two levels fades-in once the
root level is penetrated. This logo doubles as a quick navigation device and information
bar. <BR> <BR>I like this encarnation of the MT site ( other versions are visible
elsewhere on the boards ) because it actually integrates the logo presence with
the form of the site. <BR> <BR>My main question to you is how well I've succeeded
in taking the color-coded, zooming grid navigation metaphor that Revelare has pioneered,
and incorporated it into my own site in a unique fashion. <BR> <BR><img src="http://www.typophile.com/forums/messages/4100/23214.gif"
alt=""> <BR> <BR><img src="http://www.typophile.com/forums/messages/4100/23215.gif"
alt=""> <BR> <BR><img src="http://www.typophile.com/forums/messages/4100/23216.gif"
alt="">
comments:
- author:
name: aluminum
picture: 110335
body: '"zooming grid navigation metaphor " <BR> <BR>Is it really a metaphor?
As far as I can tell, it is literally a zooming grid, no? <BR> <BR>I kind of said
this last time...it's an interesting experiment in navigation, but it's
been done before. Navigation is a rather practical element to a web site. While
it's fun to come up with new ideas in interaction and then allow that interaction
to really 'be' the site, I don't think using what has already been
done really works, since this is no longer 'new' and therefore the 'hey,
cool, check this out!' factor is no longer there and you're just left
with a rather unfamiliar navigation system. <BR> <BR>In otherwords, I'd suggest
coming up with something new as in completely different, or stick with some good
tried-and-true navigation systems. <BR> <BR>As for comments on what I see now,
my only concern would be that the type is incredibly small. I can't imagine
too many people would find it that readable on a high resolution monitor (unless
you are planning on making this a resizable flash piece, which may resolve some
of the readability issues).'
created: '2004-01-02 15:42:52'
- author:
name: schwa
body: some good points, darrel <BR> <BR>additionally ... if i created a logo for
myself that looked exactly like the coca-cola logo, except that i rotated it 45
degrees .. i'm still ripping off the coca-cola logo. <BR> <BR>the diamond
shapes destroy the 'pixel metaphor' that you mentioned in an earlier post,
no?
created: '2004-01-02 16:17:20'
- author:
name: tyleryoung
picture: 110161
body: 'Darrel, yes, it literally is a zooming grid. Your points are well-made in
regards the tried and true nav systems. However, I disagree with you on a few
points. Everyone I have tested the site with has one reaction: the site is new,
cool, and intuitive. They actually get excited as they discover how the site works
by their own experimentation as the fun factor sinks in, they begin to focus on
my products, and in that brief time of newfound fun, my products become real to
them, and they like them. <BR> <BR>Not a bad way to present my products for sale,
eh? As for those who have seen and used the zooming grid before, well, they already
know how to use it. <BR> <BR>As for trying to be the world's most original
designer. I've said many times on these boards that this is not one of my
goals with the site design. I just want a site that is going to reinforce my products
as organically as possible. This zooming "pixel" navigation system does
just that. Little pixels that grow large and relveal content over and over has
the effect of transporting you into the world of the small, where pixel fonts
traditionally reside. <BR> <BR>As for the font being small: these are pixel fonts
after all. Many MT fonts are much larger than the one used in the diamond titling.
However, upon closer examination of the design, each square is on a 4x zoom factor.
That means that the small titles that represent the next "tier" of options
are set at 8pt. The title of the section you're residing in is set at 32pt.
To go from 8 to 16 at the bottom would mean 64pt up top. <BR> <BR>JH, it seems
to me now that your intentions when replying to my posts are less motivated by
a desire to contribute to the process of creation than a desire to tear down whatever
enthusiasm/credibility I may have. <BR> <BR>I could be misenterpreting your latest
reply, of course, but consder this: your whole argument on the original post centered
around the fact that my previous MT design was the exact design of Revelare's
because I used the same grid system they used. The graphics of the two sites were
too similar, and that destroyed any argument I might have about a zooming grid
not being a proprietary design. <BR> <BR>So now that I've taken that GRAPHIC
DESIGN and completely reinvented it, so that the site, its products and the zooming
itself actually takes on the shape and body of the logo presence itself (
something that the logo design had to allow for, doubling the DESIGN requirements
to pull such a thing off ), you say I'm still ripping off'
created: '2004-01-02 20:52:39'
- author:
name: schwa
body: '"Everyone I have tested the site with has one reaction: the site is new,
cool, and intuitive." <BR> <BR>the site is not new. it is definitely cool
and intuitive, but that credit should be given to the people who designed it.
<BR> <BR>Your enthusiasm is the one thing about you that I do respect. What I
desire is for you to just admit that you stole the relevare site, and stop pretending
that you 'completely reinvented' it. <BR> <BR>as far as the coca-cola
logo example goes .. you completely misunderstood. The point I was making is that
if you take someone else's design, and rotate it 45 degrees, it doesn't
make it a new design. That's what you've done with the Relevare site in
this 'new' version of your site. Apparently my illustration was unclear.
I was not saying anything about your logo, which I have no problems with. <BR>
<BR>I have realized that nothing i say will make you realize the offense you are
committing by launching this site. So go for it. I simply hope that you give credit
where credit is due, and provide a link to relevare, the designers of your site.
<BR> <BR>As for my work ... my homepage is listed in my profile .. here's
the link ... <BR> <BR><a href="http://www.jaw-schwa.com/" target="_blank">http://www.jaw-schwa.com/</a>'
created: '2004-01-02 21:26:08'
- author:
name: aluminum
picture: 110335
body: '"has one reaction: the site is new, cool, and intuitive" <BR> <BR>Well,
then I'd say go for it. <BR> <BR>Personally, I find whiz-bang navigation
not to my liking, and tend to avoid sites that use it...especially sites trying
to sell me something, but, like I said, that's just my own opinion. <BR>
<BR>As for JH's comments, he has a very valid point. You don't have to
agree with it, but realize that a percentage of your target audience may agree
with it. It's up to you to decide how big of an issue that is for you. A lot
of people will say that your site is a clear knock-off, even though is may visually
look a bit different...it's the actual site navigation that makes the site
design. The visual look is secondary. I can't say how many people will make
that connection, of course. '
created: '2004-01-02 21:58:13'
- author:
name: tyleryoung
picture: 110161
body: 'jh, <BR> <BR>First of all, let me say your work is very well done. I really
like the quality and quantity of work. The client list on bigspaceship is very
impressive as well. <BR> <BR>Now, I just want to clear a few things up. Apparently,
you have in turn not understood my words. If you visit tyleryoungcreative and
navigate to the section entitled mean tangerine, and read the text description
of the screen shot there, you will see that I have never claimed to invent the
Revelare zoom system. TYC is now one year old. My posts here are on average six
months old. Not sure about that, but ballpark. <BR> <BR>I'll say it again.
I'm not concerned with being the first one to invent the zooming grid. I never
said I was its pioneer. I never will. <BR> <BR>In your peepshow piece, you use
a mouse-sensitive mask with scrolling content behind it. Were you the first to
invent that? I doubt it, as cool as it looks. Did you commit an offence by launching
that site? I don't think you did. <BR> <BR>You are obviously an accomplished
designer with many professional clients. At the very least, you are one member
of a team of such designers. Don't you recognize what graphic design is? <BR>
<BR>The latest generation of MT takes the zooming grid idea that Revelare has
pioneered, true. It's graphic design, that is, the layout of content, its
position and coloration is completely unique. <BR> <BR>The zooming squares are
zooming squares. However, the beauty of zooming squares holding content for review
is downright brilliant, just as a mouse and an iconic interface was in the past.
I contend that a zooming grid of squares does not by itself constitute site design.
Site design involves so much more! I suppose no one should ever use this elegant,
intuitive system of organizing and presenting material for fear of not being the
first one to build it? <BR> <BR>As for Revelare designing my site: I couldn't
even get them to reply to my emails. <BR> <BR>As for me taking credit for the
site being new, cool, and intuitive. Here again, you misinterpret my words. That
is the audience's reaction. Not my assertion. Revisit every one of my long-winded
replies and you will see that I freely give credit where credit is due. <BR> <BR>Darrel,
thanks for your reply. I hear everything you say. Now, I disgree with you on some
points, but that is not to say that your counterpoint is not valid. <BR> <BR>I
do not think that the navigation system is the site design itself. Site design
is a marriage of raw concept, product enhancement and image control. It is graphic
design, content placement and description, typography, and other nuances that
are much harder to define. As for the visual look being secondary, what about
90% of all websites that use the same nav button down the left and html content
in a grid down the middle with ads across the top and down the right? <BR> <BR>Graphical
design is integral to the identity of a site. So that's my opinion, as briefly
described as it is. <BR> <BR>Many, many arthouses, even the big-name ones, feed
off of one another's designs, including navigation systems. To deny this seems
to me a silly thing to do. <BR> <BR>Ideas build upon one another, no?'
created: '2004-01-02 22:23:47'
- author:
name: Jon Whipple
picture: 110113
body: 'If I may just pipe in here: Zooming User Interfaces are not new, nor is Relevare
the first to implement such a concept. They seem to have been first to implement
it well in Flash with beautiful style and with excellent production value. <BR>
<BR>There are more examples on the web just Google for Zooming User Interface.
<BR> <BR>I have never seen an installation of Relevare's Web Index system.
From the stale date of the press releases cited on the site I think that these
guys are out of business. <a href="http://www.flashguru.co.uk/archives.php?page=15">Here's</a>
kind of a confirmation of what I suspected. <BR> <BR>I think that the ZUI is an
excellent match for MT's product. Too close to the original? Hmmm, I don't
know. In the rest of computing a window and a menu bar and a scroll button look
pretty similar from OS to OS, sometimes the colors are different, sometimes one
looks 3D and one doesn't but it's still a button that does button things.
A zoom box will pretty much look like I zoom box I suspect. A different colour,
outline, label whatever but it will still do zoom box things. <BR> <BR>I am not
a lawyer but if I was you Tyler, I think that you should be concerned if you borrowed
code. Even if these guys are bankrupt the code is probably still owned or under
copyright by somebody. Keep records of all your attempted contacts. <BR> <BR>I
think that ZUIs have a far greater role to play in computing, wheter implemented
in a grid system like this or in an infinitie space system like <a href="http://humane.sourceforge.net/the/zoom.html">this</a>.
<BR> <BR>Tyler, as I have said before, I think a zooming grid and a pixel font
house are a natural match. And if your presentation is separated from your content,
you can always modify things and tweak things later. <BR> <BR>Good luck'
created: '2004-01-04 01:31:19'
date: '2004-01-01 03:51:17'
node_type: forum
title: MT
---
|
C#
|
UTF-8
| 1,574 | 3.375 | 3 |
[] |
no_license
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JustFun.Models
{
public class QueueReconstructionByHeight
{
public int[][] Solve(int[][] arr)
{
Array.Sort(arr, new HeightComparerHelper());
int[][] ans = new int[arr.Length][];
for (int i = arr.Length - 1; i >= 0; i--)
{
InsertToPosition(ans, arr[i]);
}
return ans;
}
private void InsertToPosition(int[][] ans, int[] inner_arr)
{
if (ans[inner_arr[1]] == null)
{
ans[inner_arr[1]] = inner_arr;
return;
}
for (int i = ans.Length - 1; i > inner_arr[1]; i--)
{
if (ans[i - 1] != null)
{
ans[i] = ans[i - 1];
}
}
ans[inner_arr[1]] = inner_arr;
}
}
public class HeightComparerHelper : IComparer<int[]>
{
public int Compare(int[] x, int[] y)
{
if (x[0] < y[0])
{
return -1;
}
if (x[0] == y[0])
{
if (x[1] < y[1])
{
return 1;
}
if (x[1] == y[1])
{
return 0;
}
return -1;
}
return 1;
}
}
}
|
C++
|
WINDOWS-1251
| 720 | 3.484375 | 3 |
[] |
no_license
|
/* 3(g)
n x. y:
y= -1/x + 1/2x - 1/3x + ... + 1/nx .*/
#include "iostream"
#include <fstream>
#include <cmath>
using namespace std;
void countValue(int n, float x, float &y);
void writeFile(float &y);
int main() {
setlocale(LC_ALL, "Russian");
int n;
float x;
float y = 0;
cin >> n >> x;
countValue(n, x, y);
cout << y << endl;
writeFile(y);
getchar();
getchar();
return 0;
}
void countValue(int n, float x, float &y) {
for (int i = 1; i <= n; i++) {
if (i % 2 != 0) {
y -= (1 / (x * i));
}
else {
y += (1 / (x * i));
}
}
}
void writeFile(float &y) {
ofstream f("Results.txt");
f << y;
f.close();
}
|
Python
|
UTF-8
| 1,575 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/bin/env python3
# vim: syntax=python tabstop=2 expandtab
# coding: utf-8
#------------------------------------------------------------------------------
# Convert CSV with read counts to PyClone-VI input TSV file.
#------------------------------------------------------------------------------
# author : Harald Detering
# email : harald.detering@gmail.com
# modified : 2020-08-20
#------------------------------------------------------------------------------
from __future__ import print_function
import os, sys
import argparse
import vcf
# output header
hdr = "mutation_id sample_id ref_counts alt_counts normal_cn major_cn minor_cn".split()
def parse_args():
parser = argparse.ArgumentParser(description='Create PyClone-VI input file from CSV.')
parser.add_argument('--csv', required=True, type=argparse.FileType(), help='CSV file with somatic mutations and read counts.')
parser.add_argument('--normal', help='Normal sample id. (ignored for output)')
args = parser.parse_args()
return args
def main(args):
# print output header
print('\t'.join(hdr))
# skip input header
hdr_in = args.csv.readline()
# parse variant data
for line in args.csv:
cols = line.strip().split(',')
chrom, pos, smp, ref, alt, rc_tot, rc_alt = cols[:7]
cn_nrm = "2"
cn_maj = "1"
cn_min = "1"
if smp != args.normal:
id_var = '{}_{}'.format(chrom, pos)
rc_ref = str(int(rc_tot) - int(rc_alt))
out = [id_var, smp, rc_ref, rc_alt, cn_nrm, cn_maj, cn_min]
print('\t'.join(out))
if __name__ == '__main__':
args = parse_args()
main(args)
|
PHP
|
UTF-8
| 1,182 | 2.75 | 3 |
[] |
no_license
|
<html>
<body>
<?php
$connect = mysqli_connect('localhost', 'root', '', 'SIM')
or die('Error connecting to the server: ' . mysqli_error($connect));
$sql = 'SELECT * FROM USERS WHERE USERNAME = "' . $_POST['username'] . '"';
$result = mysqli_query($connect, $sql) or die('The query failed: ' . mysqli_error($connect));
$number = mysqli_num_rows($result);
if ($number == 0) {
$sql = 'INSERT INTO USERS (USERNAME, PASSWORD, NAME, BIRTH_DATE, ADDRESS, PHONE, EMAIL) VALUES (' .
'\'' . $_POST['username'] . '\'' . ', ' .
'\'' . md5($_POST['password']) . '\'' . ', ' .
'\'' . $_POST['name'] . '\'' . ', ' .
'\'' . $_POST['birth_date'] . '\'' . ', ' .
'\'' . $_POST['address'] . '\'' . ', ' .
'\'' . $_POST['phone'] . '\'' . ', ' .
'\'' . $_POST['email'] . '\'' . ')';
$result = mysqli_query($connect, $sql) or die('The query failed: ' . mysqli_error($connect));
echo '<p>Utilizador registado com sucesso.</p>';
} else {
include("register.php");
echo '<p>Utilizador já existente.</p>';
}
?>
</body>
</html>
|
Python
|
UTF-8
| 1,411 | 2.5625 | 3 |
[] |
no_license
|
#!/usr/bin/env python3
"""
Simple script for creating a key using KMS and applying a policy to it
__author__ = "Eddie Atkinson"
__copyright__ = "Copyright 2020"
"""
import boto3
import json
KEY_DESC = "22487668-testkey"
ALIAS = "22487668Key"
key_exists = False
JSON_FILE = "policy.json"
policy = ""
kms = boto3.client("kms")
with open(JSON_FILE, "r") as infile:
policy = json.dumps(json.load(infile))
def apply_policy(alias, kms):
keys = kms.list_keys()["Keys"]
desired_key_id = ""
for key in keys:
key_id = key["KeyId"]
aliases = kms.list_aliases(KeyId=key_id)["Aliases"]
aliases = [alias["AliasName"] for alias in aliases]
if f"alias/{alias}" in aliases:
desired_key_id = key_id
break
if not desired_key_id:
raise Exception(f"Can't find a key id for the alias {alias}")
resp = kms.put_key_policy(
KeyId=desired_key_id,
PolicyName="default",
Policy=policy,
BypassPolicyLockoutSafetyCheck=False
)
print(resp)
def create_key(kms):
resp = kms.create_key(
Description=KEY_DESC,
KeyUsage="ENCRYPT_DECRYPT",
Origin="AWS_KMS",
)
kid = resp["KeyMetadata"]["KeyId"]
arn = resp["KeyMetadata"]["Arn"]
kms.create_alias(
AliasName=f"alias/{ALIAS}",
TargetKeyId=kid
)
return kid, arn
# create_key(kms)
apply_policy(ALIAS, kms)
|
Java
|
UTF-8
| 10,003 | 1.65625 | 2 |
[] |
no_license
|
package com.app.ui;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.app.R;
import com.app.http.VerifyCodeManager;
import com.app.http.VerifyCodeManager1;
import com.app.model.PNBaseModel;
import com.app.request.RegisterRequest;
import com.app.sip.SipInfo;
import com.app.views.CleanEditText;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.mob.MobSDK;
import com.punuo.sys.app.activity.BaseSwipeBackActivity;
import com.punuo.sys.app.httplib.HttpManager;
import com.punuo.sys.app.httplib.RequestListener;
import com.punuo.sys.app.util.IntentUtil;
import com.punuo.sys.app.util.RegexUtils;
import com.punuo.sys.app.util.ToastUtils;
import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
/**
* 用户注册页
*/
public class RegisterAccountActivity extends BaseSwipeBackActivity {
@Bind(R.id.num_input)
CleanEditText numInput;
@Bind(R.id.verificode_input)
CleanEditText verificodeInput;
@Bind(R.id.get_verificode)
TextView getVerificode;
@Bind(R.id.password_set)
CleanEditText passwordSet;
@Bind(R.id.hidepassword)
ImageView hidepassword;
@Bind(R.id.btn_register)
TextView btnRegister;
@Bind(R.id.linearLayout)
LinearLayout linearLayout;
@Bind(R.id.goto_login)
TextView gotoLogin;
@Bind(R.id.iv_back)
ImageView ivBack;
private VerifyCodeManager1 codeManager1;
private EventHandler eventHandler;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_up1);
ButterKnife.bind(this);
initViews();
codeManager1 = new VerifyCodeManager1(this, numInput, getVerificode);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//因为不是所有的系统都可以设置颜色的,在4.4以下就不可以。。有的说4.1,所以在设置的时候要检查一下系统版本是否是4.1以上
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(getResources().getColor(R.color.newbackground));
}
}
private void initViews() {
numInput.setImeOptions(EditorInfo.IME_ACTION_NEXT);
verificodeInput.setImeOptions(EditorInfo.IME_ACTION_NEXT);
passwordSet.setTransformationMethod(PasswordTransformationMethod.getInstance());
passwordSet.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
// 点击虚拟键盘的done
if (actionId == EditorInfo.IME_ACTION_DONE
|| actionId == EditorInfo.IME_ACTION_GO) {
commit();
}
return false;
}
});
MobSDK.init(this, "213c5d90b2394", "793f08e685abc8a57563a8652face144");
eventHandler = new EventHandler() {
@Override
public void afterEvent(int event, int result, Object data) {
android.os.Message msg = new android.os.Message();
msg.arg1 = event;
msg.arg2 = result;
msg.obj = data;
mHandler.sendMessage(msg);
}
};
//注册回调监听接口
SMSSDK.registerEventHandler(eventHandler);
}
private RegisterRequest mRegisterRequest;
private void commit() {
showLoadingDialog();
if (mRegisterRequest != null && !mRegisterRequest.isFinish()) {
return;
}
SipInfo.userAccount2 = numInput.getText().toString().trim();
SipInfo.passWord2 = passwordSet.getText().toString().trim();
String code = verificodeInput.getText().toString().trim();
if (!checkInput(SipInfo.userAccount2, SipInfo.passWord2, code)) {
return;
}
mRegisterRequest = new RegisterRequest();
mRegisterRequest.addUrlParam("username", SipInfo.userAccount2);
mRegisterRequest.addUrlParam("password", SipInfo.passWord2);
mRegisterRequest.setRequestListener(new RequestListener<PNBaseModel>() {
@Override
public void onComplete() {
dismissLoadingDialog();
}
@Override
public void onSuccess(PNBaseModel result) {
if (result == null || result.msg == null) {
return;
}
if ("注册失败".equals(result.msg) || "手机号已注册".equals(result.msg)) {
ToastUtils.showToast(result.msg);
} else {
ToastUtils.showToast(result.msg);
IntentUtil.jumpActivity(RegisterAccountActivity.this, LoginActivity.class);
finish();
}
}
@Override
public void onError(Exception e) {
}
});
HttpManager.addRequest(mRegisterRequest);
}
private boolean checkInput(String phone, String password, String code) {
if (TextUtils.isEmpty(phone)) { // 电话号码为空
ToastUtils.showToast(R.string.tip_phone_can_not_be_empty);
} else {
if (!RegexUtils.checkMobile(phone)) { // 电话号码格式有误
ToastUtils.showToast(R.string.tip_phone_regex_not_right);
} else if (TextUtils.isEmpty(code)) { // 验证码不正确
ToastUtils.showToast(R.string.tip_please_input_code);
} else if (password.length() < 6 || password.length() > 32
|| TextUtils.isEmpty(password)) { // 密码格式
ToastUtils.showToast(R.string.tip_please_input_6_32_password);
} else {
return true;
}
}
return false;
}
@OnClick({R.id.get_verificode, R.id.hidepassword, R.id.btn_register, R.id.goto_login, R.id.iv_back})
public void onClick(View v) {
switch (v.getId()) {
case R.id.get_verificode:
codeManager1.getVerifyCode(VerifyCodeManager.REGISTER);
break;
case R.id.hidepassword:
if (passwordSet.getTransformationMethod() == PasswordTransformationMethod.getInstance()) {
hidepassword.setImageResource(R.drawable.ic_eye);
passwordSet.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
} else if (passwordSet.getTransformationMethod() == HideReturnsTransformationMethod.getInstance()) {
hidepassword.setImageResource(R.drawable.ic_hide);
passwordSet.setTransformationMethod(PasswordTransformationMethod.getInstance());
}
break;
case R.id.btn_register:
commit();
break;
case R.id.goto_login:
finish();
startActivity(new Intent(this, LoginActivity.class));
break;
case R.id.iv_back:
scrollToFinishActivity();
break;
}
}
private Handler mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
int event = msg.arg1;
int result = msg.arg2;
Object data = msg.obj;
Log.e("event", "event=" + event);
Log.e("result", "result=" + result);
// 短信注册成功后,返回LoginActivity,然后提示
if (result == SMSSDK.RESULT_COMPLETE) {
if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {// 提交验证码成功
// Toast.makeText(RegisterAccountActivity.this, "验证成功",
// Toast.LENGTH_SHORT).show();
final String phone = numInput.getText().toString().trim();
final String passWord = passwordSet.getText().toString().trim();
String code = verificodeInput.getText().toString().trim();
if (checkInput(phone, passWord, code)) {
commit();
} else {
Toast.makeText(RegisterAccountActivity.this, "填写信息格式不正确", Toast.LENGTH_SHORT).show();
}
} else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
Toast.makeText(getApplicationContext(), "验证码已经发送",
Toast.LENGTH_SHORT).show();
}
} else if (result == SMSSDK.RESULT_ERROR) {
Throwable throwable = (Throwable) data;
throwable.printStackTrace();
JsonObject obj = new JsonParser().parse(throwable.getMessage()).getAsJsonObject();
String des = obj.get("detail").getAsString();//错误描述
int status = obj.get("status").getAsInt();//错误代码
if (status > 0 && !TextUtils.isEmpty(des)) {
Toast.makeText(RegisterAccountActivity.this, des, Toast.LENGTH_SHORT).show();
}
}
return true;
}
});
}
|
SQL
|
UTF-8
| 250 | 2.640625 | 3 |
[] |
no_license
|
-- 1
SELECT DATETIME from ANIMAL_INS order by DATETIME desc limit 1
-- 2
SELECT DATETIME From ANIMAL_INS order by DATETIME asc limit 1
-- 3
SELECT COUNT(*) FROM ANIMAL_INS
-- 4
SELECT COUNT(distinct NAME) as cnt from ANIMAL_INS where NOT NAME IS NULL
|
C#
|
UTF-8
| 1,129 | 2.59375 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
using voa_ps_data_stub.Helpers;
namespace voa_ps_data_stub.Tests.Helpers
{
public class URLDataTests
{
[Fact]
public void ShouldReturnCorrectPath()
{
string directory = "/some/dir/";
string fileName = "newFile.json";
URLData urlData = new URLData(directory, fileName);
Assert.Equal("/some/dir/newFile.json", urlData.Path);
}
[Fact]
public void ShouldReturnPathWithAdditionalSlash()
{
string directory = "/some/dir";
string fileName = "newFile.json";
URLData urlData = new URLData(directory, fileName);
Assert.Equal("/some/dir/newFile.json", urlData.Path);
}
[Fact]
public void FileNameShouldRemoveLeadingSlash()
{
string directory = "/some/dir";
string fileName = "/newFile.json";
URLData urlData = new URLData(directory, fileName);
Assert.Equal("newFile.json", urlData.FileName);
}
}
}
|
C++
|
UTF-8
| 4,644 | 2.734375 | 3 |
[] |
no_license
|
#pragma once
#include <vector>
#include <unordered_map>
#include "Artifice/Core/Core.h"
#include "Artifice/Core/Log.h"
#include "RenderGraphResourceCache.h"
class RenderGraphRegistry
{
private:
RenderGraphTextureCache m_TextureCache;
RenderGraphBufferCache m_BufferCache;
std::unordered_map<std::string, uint32> m_ResourceMap;
std::vector<TextureInfo> m_Textures;
std::vector<BufferInfo> m_Buffers;
std::vector<RenderHandle> m_TextureHandles;
std::vector<RenderHandle> m_BufferHandles;
public:
RenderGraphRegistry() = default;
void Init(Device* device)
{
m_TextureCache.Init(device);
m_BufferCache.Init(device);
}
void Advance()
{
m_TextureCache.ReleaseActive();
m_BufferCache.ReleaseActive();
m_TextureCache.Advance();
m_BufferCache.Advance();
}
void Clear()
{
m_ResourceMap.clear();
m_TextureHandles.clear();
m_BufferHandles.clear();
m_Textures.clear();
m_Buffers.clear();
}
void CleanUp()
{
Clear();
m_TextureCache.Reset();
m_BufferCache.Reset();
}
bool Exists(const std::string& name) const
{
if (m_ResourceMap.find(name) != m_ResourceMap.end())
{
return true;
}
else
{
return false;
}
}
std::pair<uint32, uint32> GetAlive() const
{
return {m_TextureCache.GetAlive(), m_BufferCache.GetAlive()};
}
uint32 GetIndex(const std::string& name)
{
AR_CORE_ASSERT(m_ResourceMap.count(name), "Tried accessing resource that doesn't exists");
return m_ResourceMap[name];
}
TextureInfo GetTextureInfo(const std::string& name)
{
AR_CORE_ASSERT(m_ResourceMap.count(name), "Tried accessing resource that doesn't exists");
return m_Textures[GetIndex(name)];
}
uint32 GetTextureCount() const { return m_Textures.size(); }
uint32 GetBufferCount() const { return m_Buffers.size(); }
void ImportTexture(const std::string& name, RenderHandle texture, TextureInfo info)
{
AR_CORE_ASSERT(!m_ResourceMap.count(name), "Tried importing texture that already exists");
uint32 index = m_Textures.size();
m_ResourceMap[name] = index;
m_Textures.push_back(info);
m_TextureHandles.push_back(texture);
}
void CreateTexture(const std::string& name, TextureInfo info)
{
AR_CORE_ASSERT(!m_ResourceMap.count(name), "Tried creating texture that already exists");
uint32 index = m_Textures.size();
m_ResourceMap[name] = index;
m_Textures.push_back(info);
m_TextureHandles.push_back(RenderHandle());
}
void CreateBuffer(const std::string& name, BufferInfo info)
{
AR_CORE_ASSERT(!m_ResourceMap.count(name), "Tried creating buffer that already exists");
uint32 index = m_Buffers.size();
m_ResourceMap[name] = index;
m_Buffers.push_back(info);
m_BufferHandles.push_back(RenderHandle());
}
void AddTextureBindFlag(const std::string& name, RenderBindFlags bind_flag)
{
AR_CORE_ASSERT(m_ResourceMap.count(name), "Tried getting texture that does not exist");
m_Textures[m_ResourceMap[name]].BindFlags |= bind_flag;
}
void AddBufferBindFlag(const std::string& name, RenderBindFlags bind_flag)
{
AR_CORE_ASSERT(m_ResourceMap.count(name), "Tried getting buffer that does not exist");
m_Buffers[m_ResourceMap[name]].BindFlags |= bind_flag;
}
// Actual resource creation
RenderHandle GetTexture(const std::string& name)
{
AR_CORE_ASSERT(m_ResourceMap.count(name), "Tried getting texture that does not exist");
uint32 index = m_ResourceMap[name];
if (!m_TextureHandles[index].IsNull())
{
return m_TextureHandles[index];
}
TextureInfo key = m_Textures[index];
RenderHandle handle = m_TextureCache.Request(key);
m_TextureHandles[index] = handle;
return handle;
}
RenderHandle GetBuffer(const std::string& name)
{
AR_CORE_ASSERT(m_ResourceMap.count(name), "Tried getting buffer that does not exist");
uint32 index = m_ResourceMap[name];
if (!m_BufferHandles[index].IsNull())
{
return m_BufferHandles[index];
}
BufferInfo key = m_Buffers[index];
RenderHandle handle = m_BufferCache.Request(key);
m_BufferHandles[index] = handle;
return handle;
}
};
|
Markdown
|
UTF-8
| 886 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
# email-parser
Parser written in Java to extract and organize e-mails from an input file. User can write an e-mail using the application and save it into a file. User can also open a file and display its contents in the application. The save format below can also be found in the src folder.
-------------------------------------------------------------------------------------
File Format For E-mail Files.
All files must follow this general structure in order to be parsed by the application.
Whitespace can vary between files. The parser should be able to parse any file
with any kind of whitespace (assuming the general structure is followed).
The whitespace within the body message will be copied exactly as written by the parser.
-------------------------------------------------------------------------------------
StartEmail
To:
From:
Subject:
EndBody
EndEmail
|
C++
|
UTF-8
| 2,053 | 2.890625 | 3 |
[] |
no_license
|
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
vector<vector<double>> cost;
vector<vector<double>> minCost;
vector<int> have;
vector<double> diff;
int s, n, m, p;
int start = 0;
double calcMinCost(int st, int av)
{
if (av & 1 || av == (1 << (p + 1)) - 1)
return 0.0;
if (minCost[st][av] != INFINITY)
return minCost[st][av];
double tmp = INFINITY;
for (int i = 0; i <= p; i++) {
if (!(av & (1 << i))) {
tmp = min(tmp, cost[have[st]][have[i]] + calcMinCost(i, av | (1 << i)) - diff[i]);
}
}
minCost[st][av] = tmp;
return tmp;
}
void calcMinDistance()
{
for (int i = 0; i <= n; i++)
for (int j = 0; j <= n; j++)
for (int k = 0; k <= n; k++)
cost[j][k] = min(cost[j][k], cost[j][i] + cost[i][k]);
}
int main()
{
int i, j;
cin >> s;
for (i = 0; i < s; i++) {
cin >> n >> m;
vector<vector<double>> tmpCost(n + 1, vector<double>(n + 1, INFINITY));
for (j = 0; j <= n; j++)
tmpCost[j][j] = 0;
for (j = 0; j < m; j++) {
int from, to;
double tcost;
cin >> from >> to >> tcost;
tmpCost[from][to] = tcost;
tmpCost[to][from] = tcost;
}
cin >> p;
vector<int> tmpHave(p + 1, 0);
vector<double> tmpDiff(p + 1, 0);
tmpHave[0] = start;
tmpDiff[0] = 0.0;
for (j = 1; j < p + 1; j++)
cin >> tmpHave[j] >> tmpDiff[j];
have.swap(tmpHave);
diff.swap(tmpDiff);
cost.swap(tmpCost);
calcMinDistance();
vector<vector<double>> tmpMinCost(p + 1, vector<double>((1 << (p + 1)), INFINITY));
minCost.swap(tmpMinCost);
double answer = -calcMinCost(start, 0);
if (answer > 0.0)
printf("Daniel can save $%.2lf\n", answer);
else
printf("Don't leave the house\n");
}
return 0;
}
|
C#
|
UTF-8
| 848 | 2.796875 | 3 |
[] |
no_license
|
//USING THE STATEMNET USING IT WILL TAKE CARE TO DISPOSE CONNECTION AND PLACE TRY CATCH WITHIN PROCS
{
using (SqlConnection cnn = new SqlConnection(ConfigurationManager.AppSettings("connectionString"))) {
if (cnn.State == System.Data.ConnectionState.Closed)
cnn.Open();
using (SqlCommand cmd = new SqlCommand()) {
try {
cmd.Connection = cnn;
cmd.CommandText = "YOUR SQL STATEMENT";
int I = Convert.ToInt32(cmd.ExecuteNonQuery);
if (I > 0)
{
cmd.CommandText = "YOUR SQL STATEMENT";
//ADDITIONAL PARAMTERES
}
else
{
cmd.CommandText = "YOUR SQL STATEMENT";
//ADDITIONAL PARAMETERS
}
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
}
}
|
C++
|
UTF-8
| 476 | 3.078125 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h>
int atoi(char num[])
{
int n,i,j,len=-1;
while(num[++len]!=0);
n=0;
for(i=0;i<len;i++)
{
n*=10;
n+=num[i]-48;
}
return n;
}
int main()
{
int n;
char num[12];
printf("Ingrese una cadena de caracteres: \n");
printf("n = ");
gets (num);
n = atoi(num);
printf("La cadena convertida a entero es\n");
printf("n = %d",n);
getch();
return 0;
}
|
Java
|
UTF-8
| 10,737 | 2.171875 | 2 |
[] |
no_license
|
package org.mifosplatform.portfolio.savingsdepositproduct.domain;
import java.math.BigDecimal;
import javax.persistence.Column;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import org.apache.commons.lang.StringUtils;
import org.mifosplatform.infrastructure.core.domain.AbstractAuditableCustom;
import org.mifosplatform.organisation.monetary.domain.MonetaryCurrency;
import org.mifosplatform.portfolio.loanproduct.domain.PeriodFrequencyType;
import org.mifosplatform.portfolio.savingsdepositproduct.command.DepositProductCommand;
import org.mifosplatform.portfolio.savingsdepositproduct.exception.DepositProductValueOutsideRangeException;
import org.mifosplatform.useradministration.domain.AppUser;
@Entity
@Table(name = "m_product_deposit", uniqueConstraints={
@UniqueConstraint(columnNames = {"name"}, name="name_deposit_product"),
@UniqueConstraint(columnNames = {"external_id"}, name="externalid_deposit_product")
})
public class DepositProduct extends AbstractAuditableCustom<AppUser, Long> {
@Column(name = "name", nullable = false)
private String name;
@Column(name = "external_id", length=100)
private String externalId;
@SuppressWarnings("unused")
@Column(name = "description")
private String description;
@Column(name = "is_deleted", nullable=false)
private boolean deleted = false;
@Embedded
private MonetaryCurrency currency;
@Column(name = "minimum_balance", scale = 6, precision = 19, nullable = false)
private BigDecimal minimumBalance;
@Column(name = "maximum_balance", scale = 6, precision = 19, nullable = false)
private BigDecimal maximumBalance;
@Column(name = "interest_compounded_every", nullable=false)
private Integer interestCompoundedEvery;
@Column(name = "interest_compounded_every_period_enum", nullable=false)
private PeriodFrequencyType interestCompoundedEveryPeriodType;
@Column(name = "maturity_default_interest_rate", scale = 6, precision = 19, nullable = false)
private BigDecimal maturityDefaultInterestRate;
@Column(name = "maturity_min_interest_rate", scale = 6, precision = 19, nullable = false)
private BigDecimal maturityMinInterestRate;
@Column(name = "maturity_max_interest_rate", scale = 6, precision = 19, nullable = false)
private BigDecimal maturityMaxInterestRate;
@Column(name = "tenure_months", nullable=false)
private Integer tenureInMonths;
@Column(name = "is_renewal_allowed", nullable=false)
private boolean renewalAllowed = false;
@Column(name = "is_preclosure_allowed", nullable=false)
private boolean preClosureAllowed = false;
@Column(name = "is_compounding_interest_allowed", nullable=false)
private boolean interestCompoundingAllowed = false;
@Column(name = "pre_closure_interest_rate", scale = 6, precision = 19, nullable = false)
private BigDecimal preClosureInterestRate;
@Column(name = "is_lock_in_period_allowed", nullable=false)
private boolean isLockinPeriodAllowed = false;
@Column(name = "lock_in_period", nullable=false)
private Integer lockinPeriod;
@Column(name = "lock_in_period_type", nullable=false)
private PeriodFrequencyType lockinPeriodType;
protected DepositProduct() {
//
}
public DepositProduct(final String name, final String externalId,
final String description,
final MonetaryCurrency currency, final BigDecimal minimumBalance,
final BigDecimal maximumBalance, final Integer tenureMonths,
final BigDecimal maturityDefaultInterestRate,
final BigDecimal maturityMinInterestRate,
final BigDecimal maturityMaxInterestRate,
final Integer interestCompoundedEvery,
final PeriodFrequencyType interestCompoundedEveryPeriodType,
final boolean canRenew,
final boolean canPreClose,
final BigDecimal preClosureInterestRate,
final boolean isInterestCompoundingAllowed,
final boolean isLockinPeriodAllowed,
final Integer lockinPeriod,
final PeriodFrequencyType lockinPeriodType) {
this.name = name.trim();
if (StringUtils.isNotBlank(description)) {
this.description = description.trim();
} else {
this.description = null;
}
if (StringUtils.isNotBlank(externalId)) {
this.externalId = externalId.trim();
} else {
this.externalId = null;
}
this.currency = currency;
this.minimumBalance = minimumBalance;
this.maximumBalance = maximumBalance;
this.tenureInMonths = tenureMonths;
this.maturityDefaultInterestRate = maturityDefaultInterestRate;
this.maturityMinInterestRate = maturityMinInterestRate;
this.maturityMaxInterestRate = maturityMaxInterestRate;
this.interestCompoundedEvery = interestCompoundedEvery;
this.interestCompoundedEveryPeriodType = interestCompoundedEveryPeriodType;
this.renewalAllowed = canRenew;
this.preClosureAllowed = canPreClose;
this.preClosureInterestRate = preClosureInterestRate;
this.interestCompoundingAllowed = isInterestCompoundingAllowed;
this.isLockinPeriodAllowed = isLockinPeriodAllowed;
this.lockinPeriod = lockinPeriod;
this.lockinPeriodType = lockinPeriodType;
}
public MonetaryCurrency getCurrency() {
return currency;
}
public Integer getInterestCompoundedEvery() {
return interestCompoundedEvery;
}
public PeriodFrequencyType getInterestCompoundedEveryPeriodType() {
return interestCompoundedEveryPeriodType;
}
public Integer getTenureInMonths() {
return tenureInMonths;
}
public BigDecimal getMaturityDefaultInterestRate() {
return maturityDefaultInterestRate;
}
public BigDecimal getMaturityMinInterestRate() {
return maturityMinInterestRate;
}
public BigDecimal getPreClosureInterestRate() {
return preClosureInterestRate;
}
public boolean isRenewalAllowed() {
return this.renewalAllowed;
}
public boolean isPreClosureAllowed() {
return this.preClosureAllowed;
}
public boolean isInterestCompoundingAllowed() {
return interestCompoundingAllowed;
}
public boolean isLockinPeriodAllowed() {
return isLockinPeriodAllowed;
}
public Integer getLockinPeriod() {
return lockinPeriod;
}
public PeriodFrequencyType getLockinPeriodType() {
return lockinPeriodType;
}
public boolean isDeleted() {
return deleted;
}
/**
* Delete is a <i>soft delete</i>. Updates flag on product so it wont appear in query/report results.
*
* Any fields with unique constraints and prepended with id of record.
*/
public void delete() {
this.deleted = true;
this.name = this.getId() + "_DELETED_" + this.name;
this.externalId = this.getId() + "_DELETED_" + this.externalId;
}
public void update(final DepositProductCommand command, final PeriodFrequencyType interestCompoundingFrequency, final PeriodFrequencyType lockinPeriodType){
if (command.isExternalIdChanged()) {
this.externalId = command.getExternalId();
}
if (command.isNameChanged()) {
this.name = command.getName();
}
if (command.isDescriptionChanged()) {
this.description = command.getDescription();
}
Integer digitsAfterDecimalChanged = this.currency.getDigitsAfterDecimal();
if (command.isDigitsAfterDecimalChanged()) {
digitsAfterDecimalChanged = command.getDigitsAfterDecimal();
}
String currencyCodeChanged = this.currency.getCode();
if (command.isCurrencyCodeChanged()) {
currencyCodeChanged = command.getCurrencyCode();
}
if (command.isDigitsAfterDecimalChanged() || command.isCurrencyCodeChanged()) {
this.currency = new MonetaryCurrency(currencyCodeChanged, digitsAfterDecimalChanged);
}
if(command.isMinimumBalanceChanged()){
this.minimumBalance=command.getMinimumBalance();
}
if(command.isMaximumBalanceChanged()){
this.maximumBalance=command.getMaximumBalance();
}
if(command.isTenureMonthsChanged()){
this.tenureInMonths=command.getTenureInMonths();
}
if (command.isMaturityDefaultInterestRateChanged()) {
this.maturityDefaultInterestRate=command.getMaturityDefaultInterestRate();
}
if(command.isMaturityMaxInterestRateChanged()){
this.maturityMaxInterestRate=command.getMaturityMaxInterestRate();
}
if (command.isMaturityMinInterestRateChanged()) {
this.maturityMinInterestRate=command.getMaturityMinInterestRate();
}
if (command.isInterestCompoundedEveryChanged()) {
this.interestCompoundedEvery = command.getInterestCompoundedEvery();
}
if (command.isInterestCompoundedEveryPeriodTypeChanged()) {
this.interestCompoundedEveryPeriodType = interestCompoundingFrequency;
}
if (command.isRenewalAllowedChanged()) {
this.renewalAllowed=command.isRenewalAllowed();
}
if (command.isPreClosureAllowed()) {
this.preClosureAllowed=command.isPreClosureAllowed();
}
if (command.isPreClosureInterestRateChanged()) {
this.preClosureInterestRate=command.getPreClosureInterestRate();
}
if(command.interestCompoundingAllowedChanged()){
this.interestCompoundingAllowed = command.isInterestCompoundingAllowed();
}
if(command.isLockinPeriodAllowedChanged()){
this.isLockinPeriodAllowed = command.isLockinPeriodAllowed();
}
if(command.isLockinPeriodChanged()){
this.lockinPeriod = command.getLockinPeriod();
}
if(command.isLockinPeriodTypeChanged()){
this.lockinPeriodType = lockinPeriodType;
}
}
public void validateInterestRateInRange(final BigDecimal interestRate) {
boolean inRange = true;
if (interestRate.compareTo(this.maturityMinInterestRate) < 0) {
inRange = false;
}
if (this.maturityMaxInterestRate.compareTo(interestRate) < 0) {
inRange = false;
}
if (!inRange) {
final String actualValue = interestRate.toPlainString();
final String minValue = (this.maturityMinInterestRate == null) ? "" : this.maturityMinInterestRate.toPlainString();
final String maxValue = (this.maturityMaxInterestRate == null) ? "" : this.maturityMaxInterestRate.toPlainString();
throw new DepositProductValueOutsideRangeException(actualValue, minValue, maxValue, "deposit.account.maturityInterestRate");
}
}
public void validateDepositInRange(final BigDecimal depositAmount) {
boolean inRange = true;
if (depositAmount.compareTo(this.minimumBalance) < 0) {
inRange = false;
}
if (this.maximumBalance != null && this.maximumBalance.compareTo(depositAmount) < 0) {
inRange = false;
}
if (!inRange) {
final String actualValue = depositAmount.toPlainString();
final String minValue = (this.minimumBalance == null) ? "" : this.minimumBalance.toPlainString();
final String maxValue = (this.minimumBalance == null) ? "" : this.minimumBalance.toPlainString();
throw new DepositProductValueOutsideRangeException(actualValue, minValue, maxValue, "deposit.account.deposit.amount");
}
}
}
|
Markdown
|
UTF-8
| 5,848 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
---
date: 2019-07-23
title: "Live Stellar Wallet for Testing Smart Contracts"
published: false
tags: ["react", "projects", "css", "javascript"]
canonical_url:
cover_image: ../../images/coverImages/2019-07-23-cover-image.jpeg
---
I am very happy to announce the [Live](https://stellar-wallet.netlify.com) version of my open-source Stellar testnet wallet. Here is the code on [Github](https://github.com/edezekiel/stellar-wallet).
This is for Stellar enthusiasts and anyone working on stellar smart contracts. Below, I'll (1) explain why this tool is useful, (2) discuss some background information about Stellar smart contracts, (3) provide short answers to some of the most challenging questions I faced during development, (4) give brief instructions on how to use this tool, and (5) list some resources that I found helpful.
**Disclaimer**: _I built this as an educational experiment and the program has not been thoroughly tested._
## 1. Why Build this Stellar Tool?
I work at a blockchain development company called [web3devs](https://web3devs.com/). We're probably most well known for our work on Ethereum smart contracts, but we also work with Stellar smart contracts!
Although Stellar.org explains the concepts behind [Mutisignature Escrow Account with Time Lock & Recovery](https://www.stellar.org/developers/guides/walkthroughs/stellar-smart-contracts.html), and provides [example code](https://www.stellar.org/developers/js-stellar-base/reference/base-examples.html) for creating a multi-sig account, they do not show how to implement the time lock or recovery methods. **With this post, I am releasing that code and a live demonstration of how it works.**
## 2. Background Information
Most applications interact with the Stellar network through Horizon, a RESTful HTTP API server. See [Stellar.org](https://www.stellar.org/developers/guides/get-started/). You use a SDK to interact with Horizon. I used the Javascript SDK.
There are significant differences between Ethereum and Stellar smart contracts. For one thing, Ethereum smart contracts are written in Solidity, which is a Turing-complete language.
In contrast, stellar smart contracts can only accomplish a limited set of tasks. You use a common programming language like JavaScript or Go to You interact with Horizon, which is an interface between Stellar Core and applications that want to access the Stellar network.
## 3. Pernicious Bugs and Tricky Questions
#### Why Does My Transaction Keep Failing (Getting 400 Response from Horizon)?
1. You didn't set the base fee:
```javascript
const baseFee = await server.fetchBaseFee();
const transaction = new StellarSdk.TransactionBuilder(account, {
fee: baseFee })
```
2. You didn't load the account before building the transaction:
```javascript
const account = await server.loadAccount(sourceKeys.publicKey());
const transaction = new StellarSdk.TransactionBuilder(account, { fee: baseFee })
```
#### Why can't I submit the Unlock XDR to Horizon?
You may be trying to submit the XDR too early. The unlock XDR can only be submitted _after_ the lock-up period is over. This is a little confusing, because you have to create the unlock transaction _before_ the lock-up period is over.
The solution is signing the unlock transaction, and saving that transaction somewhere publicly. Only submit the unlock xdr to Horizon once the lock up period is over.
```javascript
try {
// Save as an XDR string
const transactionXDR = transaction
.toEnvelope()
.toXDR()
.toString("base64");
console.log("FN: unlock", "Success! Results:"), transactionXDR);
return transactionXDR;
}
```
#### How do I set timebounds?
It was not easy to figure out the syntax for setting timebounds. Here is what finally worked for me:
```javascript
// The unlock date (D+T) is the first date that the unlock transaction can be
// submitted. If Transaction 3 (this transaction) is submitted before the
// unlock date, the transaction will not be valid.
const transaction = new StellarSdk.TransactionBuilder(escrowAccount, {
fee: baseFee,
timebounds: {
minTime: (
Math.floor(Date.now() / 1000) + parseInt(unlockTx.unlockDate)
).toString(),
// The maximum time is set to 0, to denote that the transaction does not have
// an expiration date.
maxTime: (0).toString()
},
sequence: (parseInt(escrowAccount.sequence) + 1).toString()
})
```
## 4. Instructions
In order to use this tool you'll need to create at least two testnet accounts. You can make new accounts within the tool by clicking the "Create Stellar Account" button. Just take note of the public and private keys that pop up in the header.
**Note:** these are test accounts so no real money is involved. You should never post a secret key to an account on the public stellar server.
You can image one account as a "seller" (the Destination), and another as a "buyer". The buyer creates the escrow account and adds the seller (Destination) as a signer. When the lockout period expires the seller can use the XDR to "unlock" funds in the escrow account.
## 5. Resources:
Here are some of the resources I found helpful:
- [Stellar Laboratory:](https://www.stellar.org/laboratory/) I constantly had this tab open to test various operations, transactions, etc.
- [Michiel Mulders Article:](https://medium.com/wearetheledger/stellar-escrow-smart-contract-development-4c43ef32ac4b) Helps you get a little more familiar with the concept of account signers.
- [Sylvain Faucherand Article:](https://medium.com/coinmonks/simple-escrow-contract-using-stellar-67aa799f7db) Covers a basic escrow account, but doesn't address how to make it time-locked.
- [Robert Durst Article:](https://hackernoon.com/i-just-wrote-a-stellar-smart-contract-pt-2-lets-dive-a-little-deeper-a8dae19b9d0a) If you're still scratching your head about account signatures.
|
C++
|
UHC
| 638 | 3.21875 | 3 |
[] |
no_license
|
/*
* ex.15-11.cpp
*
* Created on: 2018. 11. 12.
* Author: kgall305
*/
#include <iostream>
using namespace std;
int main() {
int n, sum, average;
while(true) {
cout << " Էϼ : ";
cin >> sum;
cout << "ο Էϼ : ";
cin >> n;
try {
if (n<=0)
throw n;
else {
average = sum / n;
}
}
catch(int x) {
cout << " !! : ";
cout << x << " \n" << endl;
continue ;
}
cout << " = " << average << endl << endl;
return 0;
}
}
|
Java
|
UTF-8
| 2,076 | 2.09375 | 2 |
[] |
no_license
|
package taro.service;
import taro.app.logger.gps.auto.LogInfo;
import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.provider.Settings;
import android.provider.Settings.Secure;
import android.util.Log;
import android.view.Window;
public class AutoGPSLogService extends Service {
public class AutoGPSLogBinder extends Binder {
public AutoGPSLogService getService() {
return AutoGPSLogService.this;
}
}
private static final String TAG = "AutoGPSLogService";
private final AutoGPSLogBinder mBinder = new AutoGPSLogBinder();
private final Handler mHandler = new Handler();
private AutoGPSLogRunner mRunner;
private GPSListener mGPSListener;
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public void onCreate() {
super.onCreate();
enableGPS();
mGPSListener = new GPSListener(this);
mGPSListener.connect();
mRunner = new AutoGPSLogRunner(this, mGPSListener, mHandler);
mHandler.post(mRunner);
Intent intent = new Intent(AutoGPSLogService.this, BrightenByHandService.class);
startService(intent);
}
private void enableGPS() {
String providers =
Secure.getString(getContentResolver(), Secure.LOCATION_PROVIDERS_ALLOWED);
Log.i(TAG, "providers: " + providers);
if (providers.indexOf("gps", 0) == -1) {
// GPS が無効になっているので設定画面を開く
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
@Override
public void onDestroy() {
Intent intent = new Intent(AutoGPSLogService.this, BrightenByHandService.class);
stopService(intent);
mHandler.removeCallbacks(mRunner);
mGPSListener.disconnect();
super.onDestroy();
}
public Location getLocation() {
return mRunner.getLocation();
}
public double getDistance() {
return mRunner.getDistance();
}
}
|
JavaScript
|
UTF-8
| 1,952 | 3.125 | 3 |
[] |
no_license
|
function LikeButton() {
const [liked, setLiked] = React.useState(false);
const text = liked ? '좋아요 취소' : '좋아요';
// return React.createElement(
// 'button', // keyof ReactHTML
// { onClick: () => setLiked(!liked) }, // ...children : 이하 children 속성
// text,
// );
return <button onClick={() => setLinked(!liked)}>{text}</button>;
}
function Container() {
const [count, setCount] = React.useState(false);
return (
<div>
<LikeButton />
<div>
<span>현재 카운트: </span>
<span style={{ marginRight: 10 }}>{count}</span>
<button onClick={() => setCount(count + 1)}>증가</button>
<button onClick={() => setCount(count - 1)}>감소</button>
</div>
</div>
)
}
const domContainer = document.getElementById('root');
ReactDOM.render(React.createElement(Container), domContainer);
//const domContainer = document.getElementById('root');
//ReactDOM.render(React.createElement(LikeButton), domContainer); // ReactDom , 스크림트 실행될때 전역변수로 노출된다.
// 방법 1
// const domContainer1 = document.getElementById('root1');
// ReactDOM.render(React.createElement(LikeButton), domContainer1); // ReactDom , 스크림트 실행될때 전역변수로 노출된다.
// const domContainer2 = document.getElementById('root2');
// ReactDOM.render(React.createElement(LikeButton), domContainer2);
// const domContainer3 = document.getElementById('root3');
// ReactDOM.render(React.createElement(LikeButton), domContainer3);
// 방법 2
//const domContainer = document.getElementById('root');
//ReactDOM.render(
// React.createElement(
// 'div',
// null,
// React.createElement(LikeButton),
// React.createElement(LikeButton),
// React.createElement(LikeButton),
// ),
// domContainer
// );
|
Java
|
WINDOWS-1250
| 2,487 | 2.0625 | 2 |
[] |
no_license
|
package br.com.sicoob.sisbr.sicoobdda.entidades;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import br.com.sicoob.sisbr.sicoobdda.entidades.anotacao.Conversor;
/**
* SituacaoProcessamentoArquivo responsvel por
*
* @author Francisco.Marcio
*/
@Entity
@Table(name = "SITUACAOPROCESSAMENTOARQUIVO", schema = "DDA")
@Conversor(vo = "br.com.sicoob.sisbr.sicoobdda.comumfachada.vo.SituacaoProcessamentoArquivoVO")
public class SituacaoProcessamentoArquivo extends SicoobDDAEntidade {
private static final long serialVersionUID = 0L;
public static final short ARQUIVO_DISPONIVEL = 1;
public static final short ARQUIVO_ABERTO = 2;
public static final short REGISTROS_DETALHADOS = 3;
public static final short ARQUIVO_EM_PROCESSAMENTO = 4;
public static final short ARQUIVO_PROCESSADO = 5;
public static final short ARQUIVO_REJEITADO = 6;
public static final short ARQUIVO_ADDARR2_REJEITADO_756 = 7;
@Id
@Column(name = "CODSITUACAOPROCESSAMENTOARQUIVO", unique = true, nullable = false)
private short codSituacaoProcessamentoArquivo;
@Column(name = "DESCSITUACAOPROCESSAMENTOARQUIVO", nullable = false)
private String descSituacaoProcessamentoArquivo;
/**
*
*/
public SituacaoProcessamentoArquivo() {
}
/**
* @param codSituacaoProcessamentoArquivo
*/
public SituacaoProcessamentoArquivo(short codSituacaoProcessamentoArquivo) {
this.codSituacaoProcessamentoArquivo = codSituacaoProcessamentoArquivo;
}
/**
* @return o atributo codSituacaoProcessamentoArquivo
*/
public short getCodSituacaoProcessamentoArquivo() {
return codSituacaoProcessamentoArquivo;
}
/**
* Define o atributo codSituacaoProcessamentoArquivo
*/
public void setCodSituacaoProcessamentoArquivo(short codSituacaoProcessamentoArquivo) {
this.codSituacaoProcessamentoArquivo = codSituacaoProcessamentoArquivo;
}
/**
* @return o atributo descSituacaoProcessamentoArquivo
*/
public String getDescSituacaoProcessamentoArquivo() {
return descSituacaoProcessamentoArquivo;
}
/**
* Define o atributo descSituacaoProcessamentoArquivo
*/
public void setDescSituacaoProcessamentoArquivo(String descSituacaoProcessamentoArquivo) {
this.descSituacaoProcessamentoArquivo = descSituacaoProcessamentoArquivo;
}
}
|
Python
|
UTF-8
| 1,328 | 3.140625 | 3 |
[] |
no_license
|
import tkinter as tk
class nom_fichier(tk.Toplevel):
def __init__(self, parent, titre='titre', message='message'):
tk.Toplevel.__init__(self, parent)
self.title = titre
self.entry = tk.Entry(self, width=50)
self.entry.grid(row=1, columnspan=2, padx=2, pady=5)
tk.Button(self, text='Valider', command=self.valider).grid(row=2, column=0,
sticky=tk.W + tk.E, padx=2, pady=5)
tk.Button(self, text='Annuler', command=self.destroy).grid(row=2, column=1,
sticky=tk.W + tk.E, padx=2, pady=5)
self.wait_window(self)
def valider(self):
if not self.valid():
return
self.sortie()
self.destroy()
def valid(self):
self.filename = self.entry.get()
self.entry.delete(0, tk.END)
if self.filename == '':
return 0
else:
return 1
def sortie(self):
return self.filename
if __name__ == '__main__':
root = tk.Tk()
new_canal = nom_fichier(root, titre='Nom du Canal',
message='Veulliez saisir le nom du nouveau canal')
filename = new_canal.sortie() + '.cfg'
print
filename
root.mainloop()
|
Python
|
UTF-8
| 660 | 2.6875 | 3 |
[] |
no_license
|
from util.data import recordings, shows, productions
def find_recordings_by_show_title(title):
if title not in shows:
return []
title = shows[title]
if title in recordings:
return [item for sublist in list(recordings[title].values()) for item in sublist]
return []
def find_recordings_by_show_title_and_production(title, production):
if title not in shows:
return []
title = shows[title]
if production not in productions:
return []
production = productions[production]
if title in recordings and production in recordings[title]:
return recordings[title][production]
return []
|
C++
|
UTF-8
| 2,135 | 3.609375 | 4 |
[] |
no_license
|
#include <iostream>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <string>
using namespace std;
/*
Given two English words of the same length, say, "HEAD" and "TAIL", come up with a
sequence of valid English words, starting with "HEAD", and ending with "TAIL", such
that each word is formed by changing a single letter of the previous word.
*/
vector<string> generateCandidate(const string ¤t, const unordered_set<string> &dict) {
const string alphabet = "abcdefghijklmnopqrestuvwxyz";
vector<string> candidates;
for (int i = 0; i < current.size(); i++) {
string candidate = current;
for (int j = 0; j < alphabet.size(); j++) {
candidate[i] = alphabet[j];
if (candidate == current) {
continue;
}
auto it = dict.find(candidate);
if (it != dict.end()) {
candidates.push_back(candidate);
}
}
}
return candidates;
}
vector<string> getReachables(const string ¤t, const unordered_set<string> &dict) {
vector<string> reachables;
reachables = generateCandidate(current, dict);
return reachables;
}
vector<string> bfsGoalNodes(const string &start, const string &goal, const unordered_set<string> &dict) {
vector<string> sequence;
queue<string> q;
unordered_set<string> visited;
q.push(start);
while (!q.empty()) {
string current = q.front();
q.pop();
auto it = visited.find(current);
if (it != visited.end()) {
continue;
}
visited.insert(current);
sequence.push_back(current);
if (current == goal) {
return sequence;
}
vector<string> reachables = getReachables(current, dict);
for (auto &reachable : reachables) {
q.push(reachable);
}
}
}
int main() {
// your code goes here
unordered_set<string> dict_4_letters = {"head", "heal", "teal", "tell",
"tall", "tail", "mike", "rolf"};
vector<string> sequence = bfsGoalNodes("head", "tail", dict_4_letters);
for (auto &e : sequence) {
cout << e << endl;
}
return 0;
}
|
Ruby
|
UTF-8
| 2,970 | 3.78125 | 4 |
[] |
no_license
|
### String・シンボル・配列
## 文字列のencoding
a = "Ruby"
p a.encoding #=>'#<Encoding:UTF-8>
b = a.encode("SJIS")
p b.encoding #=>#<Encoding:Windows-31J>
## 文字列の比較
p 'a' < 'b' #=> true
p 'ab' < 'ac' #=> true
p 'ab' < 'ab' #=> false
p 'ab' == 'ab' #=> true
p 'ab' <=> 'ab' #=> 0
p 'a' <=> 'b' #=> -1
## シンボル
p sym1 = :'symbol' #=> :symbol
p sym2 = :"symbol" #=> :symbol
p sym3 = :symbol #=> :symbol
# 文字列からシンボルに変える。
p "string".to_sym #=> :string
# 文字列とシンボルの違い=(文字列は毎回新たにオブジェクトを生成するのでオブジェクトIDが変わる。
# 一方でシンボルでは同じオブジェクトを参照するのでオブジェクトIDは変わらない。)
p "string".object_id #=> 70311219446720
p "string".object_id #=> 70311219446560
p :symbol.object_id #=> 816028
p :symbol.object_id #=> 816028
p "string".equal?("string") #=> false
p :symbol.equal?(:symbol) #=> true
## Arrayの初期作成
p Array.new(4) #=> [nil, nil, nil, nil]
p Array.new(2) { |index| index + 10 } #=> [10, 11]
p Array.new(3, "a") #=> ["a", "a", "a"]
p Array.new(3) { |i| i * 3 } #=> [0, 3, 6]
# サイズを超えた要素への代入
p arry = [10] #=> [10]
p arry.length #=> 1
p arry[3] = "aa" #=>
p arry #=> [10, nil, nil, "aa"]
p arry.length #=> 4
# インデックスに負の整数を指定/要素数を指定した要素の参照
p arry[-2] #=> nil
p arry[1, 3] #=> [nil nil, "aa"](インデックス1から3個分)
## 多重代入/可変長引数
a, b, c = 1, 2, 3
p c #=> 3
a, b, c = [1, 2, 3]
p c #=> 3
def method
return 1, 2, 3
end
p a, b, c = method #=> [1, 2, 3]
# 多重代入で値の個数が足りない場合
a, b, c = 1, 2
p c #=> nil
# 多重代入で値の個数が多い場合
a, b = 1, 2, 3
p b #=> 2
# 1つの変数に複数の値を代入
a = 1, 2
p a #=> [1, 2]
# 最後の変数に配列で代入
a, *b = 1, 2, 3
p b #=> [2, 3]
# 可変長引数
def method1(a, *b)
b
end
p method1(1, 2, 3) #=> [2, 3]
##配列の演算
arry1 = [1, 1, 2, 2]
arry2 = [2, 2, 3, 3]
arry3 = [1]
p arry1 & arry2 #=> [2] 集合の積演算
p arry1 | arry2 #=> [1, 2, 3] 集合の和演算 *どちらも重複する値は削除される。
#+演算子と-演算子
p arry1 + arry2 #=> [1, 1, 2, 2, 2, 2, 3, 3]
p arry1 - arry2 #=> [1, 1]
p arry1 - arry3 #=> [2, 2] 対象が重複している場合は全て取り除く。
p arry1 * 2 #=> [1, 1, 2, 2, 1, 1, 2, 2]
p arry1 * "-" #=> "1-1-2-2" joinと同じ働きをする。
#for式とスコープ(for式最大の特徴)(if式も同じ特徴を持つ)
for i in [2, 3, 4] do
v1 = 2
end
p v1 #=> 2 for式ではスコープは作成されないので内部で宣言した変数を外部でも参照可能。
|
C
|
UTF-8
| 210 | 2.921875 | 3 |
[] |
no_license
|
#include <stdio.h>
int main(void)
{
int *arr;
int *tmp;
arr = malloc(sizeof(int) * 6);
/* if error */
tmp = realloc(arr, sizeof(int) * 8);
if (tmp == NULL) {
}
arr = tmp;
free(arr);
return 0;
}
|
Python
|
UTF-8
| 148 | 2.515625 | 3 |
[] |
no_license
|
#!/usr/bin/python
from Core.CoreCommand import CoreCommand
class PrintStringCommand(CoreCommand):
def execute(self):
print(self._obj)
|
Swift
|
UTF-8
| 577 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
//
// MeshMessage.swift
//
// Created by wesgoodhoofd on 2019-01-22.
//
import UIKit
import ObjectMapper
public class MeshMessage: RBSMessage {
public var triangles: MeshTriangleMessage[]? = [MeshTriangleMessage[]]()
public var vertices: PointMessage[]? = [PointMessage[]]()
public override init() {
super.init()
triangles = MeshTriangleMessage[]()
vertices = PointMessage[]()
}
public required init?(map: Map) {
super.init(map: map)
}
public override func mapping(map: Map) {
triangles <- map["triangles"]
vertices <- map["vertices"]
}
}
|
Java
|
ISO-8859-1
| 2,587 | 2 | 2 |
[] |
no_license
|
package gcom.gui.relatorio.atendimentopublico;
import gcom.gui.atendimentopublico.registroatendimento.ConsultarRegistroAtendimentoActionForm;
import gcom.relatorio.ExibidorProcessamentoTarefaRelatorio;
import gcom.relatorio.atendimentopublico.RelatorioConsultarRegistroAtendimento;
import gcom.seguranca.acesso.usuario.Usuario;
import gcom.tarefa.TarefaRelatorio;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
/**
* action responsvel pela exibio do relatrio de bairro manter
*
* @author Svio Luiz
* @created 11 de Julho de 2005
*/
public class GerarRelatorioRegistroAtendimentoConsultarAction extends
ExibidorProcessamentoTarefaRelatorio {
/**
* < <Descrio do mtodo>>
*
* @param actionMapping
* Descrio do parmetro
* @param actionForm
* Descrio do parmetro
* @param httpServletRequest
* Descrio do parmetro
* @param httpServletResponse
* Descrio do parmetro
* @return Descrio do retorno
*/
public ActionForward execute(ActionMapping actionMapping,
ActionForm actionForm, HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse) {
// cria a varivel de retorno
ActionForward retorno = null;
ConsultarRegistroAtendimentoActionForm consultarRegistroAtendimentoActionForm = (ConsultarRegistroAtendimentoActionForm) actionForm;
String idRegistroAtendimento = consultarRegistroAtendimentoActionForm
.getNumeroRAPesquisado();
String tipoRelatorio = httpServletRequest.getParameter("tipoRelatorio");
RelatorioConsultarRegistroAtendimento relatorioConsultarRegistroAtendimento = new RelatorioConsultarRegistroAtendimento(
(Usuario)(httpServletRequest.getSession(false)).getAttribute("usuarioLogado"));
relatorioConsultarRegistroAtendimento.addParametro(
"idRegistroAtendimento", new Integer(idRegistroAtendimento));
if (tipoRelatorio == null) {
tipoRelatorio = TarefaRelatorio.TIPO_PDF + "";
}
relatorioConsultarRegistroAtendimento.addParametro(
"tipoFormatoRelatorio", Integer.parseInt(tipoRelatorio));
retorno = processarExibicaoRelatorio(
relatorioConsultarRegistroAtendimento, tipoRelatorio,
httpServletRequest, httpServletResponse, actionMapping);
// devolve o mapeamento contido na varivel retorno
return retorno;
}
}
|
Python
|
UTF-8
| 702 | 3.3125 | 3 |
[] |
no_license
|
import math
def fuel_equation(mass):
amount = math.floor(mass / 3) - 2
return (amount if (amount > 0) else 0)
def first(input):
return sum([fuel_equation(n) for n in input])
def second(input):
def add_fuel(fuel):
amount = fuel_equation(fuel)
return (amount + add_fuel(amount) if amount > 0 else 0)
return sum([add_fuel(n) for n in input])
def main():
with open('input.txt') as file:
input = [int(n) for n in file.read().split('\n') if (n)]
firstSolution = first(input)
secondSolution = second(input)
outMsg = f"Solutions:\nPart 1: {firstSolution}\nPart 2: {secondSolution}"
print(outMsg)
################################
if (__name__ == "__main__"): main()
|
Java
|
UTF-8
| 370 | 1.507813 | 2 |
[] |
no_license
|
package rm.tabou2.storage.tabou.dao.operation;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import rm.tabou2.storage.tabou.entity.operation.TypeAmenageurEntity;
public interface TypeAmenageurDao extends CrudRepository<TypeAmenageurEntity, Long>, JpaRepository<TypeAmenageurEntity, Long> {
}
|
Java
|
UTF-8
| 1,294 | 2.8125 | 3 |
[
"MIT"
] |
permissive
|
import org.junit.Assert;
import org.junit.Test;
public class SolutionTest {
@Test
public void testCase0() {
final int[][] arr = {
{1, 1, 1, 0, 0, 0},
{0, 1, 0, 0, 0, 0},
{1, 1, 1, 0, 0, 0},
{0, 0, 2, 4, 4, 0},
{0, 0, 0, 2, 0, 0},
{0, 0, 1, 2, 4, 0}
};
final int result = Solution.hourglassSum(arr);
Assert.assertEquals(19, result);
}
@Test
public void testCase1() {
final int[][] arr = {
{1, 1, 1, 0, 0, 0},
{0, 1, 0, 0, 0, 0},
{1, 1, 1, 0, 0, 0},
{0, 9, 2, -4, -4, 0},
{0, 0, 0, -2, 0, 0},
{0, 0, -1, -2, -4, 0}
};
final int result = Solution.hourglassSum(arr);
Assert.assertEquals(13, result);
}
@Test
public void testCase2() {
final int[][] arr = {
{-9, -9, -9, 1, 1, 1},
{0, -9, 0, 4, 3, 2},
{-9, -9, -9, 1, 2, 3},
{0, 0, 8, 6, 6, 0},
{0, 0, 0, -2, 0, 0},
{0, 0, 1, 2, 4, 0}
};
final int result = Solution.hourglassSum(arr);
Assert.assertEquals(28, result);
}
}
|
TypeScript
|
UTF-8
| 1,166 | 2.65625 | 3 |
[] |
no_license
|
import { getRepository, Repository } from 'typeorm';
import IUsersRepository from '../../repositories/IUsersRepository';
import ICreateUserDTO from '../../dtos/ICreateUserDTO';
import Users from '../entities/Users';
class UsersRepository implements IUsersRepository {
private ormRepository: Repository<Users>;
constructor() {
this.ormRepository = getRepository(Users);
}
public async findAll(): Promise<Users[]> {
const user = await this.ormRepository.find();
return user;
}
public async findByEmail(email: string): Promise<Users | undefined> {
const user = await this.ormRepository.findOne({
where: { email },
});
return user;
}
public async findByCPF(cpf: string): Promise<Users | undefined> {
const user = await this.ormRepository.findOne({
where: { cpf },
});
return user;
}
public async store(data: ICreateUserDTO): Promise<Users> {
const user = this.ormRepository.create(data);
await this.ormRepository.save(user);
return user;
}
public async update(user: Users): Promise<Users> {
return this.ormRepository.save(user);
}
}
export default UsersRepository;
|
C++
|
UTF-8
| 1,884 | 3.84375 | 4 |
[] |
no_license
|
#include<stdio.h>
#include<stdlib.h>
struct Node{
int data;
struct Node* next;
};
struct Node* head;
void Insert(int data){
Node* newNode = new Node();
newNode->data = data;
newNode->next = NULL;
if(head == NULL){
head = newNode;
}
else{
Node* prevNode = head;
while(prevNode->next!=NULL){
prevNode = prevNode->next;
}
prevNode->next = newNode;
}
}
void InsertAt(int data,int n){
Node* newNode = new Node();
newNode->data = data;
newNode->next = NULL;
if(n == 1){
newNode->next = head;
head = newNode;
return;
}
else{
Node* prevNode = head;
for(int i=1;i<n-1;i++){
prevNode = prevNode->next;
}
newNode->next = prevNode->next;
prevNode->next = newNode;
}
}
void Delete(int n){
Node* temp1 = head;
if(n == 1){
head = temp1->next;
free(temp1);
return;
}
for(int i=1;i<n-1;i++){
temp1 = temp1->next;
}
Node* temp2 = temp1->next;
temp1->next = temp2->next;
free(temp2);
}
void print(){
Node* temp = head;
while(temp!=NULL){
printf("%d ",temp->data);
temp = temp->next;
}
printf("\n");
}
int main(){
head=NULL;
Insert(10);//10
print();
Insert(20);//10 20
print();
InsertAt(30,1);//30 10 20
print();
Insert(40);//30 10 20 40
print();
InsertAt(50,3);//30 10 50 20 40
print();
printf("head = %d\n",head);
int n;
printf("Enter a position: ");
scanf("%d",&n);
Delete(n);
Node* temp = head;
while(temp!=NULL){
printf("%d ",temp->data);
temp=temp->next;
}
}
|
C++
|
UTF-8
| 1,900 | 2.765625 | 3 |
[] |
no_license
|
#pragma once
#include <Windows.h>
#include <TlHelp32.h>
#include <string>
#include <comdef.h>
#include "PModule.hpp"
class Memory {
private:
HANDLE _process;
DWORD _pId;
public:
inline bool Attach(const char* pName, DWORD dwAccess) {
HANDLE handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);
PROCESSENTRY32 entry;
entry.dwSize = sizeof(entry);
do {
if (!strcmp(_bstr_t(entry.szExeFile), pName)) {
_pId = entry.th32ProcessID;
CloseHandle(handle);
_process = OpenProcess(dwAccess, false, _pId);
return true;
}
} while (Process32Next(handle, &entry));
return false;
}
inline PModule GetModule(const char* pModule) {
HANDLE module = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, _pId);
MODULEENTRY32 entry;
entry.dwSize = sizeof(entry);
do {
if (!strcmp(_bstr_t(entry.szModule), pModule)) {
CloseHandle(module);
return PModule{
reinterpret_cast<DWORD>(entry.hModule),
entry.modBaseSize
};
}
} while (Module32Next(module, &entry));
return PModule{ 0, 0 };
}
template<class T>
T Read(const DWORD dwAddress) {
T _read;
ReadProcessMemory(_process, LPVOID(dwAddress), &_read, sizeof(T), NULL);
return _read;
}
std::string ReadCharArray(const DWORD dwAddress) {
char _read[128];
ReadProcessMemory(_process, LPVOID(dwAddress), _read, sizeof(char[128]), NULL);
return std::string(_read);
}
template<class T>
void Write(const DWORD dwAddress, const T value) {
WriteProcessMemory(_process, LPVOID(dwAddress), &value, sizeof(T), NULL);
}
inline void CreateThread(uintptr_t address, LPVOID parameter = 0){
HANDLE hThread = CreateRemoteThread(_process, 0, 0, reinterpret_cast<LPTHREAD_START_ROUTINE>(address), parameter, 0, 0);
if (!hThread){
return;
}
WaitForSingleObject(hThread, 5000);
CloseHandle(hThread);
}
void Exit() {
CloseHandle(_process);
}
};
extern Memory mem;
|
Python
|
UTF-8
| 496 | 2.9375 | 3 |
[
"MIT"
] |
permissive
|
def dfs(G, S, stack, u):
if u in S: return
global cyc
S.add(u)
stack.add(u)
print(u)
for v in G[u]:
if cyc: return
if v in stack:
cyc = True
dfs(G, S, stack, v)
stack.discard(u)
cyc = False
G = {0: {1, 3}, 1:{}, 2:{0, 1}, 3:{2}}
S = set()
for u in G:
dfs(G, S, set(), u)
if cyc: print("ciclo!")
print()
cyc = False
G = {0: {1, 3}, 1:{}, 2:{0, 1}, 3:{1}}
S = set()
for u in G:
dfs(G, S, set(), u)
if cyc: print("ciclo!")
|
C++
|
UTF-8
| 4,958 | 4.0625 | 4 |
[] |
no_license
|
// Kellie Henderson, Dr_T, Unit 7 assignment
#include <iostream>
#include<string>
#include<sstream> //for overriding toString()
using namespace std;
//Declare the structs of Unit 7
struct timeOfDay
{
short Hour;
short Minute;
short Second;
};
struct appDate
{
short dayOfMonth;
short month;
int year;
};
struct event
{
string eventName;
timeOfDay eventTime;
appDate eventDate;
bool isUrgent;
//make a toString() member function for event
//giving event instructions for how to print itself
string toString()
{
short dayOfMonth = eventDate.dayOfMonth;
short month = eventDate.month;
int year = eventDate.year;
stringstream ss; //a custom style cout
ss << month << "/" << dayOfMonth << "/" << year;
string date = ss.str();
// build the time string
short hour = eventTime.Hour;
short minute = eventTime.Minute;
short second = eventTime.Second;
stringstream sst;
sst << hour << ":" << minute << ":" << second;
string time = sst.str();
return ("Date = " + date + "\nTime = " + time);
}
};
void createEvent(timeOfDay &t, appDate &d, event &e);
int main()
{
/********* PART ONE **************/
// date m/d/y time: h:m:s
timeOfDay t; //instance of the timeOfDay struct
t.Hour = 8;
t.Minute = 30;
t.Second = 22;
cout << "\nTime:" << endl;
cout << t.Hour << ":" << t.Minute << ":" << t.Second << endl;
appDate d;
d.dayOfMonth = 16;
d.month = 1;
d.year = 1988;
cout << "\nDate: " << endl;
cout << d.month << "/" << d.dayOfMonth << "/" << d.year << endl;
event e;
e.eventName = "My Date of Birth";
int decision = 0;
string status = "";
//determine if the event is urgent
cout << "\n Is the event, " << e.eventName << ", urgent (1 = yes, 2 = no): ";
cin >> decision; //ask for the input decision
if(decision == 1)
{
e.isUrgent = true; //yes an urgent event
status = "URGENT!";
}
else if(decision == 2)
{
e.isUrgent = false; //not an urgent evetn
status = "not urgent";
}
else
{
status = "error";
}
cout << "\nEvent Name: " << e.eventName << ", Status: " << status << endl;
//Populate the event e with a date and a time
e.eventDate = d; //put data into e.eventDate using an existing d instance
e.eventTime = t; //put data into e.eventTime using an existing t instance
//Print (reprint) the date and time of the event
//reprint the e date
cout << "\nEvent date: " << endl;
cout <<e.eventDate.month << "/"
<< e.eventDate.dayOfMonth << "/"
<< e.eventDate.year
<< endl;
//reprint the e time
cout << "\nEvent time: " << endl;
cout << e.eventTime.Hour << ":"
<< e.eventTime.Minute << ":"
<< e.eventTime.Second << endl;
//inspired by the excellent mind for Rafael How do I cout << e?
cout << e.toString();
/********************** PART TWO ***********************/
cout << "\nUnit 7, Part 2: Pass Event Objects by Reference &" << endl;
//declare instances of the STRUCT that we need for this work
event eMain;
timeOfDay tMain; //create a timeOfDay to share with eMain
appDate dMain; //create a appDate to share with eMain
//call a function here called void createEvent(timeOfDay t, appDate d, event e);
/*
pass tMain, dMain, and eMain by reference
ask for user input to populate tMain, dMain, with data
store these data in eMain
ask for and store the event name and urgency
print all the event details to screen.
*/
// createEvent(tMain, dMain, eMain); //function call
createEvent(tMain, dMain, eMain);
return 0;
}
void createEvent(timeOfDay &t, appDate &d, event &e)
{
short h = 0, m = 0, s = 0, mo = 0, day = 0;
int y = 0, decision = 0; string status = "";
string urgent = "", eName = "";
cout << "\nWelcome to our custom Event Creator " <<endl;
getline(cin,eName); //accept spaces for input
//populate time of day t
cout << "\nPlease enter an the hour, minute, and second: ";
cin >> h >> m >> s;
t = {h, m, s};
cout << "\n The time you entered is: " << h << ":" << m << ":"<< s << "." << endl;
//populate appDate d
cout << "\nPlease enter the Day, month and year of the event." << endl;
cin >> day >> mo >> y ;
d = {day, mo, y};
cout << "\n The event date is: " << day << "/" << mo << "/" << y << "." << endl;
//Set event details
//Populate the event name
cout << "\n Please enter the event name: " << endl;
cin >> eName;
//Populate the event urgency
cout << "\n Is the event, " << e.eventName << ", urgent (1 = yes, 2 = no): ";
cin >> decision; //ask for the input decision
status = (decision == 1) ? "Urgent!" : "Not Urgent" ;
cout << "\nThe event you are attending is: " << eName << "." << endl;
cout << "\nEVENT DETAILS --- " << endl;
cout << "Event Name: " << eName << endl;
cout << "\nStatus: " << status << endl;
e.eventDate = d;
e.eventTime = t;
cout << e.toString();
}
|
Ruby
|
UTF-8
| 1,216 | 2.625 | 3 |
[] |
no_license
|
class API::RouteTable
class << self
attr_accessor :table_items
def make(routes, descriptions)
@table_items = []
@descriptions = descriptions
routes.each do |route|
create_table_item(route, find_description(route))
end
end
def html
table_html = ""
@table_items.each { |item| table_html << item.to_table_row }
table_html
end
protected
def create_table_item(route, description)
@table_items << API::RouteTableItem.new(description.controller,
route.format,
route.method,
route.path,
description.description)
end
def find_description(route)
controller = route.controller.split('/').last
found_description = @descriptions.select do |description|
description.controller.eql?(controller) && description.action.eql?(route.action)
end.first
@descriptions.delete(found_description)
found_description || API::DescriptionHelpers::Description.new("No route description.", nil, controller)
end
end
end
|
JavaScript
|
UTF-8
| 1,306 | 3.1875 | 3 |
[] |
no_license
|
/**
* 枚举
*/
var Direction;
(function (Direction) {
Direction[Direction["Up"] = 1] = "Up";
Direction[Direction["Down"] = 2] = "Down";
Direction[Direction["Left"] = 3] = "Left";
Direction[Direction["Right"] = 4] = "Right";
})(Direction || (Direction = {}));
console.log(Direction.Up);
var Direction2;
(function (Direction2) {
Direction2[Direction2["Up"] = 0] = "Up";
Direction2[Direction2["Down"] = 1] = "Down";
Direction2[Direction2["Left"] = 2] = "Left";
Direction2[Direction2["Right"] = 3] = "Right";
})(Direction2 || (Direction2 = {}));
console.log(Direction2.Up);
console.log(Direction2[0]);
// 字符串枚举
console.log('***************');
var Direction3;
(function (Direction3) {
Direction3["Up"] = "Up";
Direction3["Down"] = "Down";
Direction3["Left"] = "Left";
Direction3["Right"] = "Right";
})(Direction3 || (Direction3 = {}));
console.log(Direction3.Up);
//运行时枚举
var E;
(function (E) {
E[E["X"] = 0] = "X";
E[E["Y"] = 1] = "Y";
E[E["Z"] = 2] = "Z";
})(E || (E = {}));
function f(obj) {
console.log(obj.X);
}
f(E);
console.log('********');
// 反向映射
var Enum;
(function (Enum) {
Enum[Enum["A"] = 0] = "A";
})(Enum || (Enum = {}));
var a = Enum.A;
console.log(a);
var nameOfA = Enum[a];
console.log(nameOfA);
|
Swift
|
UTF-8
| 6,542 | 2.53125 | 3 |
[
"LicenseRef-scancode-public-domain"
] |
permissive
|
//
// EarthquakeDetailController.swift
// Flatland
//
// Created by Stuart Rankin on 7/6/20.
// Copyright © 2020 Stuart Rankin. All rights reserved.
//
import Foundation
import AppKit
class EarthquakeDetailController: NSViewController, NSTableViewDelegate, NSTableViewDataSource
{
override func viewDidLoad()
{
super.viewDidLoad()
print("viewDidLoad")
}
@IBAction func HandleClosePressed(_ sender: Any)
{
let Window = self.view.window
let Parent = Window?.sheetParent
Parent?.endSheet(Window!, returnCode: .OK)
}
func DisplayEarthquake(_ Quake: Earthquake)
{
print("DisplayEarthquake")
QuakeSource = Quake
RelatedEarthquakeTable.reloadData()
PrimaryEarthquakeTable.reloadData()
}
var QuakeSource: Earthquake? = nil
func numberOfRows(in tableView: NSTableView) -> Int
{
switch tableView
{
case PrimaryEarthquakeTable:
if QuakeSource == nil
{
return 0
}
return 12
case RelatedEarthquakeTable:
if QuakeSource == nil
{
return 0
}
else
{
if let Related = QuakeSource?.Related
{
return Related.count
}
return 0
}
default:
return 0
}
}
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView?
{
var CellContents = ""
var CellIdentifier = ""
var CellToolTip: String? = nil
switch tableView
{
case PrimaryEarthquakeTable:
if tableColumn == tableView.tableColumns[0]
{
CellIdentifier = "QuakeAttributeColumn"
CellContents = ["Code", "Place", "Magnitude", "Time", "Location", "Depth", "Tsunami", "Status",
"Updated", "MMI", "Felt", "Significance"][row]
}
if tableColumn == tableView.tableColumns[1]
{
CellIdentifier = "QuakeValueColumn"
switch row
{
case 0:
CellContents = QuakeSource!.Code
case 1:
CellContents = QuakeSource!.Place
CellToolTip = QuakeSource!.Place
case 2:
CellContents = "\(QuakeSource!.Magnitude.RoundedTo(3))"
case 3:
CellContents = "\(QuakeSource!.Time)"
case 4:
CellContents = "\(QuakeSource!.Latitude.RoundedTo(3)), \(QuakeSource!.Longitude.RoundedTo(3))"
case 5:
CellContents = "\(QuakeSource!.Depth)"
case 6:
CellContents = QuakeSource!.Tsunami == 1 ? "Have data" : "No data"
case 7:
CellContents = QuakeSource!.Status
case 8:
let TimeAt1970 = Date().timeIntervalSince1970
if QuakeSource!.Updated.timeIntervalSince1970 > TimeAt1970
{
CellContents = "\(QuakeSource!.Updated)"
}
else
{
CellContents = ""
}
case 9:
CellContents = "\(QuakeSource!.MMI.RoundedTo(3))"
case 10:
CellContents = "\(QuakeSource!.Felt)"
case 11:
CellContents = "\(QuakeSource!.Significance)"
default:
return nil
}
}
case RelatedEarthquakeTable:
if tableColumn == tableView.tableColumns[0]
{
CellIdentifier = "CodeColumn"
CellContents = QuakeSource!.Related![row].Code
}
if tableColumn == tableView.tableColumns[1]
{
CellIdentifier = "MagnitudeColumn"
CellContents = "\(QuakeSource!.Related![row].Magnitude.RoundedTo(3))"
}
if tableColumn == tableView.tableColumns[2]
{
CellIdentifier = "DateColumn"
CellContents = "\(QuakeSource!.Related![row].Time)"
}
if tableColumn == tableView.tableColumns[3]
{
CellIdentifier = "CoordinateColumn"
let Crd = "\(QuakeSource!.Related![row].Latitude.RoundedTo(2)), \(QuakeSource!.Related![row].Longitude.RoundedTo(2))"
CellContents = Crd
CellToolTip = QuakeSource!.Place
}
if tableColumn == tableView.tableColumns[4]
{
CellIdentifier = "DistanceColumn"
let Distance = QuakeSource!.DistanceTo(QuakeSource!.Related![row]).RoundedTo(1)
CellContents = "\(Distance)"
}
default:
return nil
}
let Cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: CellIdentifier), owner: self) as? NSTableCellView
Cell?.textField?.stringValue = CellContents
if let ToolTip = CellToolTip
{
Cell?.toolTip = ToolTip
}
return Cell
}
@IBOutlet weak var RelatedEarthquakeTable: NSTableView!
@IBOutlet weak var PrimaryEarthquakeTable: NSTableView!
}
|
PHP
|
UTF-8
| 9,416 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace WebAction\Maghead;
use WebAction\Param\Param;
use WebAction\Param\ImageParam;
use WebAction\Param\FileParam;
use WebAction\Action;
use WebAction\RecordAction\BaseRecordAction;
use WebAction\RecordAction\CreateRecordAction;
use WebAction\RecordAction\UpdateRecordAction;
use WebAction\RecordAction\DeleteRecordAction;
use Maghead\Runtime\Model;
use Maghead\Runtime\Collection;
use Maghead\Schema\DeclareSchema;
use Maghead\Schema\Schema;
use Maghead\Schema\RuntimeColumn;
use Magsql\Raw;
use Exception;
/**
* Convert Maghead column to Action param,
* so that we can render with widget (currently).
*/
class ColumnConvert
{
public static $typeWidgets = [
'date' => 'DateInput',
'datetime' => 'DateTimeInput',
'text' => 'TextareaInput',
];
/**
* Convert a Maghead schema to action.
*
* This is used for generating an Action View without CRUD type.
*/
public static function convertSchemaToAction(Schema $schema, Model $record = null)
{
$action = new BaseRecordAction(array(), $record);
// no actual record is null
$action->resetParams();
$action->initParamsFromSchema($schema, $record);
return $action;
}
protected static function setupDefault(Param $p, RuntimeColumn $c)
{
if ($c->default) {
// do not use default value from the column if it's an instance of Raw
if ($c->default instanceof Raw) {
// let database put the default value by themself.
// TODO: parse fixed value here.
} else {
$p->default($c->default);
}
}
}
protected static function setupRequired(Param $p, RuntimeColumn $c, BaseRecordAction $a = null)
{
// Convert notNull to required
// required() is basically the same as notNull but provides extra
// software validation.
// When creating records, the primary key with auto-increment support is not required.
// However when updating records, the primary key is required for updating the existing record..
if ($c->notNull) {
if ($a) {
if ($c->primary) {
if ($a instanceof CreateRecordAction) {
// autoIncrement is not defined, then it requires the input value.
if ($c->autoIncrement) {
$p->required = false;
} else {
$p->required = true;
}
} else if ($a instanceof UpdateRecordAction || $a instanceof DeleteRecordAction) {
// primary key is required to update/delete records.
$p->required = true;
}
} else {
$p->required = true;
}
} else {
if (!$c->default && !($c->primary && $c->autoIncrement)) {
$p->required = true;
}
}
}
}
protected static function setupIsa(Param $p, RuntimeColumn $c)
{
if ($c->isa) {
$p->isa($c->isa);
}
}
private static function setupCurrentValue(Param $p, RuntimeColumn $c, Model $r = null)
{
// if we got record, load the value from it.
if ($r) {
// $val = $r->{$name};
// $val = $val instanceof Model ? $val->dataKeyValue() : $val;
$val = $r->getValue($c->name);
$p->setValue($val);
// XXX: should get default value (from column definition)
// default value is only used in create action.
} else {
$default = $c->getDefaultValue();
if (!$default instanceof Raw) {
$p->setValue($default);
}
}
}
private static function setupWidget(Param $p, RuntimeColumn $c)
{
if ($c->widgetClass) {
$p->widgetClass = $c->widgetClass;
}
if ($c->widgetAttributes) {
$p->widgetAttributes = $c->widgetAttributes;
} else {
$p->widgetAttributes = [];
}
if ($c->immutable) {
$p->widgetAttributes['readonly'] = 'readonly';
}
}
private static function setupWidgetType(Param $p, RuntimeColumn $c)
{
// When renderAs is specified, we should always use the widget name
if ($c->renderAs) {
$p->renderAs($c->renderAs);
} else {
self::setupWidgetTypeAuto($p, $c);
}
}
private static function setupWidgetTypeAuto(Param $p, RuntimeColumn $c)
{
if ($p->validValues || $p->validPairs || $p->optionValues) {
$p->renderAs('SelectInput');
} else if ($c->primary) {
// When it's a primary key field, then it should be hidden input if renderAs is not specified.
$p->renderAs('HiddenInput');
} else {
if (isset(static::$typeWidgets[ $p->type ])) {
$p->renderAs(static::$typeWidgets[$p->type]);
} else {
$p->renderAs('TextInput');
}
}
}
private static function setupValidValues(Param $p, RuntimeColumn $c)
{
// convert related collection model to validValues
if ($p->refer && ! $p->validValues) {
if (class_exists($p->refer, true)) {
$referClass = $p->refer;
// it's a `has many`-like relationship
if (is_subclass_of($referClass, Collection::class, true)) {
$collection = new $referClass;
$options = array();
foreach ($collection as $item) {
$label = method_exists($item, 'dataLabel')
? $item->dataLabel()
: $item->getKey();
$options[] = ["label" => $label, "value" => $item->dataKeyValue() ];
}
$p->validValues = $options;
} else if (is_subclass_of($referClass, Model::class, true)) {
// it's a `belongs-to`-like relationship
$class = $referClass . 'Collection';
$collection = new $class;
$options = array();
foreach ($collection as $item) {
$label = method_exists($item, 'dataLabel')
? $item->dataLabel()
: $item->getKey();
$options[] = [ "label" => $label, "value" => $item->dataKeyValue() ];
}
$p->validValues = $options;
} else if (is_subclass_of($referClass, DeclareSchema::class, true)
|| is_a($referClass, DeclareSchema::class, true))
{
$schema = new $referClass;
$collection = $schema->newCollection();
$options = [];
foreach ($collection as $item) {
$label = method_exists($item, 'dataLabel')
? $item->dataLabel()
: $item->getKey();
$options[] = ['label' => $label, 'value' => $item->dataKeyValue() ];
}
$p->validValues = $options;
} else {
throw new Exception('Unsupported refer type');
}
} else if ($relation = $record->getSchema()->getRelation($p->refer)) {
// so it's a relationship reference
// TODO: implement this
throw new Exception('Unsupported refer type');
}
}
}
public static function getParamClass(RuntimeColumn $c)
{
switch ($c->contentType) {
case "ImageFile":
return ImageParam::class;
case "File":
return FileParam::class;
}
return Param::class;
}
/**
* Translate Maghead RuntimeColumn to WebAction param object.
*
* @param RuntimeColumn $c
* @param Model $record presents the current values
* @return Param
*/
public static function toParam(RuntimeColumn $c, Action $action, Model $record = null)
{
$paramClass = self::getParamClass($c);
$p = new $paramClass($c->name, $action);
self::setupIsa($p, $c);
self::setupDefault($p, $c);
self::setupRequired($p, $c, $action);
foreach ($c->attributes as $k => $v) {
// skip some fields
if (in_array(strtolower($k), ['validator', 'default'])) {
continue;
}
if ($v instanceof Raw) {
continue;
}
$p->$k = $v;
}
self::setupCurrentValue($p, $c, $record);
self::setupValidValues($p, $c);
self::setupWidget($p, $c);
self::setupWidgetType($p, $c);
// Customized build process
if ($call = $c->buildParam) {
// if something is returned, replace the original param
if ($p2 = $call($p, $c)) {
$p = $p2;
}
}
return $p;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.