language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
C++
|
UTF-8
| 1,297 | 2.921875 | 3 |
[] |
no_license
|
// Written by Wouter Ensink
#include <catch2/catch_all.hpp>
#include <console_synth/sequencer/time_signature.h>
TEST_CASE ("time signature", "basic setup")
{
auto ts = TimeSignature { 4, 4, 4 };
REQUIRE (ts.getNumerator() == 4);
REQUIRE (ts.getDenominator() == 4);
REQUIRE (ts.getTicksPerQuarterNote() == 4);
SECTION ("init with different spec")
{
auto ts2 = TimeSignature { 5, 8, 16 };
REQUIRE (ts2.getNumerator() == 5);
REQUIRE (ts2.getDenominator() == 8);
REQUIRE (ts2.getTicksPerQuarterNote() == 16);
}
SECTION ("change numerator (valid)")
{
ts.setNumerator (8);
REQUIRE (ts.getNumerator() == 8);
}
SECTION ("change numerator (invalid)")
{
REQUIRE_THROWS_AS (ts.setNumerator (0), TimeSignature::InvalidNumeratorError);
}
SECTION ("change denominator (valid)")
{
ts.setDenominator (8);
REQUIRE (ts.getDenominator() == 8);
}
SECTION ("change denominator (invalid)")
{
REQUIRE_THROWS_AS (ts.setDenominator (0), TimeSignature::InvalidDenominatorError);
REQUIRE_THROWS_AS (ts.setDenominator (3), TimeSignature::InvalidDenominatorError);
REQUIRE_THROWS_AS (ts.setDenominator (1), TimeSignature::InvalidDenominatorError);
}
}
|
Python
|
UTF-8
| 161 | 4.21875 | 4 |
[] |
no_license
|
#This is a string to integer type casting
string = input("Enter a string to get converted into a integer:")
print("The input after typed cast is :"+int(string))
|
JavaScript
|
UTF-8
| 1,268 | 2.640625 | 3 |
[] |
no_license
|
// Displays the Kaminsky plot of the bytemap
function DotPlotPanel(parent) {
Globals.superConstructor(this, VisualPanel, [parent]);
this.name="DotPlot";
this.size.width = 512;
this.size.height = 512;
// create buffer
this.imageBuffer = BinVis.IMG_BUFFER_512;
this.contrastValue = 170;
this.redraw=1;
}
// Inheritance
Globals.inherits(DotPlotPanel, VisualPanel);
DotPlotPanel.prototype.update = function(diffTime) {
};
DotPlotPanel.prototype.invokeReset = function() {
};
DotPlotPanel.prototype.updateData = function() {
this.imageBuffer.clearBuffer();
if(FileBuffer.data){
var x,y,i;
var fb=FileBuffer.data;
i = BinVis.dataOffset;
for(y=0;y<512 && y+i<BinVis.dataLength;y++) {
for(x=0;x<512 && x+i<BinVis.dataLength;x++) {
if(fb[i+y] == fb[i+x])
this.imageBuffer.setPixel(x,y,0,255,0);
}
}
}
};
DotPlotPanel.prototype.render = function(ctx, diffTime) {
if(this.redraw>0){
this.imageBuffer.flush();
console.log("DOTPLOT REDRAW");
this.redraw--;
}
ctx.drawImage(this.imageBuffer.getCanvas(), 0,0,this.size.width,
this.size.height);
};
|
Markdown
|
UTF-8
| 4,114 | 3.171875 | 3 |
[] |
no_license
|
---
layout : post
title : React is a framework
date: 2016-11-16T08:45:12.000Z
categories: javascript node js react redux
comments: true
---
One of the more common phrases you hear anytime you talk about ReactJs is :
>React is not a framework, its a library
or
>React is just the "V" in "MVC"
This would have made sense when the React ecosystem was still in its early stages, but it doesn't hold true anymore. To clarify, nothing about React has fundamentally changed since it first released. What has changed, however, is what people think when they think of React.
When someone says "We have used React to build our web application", they almost never mean that React is _all_ they use (contrary to other frameworks like angular or ember). In fact, it's actually impossible to make a website *only* with React. This is because the only thing React (and I mean the actual React library) does, is provide a way to represent and update HTML as functions. To actually call and render those functions on a browser, you would need ReactDOM as well.
The term "React" is now used more to refer to an entire stack of libraries and frameworks rather than the React library alone. The obvious problem with this is, that different people have a different perception of what an ideal React stack is. For me personally, I have sometimes (wrongly) assumed that any website using React is _obviously_ using redux for state management as well.
Like it or not, the term "React" has now become synonymous with a framework consisting of isolated libraries that have come to support the functionality required in a full fledged framework. This is both a pain in backside, and a blessing in disguise.
On one hand, if you do not like a certain part of a framework, you normally have to go to great lengths and "go against the grain" to make it work your way. This is totally different in the case of the React "framework" :
- Don't like the JSX style routing in [react-router](https://github.com/ReactTraining/react-router) ? Just use [something else](https://github.com/larrymyers/react-mini-router)!
- Don't like the amount of boilerplate [redux](https://github.com/reactjs/redux) comes with? Use something like [jumpsuit](https://github.com/jumpsuit/jumpsuit) instead!
- Don't like [webpack](https://webpack.github.io/) to bundle your modules? Try [rollup](https://github.com/rollup/rollup) for a change. Or if you don't want to use bundles at all, you can still use react with plain old script tags.
The multitude of choices we have can give us a sense of relief... a sense of security that there are so many libraries out there that there has to be _atleast one_ that does what I want it to do. On the flip side, it can also make you feel like [this](https://hackernoon.com/how-it-feels-to-learn-javascript-in-2016-d3a717dd577f#.sg7kkylig) -- and that's precisely the problem. The amount of libraries out there creates a sort of [paradox of choice](https://en.wikipedia.org/wiki/The_Paradox_of_Choice), because of which we always feel that we could have chosen a better set of libraries to compose our framework. In fact, there are _so many_ choices of libraries out there, that there exists a [tool](http://andrewhfarmer.com/starter-project/) to help you search for the perfect boilerplate to suit your needs. We can even consider each boilerplate project to be its own framework because of the vastly different choices of libraries and convention seen between any two.
This kind of mental load of choosing the right boilerplate is rarely, if ever, present in other fully featured frameworks... but for some reason, I have always found myself complaining about atleast _some_ part of any of these that I use (After all, no one's perfect).
In the end, this post is not a rant about the current state of the React ecosystem, nor one about the lack of choice in other frameworks. It is simply a reflection on the direction the current React ecosystem is headed. React has not only changed the way we think about our code, but has also brought a whole ecosystem along with it, and that is always something to appreciate.
|
Markdown
|
UTF-8
| 2,258 | 3.234375 | 3 |
[
"MIT"
] |
permissive
|
## Deploying Faktory to Render.com
[Render](https://render.com) is a SaaS which makes it really easy to deploy custom
Docker-based services around the world with a few clicks.
[Faktory](/contribsys/faktory/wiki) is a
persistent background job system for any programming language. Let's get a Faktory
instance running for your app.
1. Sign in at Render.com.
2. On your Dashboard, select "New Private Service".
3. Paste in the URL for this repo:
https://github.com/contribsys/faktory-render and click the box that
appears.

4. Customize it:
- Enter a unique name for your Faktory server: "faktory", "foobar-faktory", etc.
- Select an appropriate region "near" your app.
- Notice you can set ENV variables or secrets files, useful for
FAKTORY_LICENSE if you upgrade to Faktory Pro or Enterprise.
- Change the value for FAKTORY_PASSWORD in Environment Variables.
- Select an appropriate instance size and create a persistent disk for
your data, mounted at /var/lib/faktory. See sizing notes below.
- Click "Create Private Service". You should have a live Faktory
instance in a minute. Both ports should be accessible to your app
running in Render.

### Resource Sizing
Faktory doesn't need much disk because queues are typically empty. Only
your error queue and scheduled queue will contain long-term data so I
recommend going small: 5-10GB should be plenty of space for most people.
Faktory uses Redis under the covers and all data must fit into RAM with
Redis. A small, test instance can run with 1GB. A light instance
processing less than 10m jobs/day can run with 2GB. For bigger users or users
using more data-heavy features like Batches, go with 4GB. Likewise, go
with 1, 2 or 4 CPUs based on your expected usage.
Remember we are spec'ing out the instance running Faktory **only**. It's your
worker instances that will actually execute jobs: that's where
you'll spend most of your resource budget.
### Limitations
Unfortunately private services are just that: private. You can't use a
Faktory service deployed to render.com with a generic app deployed in AWS
because there is no access to the service via public network.
If this changes, I will update this section with details.
|
JavaScript
|
UTF-8
| 372 | 2.734375 | 3 |
[] |
no_license
|
// Do nothing. Might be useful to see how other bots perform without interruption. o_O
(function() {
var bot = {name: 'doNothing', icon:'bot', cb: function() { return [] }};
setTimeout(function registerArmy() {
window.registerArmy({
name: bot.name,
icon: bot.icon,
cb: bot.cb
});
}, 2000);
})();
|
Python
|
UTF-8
| 1,850 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/bin/env python3
import gym
from griddly import GymWrapper, gd
from griddly.RenderTools import VideoRecorder
import matplotlib.pyplot as plt
def test_griddly():
env = gym.make('GDY-Labyrinth-v0')
env.reset()
for s in range(10):
obs, reward, done, info = env.step(env.action_space.sample())
if done:
env.reset()
def test_custom_env():
env = GymWrapper(yaml_file='simple_zelda.yaml', level=0,
global_observer_type=gd.ObserverType.SPRITE_2D, player_observer_type=gd.ObserverType.SPRITE_2D)
env.reset()
for s in range(1000):
#obs, reward, done, info = env.step(env.action_space.sample())
env.render()
# if done:
# env.reset()
def test_zelda_env():
env = GymWrapper(yaml_file='simple_zelda.yaml')
env.reset()
total_reward = 0
for s in range(100):
action = env.action_space.sample()
obs, reward, done, info = env.step(action)
total_reward = total_reward + reward
if done:
env.reset()
print(total_reward)
return total_reward
def test_video():
video_recorder = VideoRecorder()
env = GymWrapper(yaml_file='simple_zelda.yaml')
env.reset()
obs = env.render()
video_recorder.start("video/random_agent.mp4", obs.shape)
total_reward = 0
for s in range(500):
action = env.action_space.sample()
obs, reward, done, info = env.step(action)
total_reward = reward + total_reward
image = env.render()
video_recorder.add_frame(image)
if done:
env.reset()
print(total_reward)
video_recorder.close()
#test_custom_env()
#test_video()
# results = []
# for i in range(200):
# results.append(test_zelda_env())
# print(sum(results)/200)
# plt.plot(results)
# plt.show()
test_custom_env()
|
PHP
|
UTF-8
| 929 | 2.625 | 3 |
[] |
no_license
|
<?php
namespace Ekapusta\DoctrineCustomTypesBundle\ORM\Query\AST\Functions\Postgresql;
use Doctrine\ORM\Query\Lexer;
use Doctrine\ORM\Query\Parser;
use Doctrine\ORM\Query\SqlWalker;
abstract class TwoArgsStringFunctionNode extends PostgresFunctionNode
{
public $arg1;
public $arg2;
public static function getReturnType()
{
return self::RETURN_TYPE_STRING;
}
public function getSql(SqlWalker $sqlWalker)
{
return sprintf('%s(%s, %s)', $this->getName(), $this->arg1->dispatch($sqlWalker), $this->arg2->dispatch($sqlWalker));
}
public function parse(Parser $parser)
{
$parser->match(Lexer::T_IDENTIFIER);
$parser->match(Lexer::T_OPEN_PARENTHESIS);
$this->arg1 = $parser->ArithmeticPrimary();
$parser->match(Lexer::T_COMMA);
$this->arg2 = $parser->ArithmeticPrimary();
$parser->match(Lexer::T_CLOSE_PARENTHESIS);
}
}
|
JavaScript
|
UTF-8
| 1,334 | 4.125 | 4 |
[] |
no_license
|
//template string
var x=5;
console.log(`the value of a is =${x}`);
//class
class ArithmaticOperators {
constructor(a,b,name) {
this.input1=a;
this.input2=b;
this.operation = name;
}
getSum() {
return `the sum is ${this.input1 + this.input2}`;
}
getSub() {
return `the sub is ${this.input1 - this.input2}`;
}
}
var object = new ArithmaticOperators(10,10,"chandini");
console.log(object.getSum());
//object literals
function studentDetails(name,number) {
return {
name,
number
}
}
let studentObj1 = new studentDetails("chandini",12);
console.log(studentObj1.name);
let studentObj2 = new studentDetails("chitra",12);
console.log(studentObj2.number);
//method in objects
function getstudentDetails(name,age,job) {
return {
getName() {
return `student name:${name}`;
},
getAge() {
return `student age:${age}`;
},
getJob() {
return `student job:${job}`;
}
}
}
let obj = getstudentDetails("chandini",12,"developer").getName();
console.log(obj);
//destucturing
let collegeDetails = {
sName:"BWEC",
branch:"cse",
id:"y16cs2612"
};
let {sName,id} = collegeDetails;
console.log(sName,id);
let {sName:s,branch:y} = collegeDetails;
console.log(s,y);
|
Markdown
|
UTF-8
| 3,422 | 3.21875 | 3 |
[] |
no_license
|
```
exports.handler = async event => {
if (!event.user || !event.user.info) {
return {
statusCode: 400,
body: JSON.stringify({ message: "Missing input" })
};
}
const user = {
name: event.user.info.name,
email: event.user.info.email,
password: event.user.info.password
};
if (!user.name) {
return {
statusCode: 400,
body: JSON.stringify({ message: "Missing name" })
};
}
if (!user.email) {
return {
statusCode: 400,
body: JSON.stringify({ message: "Missing email" })
};
}
if (!user.password || user.password.length < 6) {
return {
statusCode: 400,
body: JSON.stringify({ message: "Invalid password" })
};
}
return {
statusCode: 200,
body: JSON.stringify({
message: "User is correct"
})
};
};
```
________________________________________________________________________________________________
# b. Qual o retorno da função se ela receber um objeto vazio de entrada?
{ message: "Missing input" }
________________________________________________________________________________________________
________________________________________________________________________________________________
# c. Qual o retorno da função se ela receber este objeto como entrada:
{
"user": {
"name": "Astrodev"
}
}
{ message: "Missing input" }
________________________________________________________________________________________________
________________________________________________________________________________________________
# d. Qual o retorno da função se ela receber este objeto como entrada:
let exercicio1_d = {
"user": {
"info": {
"name": "Astrodev"
}
}
}
{ message: "Missing email" }
________________________________________________________________________________________________
________________________________________________________________________________________________
# e. Qual o retorno da função se ela receber este objeto como entrada:
{
"user": {
"info": {
"name": "Astrodev",
"email": "astrodev@f4.com.br",
"password": "12345"
}
}
}
{ message: "Invalid password" }
________________________________________________________________________________________________
________________________________________________________________________________________________
# f. Qual o retorno da função se ela receber este objeto como entrada:
{
"user": {
"info": {
"name": "Astrodev",
"email": "astrodev@f4.com.br",
"password": "123456"
}
}
}
{message: "User is correct"}
________________________________________________________________________________________________
# g. Onde devemos alterar para que a função retorne o status `422` caso o email seja inválido?
```
if (!user.email) {
return {
statusCode: 422,
body: JSON.stringify({ message: "Missing email" })
};
}
```
# h. Qual deve ser o objeto de entrada para que a função retorne o status `200`?
```
{
"user": {
"info": {
"name": "Astrodev",
"email": "astrodev@f4.com.br",
"password": "123456"
}
}
}
```
|
Markdown
|
UTF-8
| 5,163 | 2.65625 | 3 |
[] |
no_license
|
---
description: "Simple Way to Make Perfect Stir Fry Veggies"
title: "Simple Way to Make Perfect Stir Fry Veggies"
slug: 1580-simple-way-to-make-perfect-stir-fry-veggies
date: 2020-08-30T10:01:01.591Z
image: https://img-global.cpcdn.com/recipes/00c9c967d040184e/751x532cq70/stir-fry-veggies-recipe-main-photo.jpg
thumbnail: https://img-global.cpcdn.com/recipes/00c9c967d040184e/751x532cq70/stir-fry-veggies-recipe-main-photo.jpg
cover: https://img-global.cpcdn.com/recipes/00c9c967d040184e/751x532cq70/stir-fry-veggies-recipe-main-photo.jpg
author: Jonathan Flowers
ratingvalue: 3.2
reviewcount: 6
recipeingredient:
- "1 capsicum"
- "1/4 cabbage"
- "1 Onion"
- "1/4 Red bell pepper"
- "1/4 Yellow bell pepper"
- "10-12 French beans"
- "10-12 Flowers of blanched Broccoli"
- "1 inch Ginger"
- "2 green chillies"
- "200 gm Paneer"
- "1 tsp black pepper powder"
- "1 tsp chilli flakes"
- "1 tsp oregano"
- "To taste Salt"
- "2 tsp Olive oil"
- "1 orange carrot"
- "2-3 garlic cloves"
recipeinstructions:
- "Chop all the vegetables as per your likes."
- "Heat olive oil in a pan"
- "Add chopped ginger garlic and green chillies."
- "Then add onion and sauté it for a min on high flame."
- "Then add carrot beans and stir for a min."
- "Add all the veggies and sauté it for a min on high flame."
- "Add Paneer and all the spices and stir."
- "You can cook it in butter too or can add butter to it for better taste."
- "You can add sauces also."
categories:
- Recipe
tags:
- stir
- fry
- veggies
katakunci: stir fry veggies
nutrition: 187 calories
recipecuisine: American
preptime: "PT37M"
cooktime: "PT50M"
recipeyield: "1"
recipecategory: Lunch
---
<br>
Hey everyone, welcome to my recipe site, If you're looking for recipes idea to cook today, look no further! We provide you only the perfect Stir Fry Veggies recipe here. We also have wide variety of recipes to try.
<br>

<i>Before you jump to Stir Fry Veggies recipe, you may want to read this short interesting healthy tips about <strong>Easy Ways to Get Healthy</strong>.</i>
Every person knows that in order to truly be healthy you need to eat a nutritious and balanced diet and get a proper workout regularly. The worst part is that, at the end of the day, we don't always have the time or energy required for a healthy lifestyle. At the conclusion of the day, most of us want to go home, not to the gym. We want a delicious, greasy burger, not an equally tasty salad (unless we’re vegetarians). You will be delighted to discover that achieving good health doesn't have to be hard. With practice you can get all of the nutrients and the physical exercise that you need. Here are some hints to be as healthy as possible.
Drink water, not other beverages. Having a soda or a cup of coffee every once in a while isn’t a terrible idea. Using them for your only source of hydration, on the other hand, is dumb. Choosing water as an alternative to other beverage adds to your body's health and helps it stay hydrated. You’re also cutting hundreds of calories out of your diet— without having to deal with terrible tasting diet food. Water is typically one of the keys to really slimming down and leading a healthful lifestyle.
There are all sorts of activities that you can do to get wholesome. An expensive gym membership and very restrictive diets are not the only way to do it. Little things, when done every single day, can do plenty to help you get healthy and lose pounds. Being clever when you choose your food and actions is where it begins. A suitable amount of physical activity each day is also necessary. Don't overlook that health isn't only about just how much you weigh. You want your body to be powerful too.
<i>We hope you got insight from reading it, now let's go back to stir fry veggies recipe. To cook stir fry veggies you need <strong>17</strong> ingredients and <strong>9</strong> steps. Here is how you achieve that.
</i>
##### The ingredients needed to prepare Stir Fry Veggies:
1. Take 1 capsicum
1. Get 1/4 cabbage
1. Prepare 1 Onion
1. Take 1/4 Red bell pepper
1. Prepare 1/4 Yellow bell pepper
1. Get 10-12 French beans
1. Get 10-12 Flowers of blanched Broccoli
1. Get 1 inch Ginger
1. Take 2 green chillies
1. You need 200 gm Paneer
1. Prepare 1 tsp black pepper powder
1. Provide 1 tsp chilli flakes
1. Provide 1 tsp oregano
1. Provide To taste Salt
1. Prepare 2 tsp Olive oil
1. You need 1 orange carrot
1. Provide 2-3 garlic cloves
##### Instructions to make Stir Fry Veggies:
1. Chop all the vegetables as per your likes.
1. Heat olive oil in a pan
1. Add chopped ginger garlic and green chillies.
1. Then add onion and sauté it for a min on high flame.
1. Then add carrot beans and stir for a min.
1. Add all the veggies and sauté it for a min on high flame.
1. Add Paneer and all the spices and stir.
1. You can cook it in butter too or can add butter to it for better taste.
1. You can add sauces also.
<i>If you find this Stir Fry Veggies recipe useful please share it to your good friends or family, thank you and good luck.</i>
|
Ruby
|
UTF-8
| 2,299 | 3.34375 | 3 |
[] |
no_license
|
require './lib/enigma'
require './lib/key_generator'
require 'Date'
require 'minitest/autorun'
require 'minitest/pride'
class EnigmaTest < Minitest::Test
def test_total_shift
# binding.pry
e = Enigma.new
key = 41521
a = 49
b = 18
c = 54
d = 25
expected = [a, b, c, d]
output = e.total_shift(key)
assert_equal expected, output
end
def test_encrpyt_one_letter
e = Enigma.new
output = e.encrypt('b', 41521, 150518)
expected = e.char_map[50] # (1 + 41 + 8) % 85
assert_equal expected, output
end
def test_encrypt_four_letters
e = Enigma.new
# total shift is first and second digits of key plus offset.
output = e.encrypt('bird', 41521, 150518)
expected = 'YA(C'
assert_equal expected, output
end
def test_encrypt_words_longer_than_four
e = Enigma.new
output = e.encrypt('birdbird', 41521, 150518) # 'bird' encrpyted is 'YA(C'
expected = 'YA(CYA(C'
assert_equal expected, output
end
def test_encrypt_numbers_and_characters
e = Enigma.new
output = e.encrypt('9/?', 41521, 150518)
expected = 'zoZ' # calculated by hand
assert_equal expected, output
end
def test_decrypt_with_known_ciphertext_known_key
e = Enigma.new
key = 41521
original_message = 'bird'
ciphertext = 'YA(C'
decrypted_text = e.decrypt(ciphertext, key)
assert_equal original_message, decrypted_text
end
def test_encrypt_decrypt_with_random_key
e = Enigma.new
key = e.keygen.key
original_message = 'this 1s 5o secret? ..end..'
ciphertext = e.encrypt(original_message, key)
decrypted_text = e.decrypt(ciphertext, key)
assert_equal original_message, decrypted_text
end
def test_cipher_shifts_known_plaintext
e = Enigma.new
plaintext = 'bird'
shift = [49, 18, 54, 25] # using key 41521 and date 150518
expected_ciphertext = 'YA(C'
ciphertext = e.cipher(plaintext, shift, 1)
assert_equal expected_ciphertext, ciphertext
end
def test_cipher_shifts_known_ciphertext
e = Enigma.new
expected_plaintext = 'bird'
shift = [49, 18, 54, 25] # using key 41521 and date 150518
known_ciphertext = 'YA(C'
ciphertext = e.cipher(known_ciphertext, shift, -1)
assert_equal expected_plaintext, ciphertext
end
end
|
JavaScript
|
UTF-8
| 831 | 2.96875 | 3 |
[] |
no_license
|
import { hasRoute } from "../4.1 - Route Between Nodes";
import { buildBinaryTree } from "../../Data Structures/BinaryTree";
import { range } from "lodash";
test("Route Between Nodes", () => {
const tree = buildBinaryTree(range(10));
const startNode = tree.left;
const endNode = tree.left.left.right;
const otherNode = tree.right.right;
expect(hasRoute(startNode, endNode)).toBe(true);
expect(hasRoute(startNode, otherNode)).toBe(false);
});
test("Route Between Nodes - Cycle Exists", () => {
const tree = buildBinaryTree(range(30));
const startNode = tree;
const endNode = tree.right.left;
expect(hasRoute(startNode, endNode)).toBe(true);
// add a cycle that prevents the left side from being seen
tree.left = tree;
tree.children[0] = tree;
expect(hasRoute(startNode, endNode)).toBe(false);
});
|
Python
|
UTF-8
| 2,231 | 3.578125 | 4 |
[] |
no_license
|
#Importing libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#Importing dataset with pandas
dataset = pd.read_csv('Mall_Customers.csv')
X= dataset.iloc[:,[3,4]].values
#using the elbow method to find exact number of clusters
from sklearn.cluster import KMeans
#so as to plot the graph, we are going to compute wing cluster sum of squares for 10 different numbers.So we are going to write a for loop to write 10 different cluster sum of squares for the 10 number of clusters
wcss=[]
for i in range(1,11):
#in each iteraion we are doing 2 things:
#fit the KMeans to dataset
#compute the within clusrers sum of squares and append to wcss list
#max_iter: maximum no of iterations that can be defined to final clusters, when k-means algo is running.
#n_init: max no of centroids our Kmeans will run
kmeans= KMeans(n_clusters=i, init="k-means++", max_iter=300, n_init=10,random_state=0)
kmeans.fit(X)
#WCSS: Within Clusters Sum of Squares
wcss.append(kmeans.inertia_)
plt.plot(range(1,11),wcss)
plt.title("Elbow Show Method")
plt.xlabel("No of Clusters")
plt.ylabel("WCSS: Inertia")
plt.show()
#Applying KMeans to Mall Dataset
kmeans= KMeans(n_clusters=5, init="k-means++", max_iter=300, n_init=10,random_state=0)
#instead of fit() we use fit_predict() which returns to which cluster the these points belong to. It will return cluster number into a vector which we call y_kmeans
y_kmeans= kmeans.fit_predict(X)
#Visualising The Clusters
plt.scatter(X[y_kmeans==0,0], X[y_kmeans==0,1],s=100, c='red',label="Careful")
plt.scatter(X[y_kmeans==1,0], X[y_kmeans==1,1],s=100, c='green',label="Standard")
plt.scatter(X[y_kmeans==2,0], X[y_kmeans==2,1],s=100, c='blue',label="Target")
plt.scatter(X[y_kmeans==3,0], X[y_kmeans==3,1],s=100, c='yellow',label="Careless")
plt.scatter(X[y_kmeans==4,0], X[y_kmeans==4,1],s=100, c='orange',label="Sensible")
plt.scatter(kmeans.cluster_centers_[:,0],kmeans.cluster_centers_[:,1],s=300,c='magenta', label="Cluster Centroids")
plt.title("Cluster of Clients")
plt.xlabel("Annual Income in Dollars")
plt.ylabel('Spending Score(1-100)')
plt.legend()
plt.show()
|
C++
|
UTF-8
| 505 | 2.734375 | 3 |
[] |
no_license
|
#include <iostream>
#include <string>
using namespace std;
int G[6][6];
int main ()
{
int m, a, b;
cin >> m;
while (m--)
{
cin >> a >> b;
G[a][b] = G[b][a] = 1;
}
int ts = 0;
for (int x=1; x<=5; ++x)
for (int y=1; y<=5; ++y)
for (int z=1; z<=5; ++z)
{
if (x==y || x==z || y==z)
continue;
int cnt = G[x][y] + G[x][z] + G[y][z];
ts += cnt==0 || cnt == 3;
}
cout << ( ts>0 ? "WIN" : "FAIL") << endl;
return 0;
}
|
Python
|
UTF-8
| 623 | 2.6875 | 3 |
[] |
no_license
|
import json
from flask import Response
from .codes import WEBCodes
class AbstractHTTPResult:
def __init__(
self, data: dict, msg: str,
http_code: int = 200, status: int = WEBCodes.OK
):
self.http_code = http_code
self.data = data
self.msg = msg
self.status = status
@property
def result(self):
result_data = {"status": self.status,
"data": self.data, "msg": self.msg}
json_res = json.dumps(result_data)
return Response(json_res, status=self.http_code,
mimetype="application/json")
|
Python
|
UTF-8
| 10,945 | 2.546875 | 3 |
[] |
no_license
|
# ----------------------------------------------------------------------
# --- rxtx.py ---
# ----------------------------------------------------------------------
# --- High level static functions to deal with RX, TX and also ---
# --- generation and execution of received actions ---
# ----------------------------------------------------------------------
# --- Author: Jaime Martin Soler ---
# --- Date : 2016-10-25 ---
# ----------------------------------------------------------------------
# ----------------------------------------------------------------------
# IMPORTS
import RPi.GPIO as GPIO
from lib_nrf24 import NRF24
import spidev
import time
import sqlite3
from log import LOG, LOG_DEB, LOG_DET, LOG_INF, LOG_WAR, LOG_ERR, LOG_CRS, LOG_OFF
from action import *
from glob import *
from DBmanager import *
from actionManager import *
# ----------------------------------------------------------------------
# PARAMETERS
# NRF24L01
PAYLOAD_MAX_SIZE = 32 # defined by NRF24 datasheet
PAYLOAD_ACK_MAX_SIZE = 32 # defined by NRF24 datasheet
# ----------------------------------------------------------------------
# FUNCTIONS
# -------------------------------------
# setup_NRF24(NRF24)
def setup_GPIO():
# GPIO as BCM mode as per lib_nrf24 requires
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
# -------------------------------------
# setup_NRF24(NRF24)
def setup_NRF24(radio):
# parameters: NRF24L01 communication
pipes = [[0xE8, 0xE8, 0xF0, 0xF0, 0xE1], [0xF0, 0xF0, 0xF0, 0xF0, 0xE1]]
PIPE_R = 1
PIPE_W = 0
# parameters: NRF24L01 pins (CE) and spidev file
SPIDEV_FILE = 0
PIN_CE_BCM = 17
# NRF24L01 begin
radio.begin(SPIDEV_FILE, PIN_CE_BCM)
# message and ACK
radio.setPayloadSize(PAYLOAD_MAX_SIZE)
radio.enableDynamicPayloads() # instead of: radio.setPayloadSize(int)
radio.setAutoAck(True)
radio.enableAckPayload()
radio.setRetries(1,15); # min ms between retries, max number of retries
# channel and pipes
radio.setChannel(0x76)
radio.openReadingPipe(1, pipes[PIPE_R])
radio.openWritingPipe(pipes[PIPE_W])
# rate, power
radio.setDataRate(NRF24.BR_1MBPS) # with NRF24.BR_250KBPS <10% success..., NRF24.BR_1MBPS OK
radio.setPALevel(NRF24.PA_HIGH)
# print details
radio.printDetails()
# -------------------------------------
# intArrayToString(intArray)
# this is used after radio.read(), which returns an array of integer representing a string
def intArrayToString(intArray = []):
s = ''
for i in intArray:
s += chr(i)
return s
# -------------------------------------
# Function stringToIntArray(s,size)
# used to ease the process of radio.write(), which better requires an array of integers
def stringToIntArray(s,size=PAYLOAD_ACK_MAX_SIZE):
charArray = list(s)
arrayLen = len(charArray)
intArray = [None] * arrayLen
for idx in range(arrayLen):
intArray[idx] = ord(charArray[idx])
if (size < arrayLen):
return intArray[0:size]
elif (size > arrayLen):
return intArray + ([0]*(size-arrayLen))
return intArray
# -------------------------------------
# rx(NRF24, rxLoop=False)
# This is the main funcion and is meant to be executed as a thread
# Receives and manages a radio message, creating and executing the necessary Actions
# return: True(rx success), False(rx failed)
def rx(rxLoop=True):
# parameters DBconn, DBcursor, radio
DBconn = sqlite3.connect(DB_FILE_NAME_FULL)
DBcursor = DBconn.cursor()
radio = NRF24(GPIO, spidev.SpiDev())
# setup DBconn, DBcursor, GPIO
setup_GPIO()
setup_NRF24(radio)
DBsetup(DBconn, DBcursor)
# rx loop (if !rxLoop it breaks at the bottom)
while (STATUS.get("isAlive")):
# RX start listening TX
radio.startListening();
# RX loop: wait for a message
LOG(LOG_INF, " RX waiting message...");
while (not radio.available()):
# Check STATUS.get("isAlive")
if (not STATUS.get("isAlive")):
return False
# Check Normal Action to be transmitted, managed from manageNormalAction thread
if (txNormalAction.txReadyToTx and txNormalAction.txSuccess<=0):
tx(radio,txNormalAction) # startListeningAuto=True by default
# Check Twitter Action to be transmitted, managed from twitterManagerLoop thread
elif (txTwitterAction.txReadyToTx and txTwitterAction.txSuccess<=0):
tx(radio,txTwitterAction) # startListeningAuto=True by default
# delay
time.sleep(0.010)
# ACK_TX payload before RX
# issue!!!: ACK payload is getting delayed by 1 (ACK_RX[i]=ACK_TX[i-1]), but this does not affect to a normal ACK
strAckTx = 'ACK to Temp from RPi'
intAckTx = stringToIntArray(strAckTx)
radio.writeAckPayload(1, intAckTx, len(intAckTx))
# RX the message (cleaning non-printable characters and the whitespace)
intMsgRx = []
radio.read(intMsgRx, radio.getDynamicPayloadSize())
strMsgRx = intArrayToString(intMsgRx)
strMsgRx = ''.join([c for c in strMsgRx if ord(c) >= ASCII_PRINT_MIN and ord(c) <= ASCII_PRINT_MAX])
LOG(LOG_INF, "RX: \"{}\"".format(strMsgRx))
LOG(LOG_INF, " ACK_TX_payload: \"{}\"".format(strAckTx))
# Action: create and manage actions
rxAction.set(text=strMsgRx)
if (rxAction.getRxBoardId()==BOARD_ID):
rxType = rxAction.getType()
# rxNormalAction
if (rxType==TYPE_NORMAL_L or rxType==TYPE_NORMAL_S):
rxNormalAction.set(copy=rxAction)
rxNormalAction.rxReadyToExec = True
execute(radio,rxNormalAction, DBconn, DBcursor)
# rxTwitterAction
elif (rxType==TYPE_TWITTER_L or rxType==TYPE_TWITTER_S):
rxTwitterAction.set(copy=rxAction)
rxTwitterAction.rxReadyToExec = True
execute(radio,rxTwitterAction, DBconn, DBcursor)
# rxArduinoAction
elif (rxType==TYPE_ARDUINO_L or rxType==TYPE_ARDUINO_S):
rxArduinoAction.set(copy=rxAction)
rxArduinoAction.rxReadyToExec = True
execute(radio,rxArduinoAction, DBconn, DBcursor)
else:
LOG(LOG_WAR,"<<< WARNING: RX Action mode unknown: \"{}\" >>>".format(rxType))
# keep/breake infinite loop
if (not rxLoop):
return True
# if RX loop is broken, return false
return False;
# -------------------------------------
# tx(NRF24, Action)
# Transmit the passed Action
# return: true(ACK_RX), false(NO_ACK_RX)
def tx(radio, action, startListeningAuto=True):
# check if action is validated
if (not action.validated):
LOG(LOG_WAR, "<<< WARNING: Action \"{}\" NOT TX, Action NOT Validated >>>".format(action.text))
return False
# wait a bit for the receiver to get ready for RX mode, just in case
time.sleep(0.020)
# TX stop listening RX
radio.stopListening();
# TX message
intMsgTx = stringToIntArray(action.text)
LOG(LOG_INF, "TX: \"{}\"".format(action.text), logPreLn=True)
# No ACK received, return False:
action.txAttempts += 1
if(radio.write(intMsgTx) == 0):
LOG(LOG_WAR, "<<< WARNING: ACK_RX: NOT received >>>")
if (startListeningAuto):
radio.startListening()
return False
# ACK_RX, return True:
# issue!!!: when a row of msg is read, after TX stops, RX keeps reading ACKs for 2-3 times
else:
action.txSuccess += 1
# ACK_RX (ACK payload OK):
# issue!!!: ACK payload is getting delayed by 1 (ACK_RX[i]=ACK_TX[i-1]), but this does not affect to a normal ACK
if (radio.isAckPayloadAvailable()):
intAckRx = []
radio.read(intAckRx, radio.getDynamicPayloadSize())
strAckRx = intArrayToString(intAckRx)
LOG(LOG_INF, " ACK_RX: YES (payload=\"{}\")".format(strAckRx))
# ACK_RX (ACK payload <empty>):
else:
LOG(LOG_INF, " ACK_RX: YES (ack_payload=<empty>)")
# return True
if (startListeningAuto):
radio.startListening()
return True
# -------------------------------------
# execute(NRF24,Action)
# Execute and Action, both received and meant to be transmitted
# return: true(exec success), false(exec failed)
def execute(radio, action, DBconn, DBcursor):
LOG(LOG_INF, " Action to execute: \"{}\"".format(action.text));
# check action.validated
if (not action.validated):
LOG(LOG_WAR, "<<< WARNING: Action \"{}\" NOT executed, Action NOT Validated >>>".format(action.text))
return False
# check action.rxReadyToExec
if (not action.rxReadyToExec):
LOG(LOG_WAR, "<<< WARNING: Action \"{}\" NOT executed, Action NOT Ready to Exec >>>".format(action.text))
return False
# get parameters
id = action.getId()
txBoardId = action.getTxBoardId()
rxBoardId = action.getRxBoardId()
type = action.getType()
type_L = action.getType_L()
func = action.getFunc()
paramNum = action.getParamNum()
wpar = action.getWpar()
wparId = action.getWparId()
value = action.getValue()
value2 = action.getValue2()
# log parameters
LOG(LOG_DET, " ID: \"{}\"".format(id));
LOG(LOG_DET, " txBoardId: \"{}\"".format(txBoardId))
LOG(LOG_DET, " rxBoardId: \"{}\"".format(rxBoardId))
LOG(LOG_DET, " type: \"{}\"".format(type))
LOG(LOG_DET, " function: \"{}\"".format(func))
LOG(LOG_DET, " paramNum: {}".format(paramNum))
LOG(LOG_DET, " weather param: \"{}\"".format(wpar))
LOG(LOG_DET, " weather param id: \"{}\"".format(wparId))
LOG(LOG_DET, " value: \"{}\"".format(value))
LOG(LOG_DET, " value2: \"{}\"".format(value2))
# BOARD_ID = RX
if (rxBoardId==BOARD_ID):
# FUNC = SET
if (func==FUNC_SET_L or func==FUNC_SET_S):
# PARAM NUM = 3
if (paramNum>=3):
# WPAR = TEMP
if (wpar==WPAR_TEMP_L or wpar==WPAR_TEMP_S):
# WPARID = LM35
if (wparId==WPARID_TEMP_LM35_L or wparId==WPARID_TEMP_LM35_S):
DBweatherInsert(DBconn, DBcursor, type_L, WPAR_TEMP_L, WPARID_TEMP_LM35_L, valueReal=float(value))
action.rxExec += 1
return True
# WPARID = DHT (for WPAR = TEMP)
elif (wparId==WPARID_TEMP_DHT_L or wparId==WPARID_TEMP_DHT_S):
DBweatherInsert(DBconn, DBcursor, type_L, WPAR_TEMP_L, WPARID_TEMP_DHT_L, valueReal=float(value))
action.rxExec += 1
return True
# WPAR = HUMI
elif (wpar==WPAR_HUMI_L or wpar==WPAR_HUMI_S):
# WPARID = DHT (for WPAR = HUMI)
if (wparId==WPARID_HUMI_DHT_L or wparId==WPARID_HUMI_DHT_S):
DBweatherInsert(DBconn, DBcursor, type_L, WPAR_HUMI_L, WPARID_HUMI_DHT_L, valueReal=float(value))
action.rxExec += 1
return True
# WPAR = RAIN
elif (wpar==WPAR_RAIN_L or wpar==WPAR_RAIN_S):
# WPARID = MH
if (wparId==WPARID_RAIN_MH_L or wparId==WPARID_RAIN_MH_S):
DBweatherInsert(DBconn, DBcursor, type_L, WPAR_RAIN_L, WPARID_RAIN_MH_L, valueReal=float(value))
action.rxExec += 1
return True
# BOARD_ID = TX
elif (txBoardId==BOARD_ID):
if (action.txReadyToTx and action.txSuccess<=0):
tx(radio, action)
if (action.txSuccess>0):
LOG(LOG_DET, " Action to execute: \"{}\" successfully executed".format(action.text))
action.rxExec += 1
return True
LOG(LOG_WAR, "<<< WARNING: Action to execute: \"{}\" was NOT successfully executed >>>".format(action.text));
return False
|
PHP
|
UTF-8
| 1,043 | 2.59375 | 3 |
[] |
no_license
|
<?php
session_start();
if (!isset( $_SESSION['count'])){
$_SESSION['count'] = 1;
} else {
$_SESSION['count']++;
}
$id = $_SESSION['count'];
if(isset($_POST['bookbus'])){
$passenger = $_POST['passengername'];
$dest = $_POST['dest'];
$bus = $_POST['bus'];
if(!empty($passenger) && !empty($dest) && !empty($bus)){
$servername = "localhost";
$root = "root";
$password = "";
$dbname = "busdb";
// Create connection
$conn = mysqli_connect($servername, $root, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO passenger VALUES ($id, '$passenger', '$dest', 50.00, '$bus');";
$sql .= "UPDATE totalSales SET totalsales = totalsales + 50 WHERE id = 1;";
mysqli_multi_query($conn, $sql);
}
mysqli_close($conn);
}
?>
|
TypeScript
|
UTF-8
| 440 | 2.875 | 3 |
[] |
no_license
|
const carMakers = ['ford', 'toyota', 'chevy'];
const carMakersEmpty: string[] = [];
const carsByMake = [['f150'], ['90'], ['camaro']];
const carsByMakeEmpty: string[][] = [];
const make = carsByMake.pop();
const makers = carMakers.map((car: string): { [car: string]: string } => ({
[car]: car,
}));
interface Makers {
[car: string]: string;
}
function logMakers(makers: Makers[]): void {
console.log(makers);
}
logMakers(makers);
|
Markdown
|
UTF-8
| 3,184 | 3.859375 | 4 |
[
"Apache-2.0"
] |
permissive
|
---
layout: post
title: LeetCode 0119 题解
description: "杨辉三角 II"
keywords: test
category: LeetCode
tags: [solving LeetCode]
---
### 题目描述
[杨辉三角 II](https://leetcode-cn.com/problems/pascals-triangle-ii/)
### 思路
根据第118题的思路,构造杨辉三角的集合,并返回最后一行。
### 题解
```java
class Solution {
public List<Integer> getRow(int rowIndex) {
List<List<Integer>> triangle = new ArrayList<>();
triangle.add(new ArrayList<Integer>());
triangle.get(0).add(1);
for(int i = 1; i < rowIndex+1; i++){
List<Integer> row = new ArrayList<>();
row.add(1);
for(int j = 1; j < i; j++)
row.add(triangle.get(i-1).get(j-1) + triangle.get(i-1).get(j));
row.add(1);
triangle.add(row);
}
return triangle.get(rowIndex);
}
}
```
* 改进一:不保存每一行,只保存前一行,用来计算当前行。
```java
class Solution {
public List<Integer> getRow(int rowIndex) {
List<Integer> preRow = new ArrayList<>();
preRow.add(1);
for(int i = 1; i < rowIndex+1; i++){
List<Integer> row = new ArrayList<>();
row.add(1);
for(int j = 1; j < i; j++)
row.add(preRow.get(j-1) + preRow.get(j));
row.add(1);
preRow = row;
}
return preRow;
}
}
```
两重`for`循环也可写成:
```java
for(int i = 1; i < rowIndex+1; i++){
List<Integer> row = new ArrayList<>();
for(int j = 0; j <= i; j++)
if(j == 0 || j == i)
row.add(1);
else
row.add(preRow.get(j-1) + preRow.get(j));
preRow = row;
}
```
* 改进二:只使用一个`List`集合(这里的内循环有点难理解,其实每次循环保存下来的`temp`是第$j$个值,随后赋给`pre`,给下一次$j$循环使用;那么相对于下次的$j$来说,这个`pre`就是第$j-1$个,即它的上一行的前一个值,因此此时可将第$j$个值更新为`pre + cur.get(j)`。)
```java
class Solution {
public List<Integer> getRow(int rowIndex) {
List<Integer> cur = new ArrayList<>();
cur.add(1);
int pre = 1;
for(int i = 1; i < rowIndex+1; i++){
for(int j = 1; j < i; j++){
int temp = cur.get(j);
cur.set(j, pre + cur.get(j));
pre = temp;
}
cur.add(1);
}
return cur;
}
}
```
* 改进三:根据上述思路,每次在第$j$个位置的值会被替换,因此要先将之前的值保存下来,如果每一行从后向前更新,就不需要保存了。
```java
class Solution {
public List<Integer> getRow(int rowIndex) {
List<Integer> cur = new ArrayList<>();
cur.add(1);
int pre = 1;
for(int i = 1; i < rowIndex+1; i++){
cur.add(1);
for(int j = i-1; j >= 1; j--)
cur.set(j, cur.get(j) + cur,get(j-1));
}
return cur;
}
}
```
|
PHP
|
UTF-8
| 704 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace Noldors\CommerceMLParser\Events;
use Noldors\Collections\Collection;
use Symfony\Component\EventDispatcher\Event;
class CategoryEvent extends Event
{
/**
* Categories collection.
*
* @var \Noldors\Collections\Collection
*/
protected $categories;
/**
* CategoryEvent constructor.
*
* @param \Noldors\Collections\Collection $categories
*/
public function __construct(Collection $categories)
{
$this->categories = $categories;
}
/**
* Get category collection.
*
* @return \Noldors\Collections\Collection
*/
public function getCategories()
{
return $this->categories;
}
}
|
Java
|
UTF-8
| 1,375 | 2.109375 | 2 |
[] |
no_license
|
package com.accolite.ims.ims.modles;
import java.sql.Date;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
@Getter
@Setter
@ToString
public class jobOpenings {
private long requirementId;
private String requirementDetails;
private Date startDate;
private Date endDate;
private int noOfCandidates;
private long skillId;
private String skill;
public String getSkill() {
return skill;
}
public void setSkill(String skill) {
this.skill = skill;
}
public long getRequirementId() {
return requirementId;
}
public void setRequirementId(long requirementId) {
this.requirementId = requirementId;
}
public String getRequirementDetails() {
return requirementDetails;
}
public void setRequirementDetails(String requirementDetails) {
this.requirementDetails = requirementDetails;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public int getNoOfCandidates() {
return noOfCandidates;
}
public void setNoOfCandidates(int noOfCandidates) {
this.noOfCandidates = noOfCandidates;
}
public long getSkillId() {
return skillId;
}
public void setSkillId(long skillId) {
this.skillId = skillId;
}
}
|
Python
|
UTF-8
| 2,751 | 3.125 | 3 |
[] |
no_license
|
'''
This file defines our database model.
'''
from flask_sqlalchemy import SQLAlchemy
from dataclasses import dataclass
from sqlalchemy.orm import backref
db = SQLAlchemy()
@dataclass
class TestSuite(db.Model):
'''
Defines a test suite. A test suite is a collection of test cases.
'''
__tablename__ = 'testsuite'
__test__ = False # Prevent PyTest from picking up this class
id = db.Column(db.Integer, primary_key=True)
# Suite name is limited to 128 characters to prevent boundless data storage.
name = db.Column(db.Unicode(length=128), nullable=False)
# The test suite's cases (one-to-many)
test_cases = db.relationship('TestCase', backref=backref('test_suite', cascade='all,delete'), lazy='dynamic')
def to_json(self):
return {
'id': self.id,
'name': self.name,
'test_cases': [test_case.to_json() for test_case in self.test_cases]
}
@dataclass
class TestCase(db.Model):
'''
Defines a test case. A test case is a collection of actions and assertions.
'''
__tablename__ = 'testcase'
__test__ = False # Prevent PyTest from picking up this class
id = db.Column(db.Integer, primary_key=True)
# Establish a relationship with the TestSuite model. Many cases can exist in a single test suite.
test_suite_id = db.Column(db.Integer(), db.ForeignKey('testsuite.id', ondelete='CASCADE'))
# The test case's steps (one-to-many)
steps = db.relationship('Step', backref=backref('test_case', cascade='all,delete'), lazy='dynamic')
def to_json(self):
return {
'id': self.id,
'test_suite_id': self.test_suite_id,
'steps': [step.to_json() for step in self.steps]
}
@dataclass
class Step(db.Model):
'''
Defines a test step. Defines what type of step (action, assertion) it is, and the test
case that this step is associated with, along with ordering.
'''
__tablename__ = 'step'
id = db.Column(db.Integer, primary_key=True)
# Establish a relationship with the TestCase model. Many steps can exist in a single test case.
test_case_id = db.Column(db.Integer(), db.ForeignKey('testcase.id', ondelete='CASCADE'))
# Contents of a step is limited to 1024 characters to prevent boundless data storage.
contents = db.Column(db.Unicode(length=1024), nullable=False)
# Will be either 'assertion' or 'action'. Limited to 9 characters as 'assertion' is the max length.
type = db.Column(db.Unicode(length=9), nullable=False)
def to_json(self):
return {
'id': self.id,
'test_case_id': self.test_case_id,
'contents': self.contents,
'type': self.type
}
|
Markdown
|
UTF-8
| 3,557 | 2.859375 | 3 |
[] |
no_license
|
+-- {: .rightHandSide}
+-- {: .toc .clickDown tabindex="0"}
### Context
#### Philosophy
+-- {: .hide}
[[!include philosophy - contents]]
=--
=--
=--
This page collects material related to
* [[Georg Hegel]],
_Lectures on the Philosophy of Religion_
published posthumously, starting 1832
([English hypertext version](https://www.marxists.org/reference/archive/hegel/works/re/index.htm))
In the _[[Encyclopedia of the Philosophical Sciences]]_ this material roughly corresponds to the third part, third section, b and c.
#Contents#
* table of contents
{:toc}
## Preliminaries
{#Preliminaries}
The preliminaries of the lectures state that religion and [[philosophy]] have the same subject, fall together, both are _worship_ of the _eternal truth in its very objectivity_, just by different means, following the ancient tradition of [[hermeticism]] and medieval [[mysticism]]:
> In der Tat ist dagegen die Behauptung zu machen, daß der Inhalt, das Bedürfnis, das Interesse der Philosophie mit der Theologie ein gemeinschaftliches ist.
> Der Gegenstand der Religion, wie der Philosophie, ist die ewige Wahrheit in ihrer Objektivität selbst, Gott und Nichts als Gott und die Explikation Gottes. Die Philosophie expliziert nur sich, indem sie die Religion expliziert, und indem sie sich expliziert, expliziert sie die Religion. Sie ist, wie die Religion, Beschäftigung mit diesem Gegenstande, sie ist der denkende Geist, der diesen Gegenstand, die Wahrheit, durchdringt, Lebendigkeit und Genuß, Wahrheit und Reinigung des subjektiven Selbstbewusstseins in und durch diese Beschäftigung.
> So fällt Religion und Philosophie in eins zusammen, die Philosophie ist in der Tat selbst Gottesdienst, aber beide sind Gottesdienst auf eigentümliche Weise: in dieser Eigentümlichkeit der Beschäftigung mit Gott unterscheiden sich beide.
...
> Neu ist aber die Verknüpfung der Philosophie und der Theologie nicht: sie hat Statt gefunden bei denjenigen Theologen, die man die Kirchenväter nennt, bei den vorzüglichen derselben.
...
> Diese Verknüpfung der Theologie und Philosophie sehen wir auch im Mittelalter; scholastische Philosophie ist eins und dasselbe mit der Theologie; Philosophie ist Theologie und Theologie ist Philosophie.
In ([Hegel, EncPhil, third part, third section](#HegelEnc)) art, religion and philosophy are discussed as three stages of the _absolute spirit_.
## More
On _[[speculative philosophy]]_:
> Spekulative Philosophie ist das Bewusstsein der Idee, so daß alles als Idee aufgefasst wird; die Idee aber ist das Wahre in Gedanken, nicht als bloße Anschauung oder Vorstellung. Das Wahre in Gedanken ist näher dieses, daß es konkret sei, in sich entzweit gesetzt, und zwar so, daß die zwei Seiten des Entzweiten entgegengesetzte Denkbestimmungen sind, als deren Einheit die Idee gefasst werden muss. Spekulativ denken heißt, ein Wirkliches auflösen und dieses in sich so entgegensetzen, daß die Unterschiede nach Denkbestimmungen entgegengesetzt sind und der Gegenstand als Einheit beider aufgefasst wird.
## Related
* _[[Lectures on the Philosophy of History]]_
* _[[Lectures on the History of Philosophy]]_
## References
* Wikipedia, _[Lectures of the Philosophy of Religion](http://en.wikipedia.org/wiki/Lectures_on_the_Philosophy_of_Religion)_
* {#HegelEnc} [[Georg Hegel]], _[[Encyclopedia of the Philosophical Sciences]]_
category: reference
|
Go
|
UTF-8
| 1,845 | 2.6875 | 3 |
[] |
no_license
|
package main
import (
"fmt"
"io/ioutil"
"os"
"github.com/adrg/xdg"
"gopkg.in/yaml.v2"
)
type NodeConfiguration struct {
Master string `yaml:"master"`
Slaves []string `yaml:"slaves"`
}
func localConfigPath() (string, error) {
return xdg.ConfigFile("FORmicidae Tracker/leto.yml")
}
var defaultNodeConfiguration NodeConfiguration = NodeConfiguration{
Master: "",
Slaves: nil,
}
func GetNodeConfiguration() NodeConfiguration {
confPath, err := localConfigPath()
if err != nil {
return defaultNodeConfiguration
}
conf, err := os.Open(confPath)
if err != nil {
return defaultNodeConfiguration
}
defer conf.Close()
txt, err := ioutil.ReadAll(conf)
if err != nil {
return defaultNodeConfiguration
}
res := defaultNodeConfiguration
err = yaml.Unmarshal(txt, &res)
if err != nil {
return defaultNodeConfiguration
}
return res
}
func (c NodeConfiguration) Save() {
confPath, err := localConfigPath()
if err != nil {
return
}
data, err := yaml.Marshal(c)
if err != nil {
return
}
ioutil.WriteFile(confPath, data, 0644)
}
func (c NodeConfiguration) IsMaster() bool {
return len(c.Master) == 0
}
func (c *NodeConfiguration) AddSlave(hostname string) error {
slaves := make(map[string]int, len(c.Slaves))
for i, s := range c.Slaves {
slaves[s] = i
}
if _, ok := slaves[hostname]; ok == true {
return fmt.Errorf("NodeConfiguration: already has slave %s", hostname)
}
c.Slaves = append(c.Slaves, hostname)
return nil
}
func (c *NodeConfiguration) RemoveSlave(hostname string) error {
slaves := make(map[string]int, len(c.Slaves))
for i, s := range c.Slaves {
slaves[s] = i
}
idx, ok := slaves[hostname]
if ok == false {
return fmt.Errorf("NodeConfiguration: does not have slave %s (%s)", hostname, c.Slaves)
}
c.Slaves = append(c.Slaves[:idx], c.Slaves[idx+1:]...)
return nil
}
|
Swift
|
UTF-8
| 6,592 | 2.828125 | 3 |
[] |
no_license
|
//
// ViewController.swift
// Baby Beat
//
// Created by may985 on 7/5/17.
// Copyright © 2017 may985. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var view1: UIView!
@IBOutlet weak var uiscrollview: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewDidLayoutSubviews() {
let imageWidth:CGFloat = view1.frame.width - 10
let imageHeight:CGFloat = 147
var yPosition:CGFloat = 0
var scrollViewContentSize:CGFloat=0
let spacer:CGFloat = 8
let label:UILabel = UILabel()
label.font = UIFont(name: "Futura-Bold", size: 12)
// let font = UIFont
let label2:UILabel = UILabel()
label2.font = UIFont(name: "Futura-Bold", size: 12)
//label2.font = UIFont(name: UIFont.fontNames(forFamilyName: "Futara")[2], size: 14)
let label3:UILabel = UILabel()
label3.font = UIFont(name: "Futura-Bold", size: 12)
let label4:UILabel = UILabel()
label4.font = UIFont(name: "Futura-Bold", size: 12)
let label5:UILabel = UILabel()
label5.font = UIFont(name: "Futura-Bold", size: 12)
//add label 1
label.text = "It is possible to hear your baby's hearthbeat from as early as 19-20 weeks in pregnancy, but it's higher chance to hear it i the last trimester as the baby gets bigger and the hearbeat stronger"
label.frame.size.width = imageWidth
label.frame.size.height = 90
label.numberOfLines = 0
label.textAlignment = .center
label.textColor = UIColor.white
label.center = self.view.center
label.frame.origin.y = yPosition
uiscrollview.addSubview(label)
scrollViewContentSize += 90 + spacer
yPosition += 50 + spacer
uiscrollview.contentSize = CGSize(width: imageWidth, height: scrollViewContentSize)
// add label 2
label2.text = "To record place you iPhone as shown in the picture, gently press on belly and tap button to start recording. When you want to finish recording tap again to stop recording"
label2.frame.size.width = imageWidth
label2.frame.size.height = imageHeight
label2.numberOfLines = 0
label2.textAlignment = .center
label2.textColor = UIColor.white
label2.center = self.view.center
label2.frame.origin.y = yPosition
uiscrollview.addSubview(label2)
scrollViewContentSize += imageHeight + 10 - 20
yPosition += imageHeight + 10 - 20
uiscrollview.contentSize = CGSize(width: imageWidth, height: scrollViewContentSize)
// add image view
let myImage:UIImage = UIImage(named: "baby.png")!
let myImageView:UIImageView = UIImageView()
myImageView.image = myImage
myImageView.contentMode = UIViewContentMode.scaleAspectFill
myImageView.frame.size.width = imageWidth
myImageView.frame.size.height = imageHeight
myImageView.center = self.view.center
myImageView.frame.origin.y = yPosition
uiscrollview.addSubview(myImageView)
yPosition += imageHeight + spacer - 20
scrollViewContentSize += imageHeight + spacer - 20
uiscrollview.contentSize = CGSize(width: imageWidth, height: scrollViewContentSize)
//add label 3
label3.text = "if you don't hear your baby heart beat try other positions."
label3.frame.size.width = imageWidth
label3.frame.size.height = imageHeight
label3.numberOfLines = 0
label3.textAlignment = .center
label3.textColor = UIColor.white
label3.center = self.view.center
label3.frame.origin.y = yPosition
uiscrollview.addSubview(label3)
scrollViewContentSize += imageHeight + 10 - 20
yPosition += 100 + 10 - 20
uiscrollview.contentSize = CGSize(width: imageWidth, height: scrollViewContentSize)
//add image 1
let myImage1:UIImage = UIImage(named: "born.png")!
let myImageView1:UIImageView = UIImageView()
myImageView1.image = myImage1
myImageView1.contentMode = UIViewContentMode.scaleAspectFill
myImageView1.frame.size.width = imageWidth
myImageView1.frame.size.height = 392
myImageView1.center = self.view.center
myImageView1.frame.origin.y = yPosition
uiscrollview.addSubview(myImageView1)
yPosition += 350 + spacer - 20
scrollViewContentSize += imageHeight + spacer - 20
uiscrollview.contentSize = CGSize(width: imageWidth, height: scrollViewContentSize)
//add label 4
label4.text = "If you still can't hear your baby heartbeat don't worry it doesn't mean anything is wrong with your baby. Wait for someday and try again to record."
label4.frame.size.width = imageWidth
label4.frame.size.height = imageHeight
label4.numberOfLines = 0
label4.textAlignment = .center
label4.textColor = UIColor.white
label4.center = self.view.center
label4.frame.origin.y = yPosition
uiscrollview.addSubview(label4)
scrollViewContentSize += 100 + 10
yPosition += 100 + 10
uiscrollview.contentSize = CGSize(width: imageWidth, height: scrollViewContentSize)
//add label 5
label5.text = "You can also try to record your hearbeat."
label5.frame.size.width = imageWidth
label5.frame.size.height = imageHeight
label5.numberOfLines = 0
label5.textAlignment = .center
label5.textColor = UIColor.white
label5.center = self.view.center
label5.frame.origin.y = yPosition
uiscrollview.addSubview(label5)
scrollViewContentSize += 100
yPosition += 100
uiscrollview.contentSize = CGSize(width: imageWidth, height: scrollViewContentSize)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
JavaScript
|
UTF-8
| 7,998 | 4 | 4 |
[] |
no_license
|
/*eslint-env browser */
//STEP 1
/*
var movies = ["Star Wars", "Monsters", "Happy Feet", "Ice Age", "War Games"];
window.console.log(movies[1]);
*/
//STEP 2: CONSTRUCTOR
/*
var movies = new Array(5);
var movies = new Array("Star Wars", "Monsters","Happy Feet", "Ice Age","War Games");
window.console.log(movies[0]);
*/
//STEP 3
/*
var movies = new Array("Star Wars", "Monsters","Happy Feet", "Ice Age","War Games");
movies[5] = new Array("RP1");
window.console.log(movies.length);
*/
//STEP 4 (DELETE FIRST ITEM)
/*
var movies = ["Star Wars", "Monsters", "Happy Feet", "Ice Age", "War Games"];
var lessmovies = movies.shift();
window.console.log(movies); // display content of the original array minus first
window.console.log(lessmovies); // display deleted content of the array
*/
//STEP 5 (FOR LOOP ITERATION)
/*
var movies = [];
movies[0] = "Star Wars";
movies[1] = "Monsters";
movies[2] = "Happy Feet";
movies[3] = "Ice Age";
movies[4] = "War Games";
movies[5] = "ET";
movies[6] = "Tron";
var i;
for (i = 0; i < movies.length; i += 1) {
window.console.log(movies[i] + "\n");
}
*/
//STEP 6 (FOR-IN LOOP)
/*
var movies = [];
movies[0] = "Star Wars";
movies[1] = "Monsters";
movies[2] = "Happy Feet";
movies[3] = "Ice Age";
movies[4] = "War Games";
movies[5] = "ET";
movies[6] = "Tron";
var element;
for (element in movies) {
window.console.log(movies[element]);
}
*/
//STEP 7 (FOR-IN LOOP SORTED)
/*
var movies = [];
movies[0] = "Star Wars";
movies[1] = "Monsters";
movies[2] = "Happy Feet";
movies[3] = "Ice Age";
movies[4] = "War Games";
movies[5] = "ET";
movies[6] = "Tron";
var moviesSort = movies.sort();
var element;
for (element in moviesSort) {
window.console.log(moviesSort[element]);
}
*/
//STEP 8 (LIST TWO ARRAYS)
/*
var movies = [];
movies[0] = "Star Wars";
movies[1] = "Monsters";
movies[2] = "Happy Feet";
movies[3] = "Ice Age";
movies[4] = "War Games";
movies[5] = "ET";
movies[6] = "Tron";
var leastFavMovies = [];
leastFavMovies[0] = "Bad Movie 1";
leastFavMovies[1] = "Bad Movie 2";
leastFavMovies[2] = "3 Bad Movies";
var i;
window.console.log("Movies I like:" + "\n" + "\n");
for (i = 0; i < movies.length; i += 1) {
window.console.log(movies[i] + "\n");
}
window.console.log("\n" + "\n");
var i;
window.console.log("Movies I regret watching:" + "\n" + "\n");
for (i = 0; i < leastFavMovies.length; i += 1) {
window.console.log(leastFavMovies[i] + "\n");
}
*/
//STEP 9 (CONCAT / REVERSE SORTED)
/*
var movies = [];
movies[0] = "Star Wars";
movies[1] = "Monsters";
movies[2] = "Happy Feet";
movies[3] = "Ice Age";
movies[4] = "War Games";
movies[5] = "ET";
movies[6] = "Tron";
var leastFavMovies = [];
leastFavMovies[0] = "Bad Movie 1";
leastFavMovies[1] = "Bad Movie 2";
leastFavMovies[2] = "3 Bad Movies";
var movies = movies.concat(leastFavMovies);
var moviesReverse = movies.reverse();
var element;
for (element in moviesReverse) {
window.console.log(moviesReverse[element]);
}
*/
//STEP 10 (POP - last item)
/*
var movies = [];
movies[0] = "Star Wars";
movies[1] = "Monsters";
movies[2] = "Happy Feet";
movies[3] = "Ice Age";
movies[4] = "War Games";
movies[5] = "ET";
movies[6] = "Tron";
var leastFavMovies = [];
leastFavMovies[0] = "Bad Movie 1";
leastFavMovies[1] = "Bad Movie 2";
leastFavMovies[2] = "3 Bad Movies";
var movies = movies.concat(leastFavMovies);
var moviesReverse = movies.reverse();
window.console.log(moviesReverse.pop());
*/
//STEP 11 (SHIFT - First item)
/*
var movies = [];
movies[0] = "Star Wars";
movies[1] = "Monsters";
movies[2] = "Happy Feet";
movies[3] = "Ice Age";
movies[4] = "War Games";
movies[5] = "ET";
movies[6] = "Tron";
var leastFavMovies = [];
leastFavMovies[0] = "Bad Movie 1";
leastFavMovies[1] = "Bad Movie 2";
leastFavMovies[2] = "3 Bad Movies";
var movies = movies.concat(leastFavMovies);
var moviesReverse = movies.reverse();
window.console.log(moviesReverse.shift());
*/
//STEP 12
/*
var movies = [];
movies[0] = "Star Wars";
movies[1] = "Monsters";
movies[2] = "Happy Feet";
movies[3] = "Ice Age";
movies[4] = "War Games";
movies[5] = "ET";
movies[6] = "Tron";
var leastFavMovies = [];
leastFavMovies[0] = "Bad Movie 1";
leastFavMovies[1] = "Bad Movie 2";
leastFavMovies[2] = "3 Bad Movies";
var movies = movies.concat(leastFavMovies);
var badMovie1 = movies.indexOf("Bad Movie 1");
var badMovie2 = movies.indexOf("Bad Movie 2");
var badMovie3 = movies.indexOf("3 Bad Movies");
window.console.log(badMovie1);
window.console.log(badMovie2);
window.console.log(badMovie3);
movies[7] = "New1";
movies[8] = "New2";
movies[9] = "New3";
var element;
for (element in movies) {
window.console.log(movies[element]);
}
*/
//STEP 13
/*
var employee1 = [];
employee1[0] = 4235;
employee1[1] = "Zak Ruvalcaba";
employee1[2] = "Web Developer";
employee1[3] = "Engineering";
employee1[4] = true;
var employee2 = [];
employee2[0] = 4567;
employee2[1] = "Jane Smith";
employee2[2] = "IT Help Desk";
employee2[3] = "IT";
employee2[4] = true;
var employees = employee1.concat(employee2);
window.console.log(employees);
window.console.log(employees[6]);
*/
//STEP 14
/*
var employee1 = [[4235, "Zak Ruvalcaba", "Web Developer", "Engineering", true]];
var employee2 = [[4567, "Jane Smith", "IT Help Desk", "IT", true]];
var employees = employee1.concat(employee2);
window.console.log(employees);
function listEmployee() {
"use strict";
var i, j, employeeNames;
for (i = 0; i < employees.length; i += 1) {
for (j = 0; j < employees[1].length; j += 1) {
employeeNames = employees[i][1];
window.console.log(employeeNames);
}
}
}
listEmployee();
*/
//employee.forEach(function(element) {
// "use strict";
// window.console.log(employee);
//});
//STEP 15
/*
function listEmployee() {
"use strict";
var i, employee1, employee2, employee3, employeesAll, currentEmployees;
employee1 = [[4235, "Zak Ruvalcaba", "Web Developer", "Engineering", "true"]];
employee2 = [[4567, "Jane Smith", "IT Help Desk", "IT", "true"]];
employee3 = [[4789, "Fred Brown", "HR Asst", "HR", "false"]];
employeesAll = employee1.concat(employee2, employee3);
window.console.log(employeesAll);
currentEmployees = [];
for (i = 0; i < employeesAll.length; i += 1) {
// for (j = 0; j < employeesAll[i].length; j += 1) {
// currentEmployees = employeesAll[i][4] === "true";
if (employeesAll[i][4] === "true") {
window.console.log(currentEmployees[i]);
}
}
}
listEmployee();
*/
//STEP 16
/*
function listMovies() {
"use strict";
var i, j, movies, movieNames;
movies = [
["Star Wars", 1],
["Happy Feet", 2],
["ET", 3],
["Ice Age", 4],
["Monster", 7]
];
movieNames = movies.filter(function (movie) {
for (i = 0; i < movies.length; i += 1) {
for (j = 0; j < movies[i].length; j += 1) {
if (typeof movie[i][j] === "string") {
window.console.log(movieNames);
}
}
}
});
*/
//STEP 17
/*
var employees = ["Zak", "Jessica", "Mark", "Fred", "Sally"];
window.console.log("Employees:" + "\n" + "\n");
function showEmployee() {
"use strict";
var i;
for (i = 0; i < employees.length; i += 1) {
window.console.log(employees[i] + "\n");
}
}
showEmployee();
*/
//STEP 18
/*
var data = [58, "abcd", true, null, false, 0];
window.console.log(data);
var filterData = data.filter(function (isNaN) {
"use strict";
window.console.log(filterData);
});
*/
//STEP 19
/*
function randomItem() {
"use strict";
var number, item;
number = [0, 10, 2, 103, 4, 65, 64, 7, 8, 9];
item = number[Math.floor(Math.random() * number.length)];
window.console.log(item);
}
randomItem();
*/
//STEP 20
/*
function maxItem() {
"use strict";
var number, maxNumber;
number = [0, 10, 2, 103, 4, 65, 64, 7, 8, 9];
maxNumber = Math.max(number);
window.console.log(maxNumber);
}
maxItem();
*/
|
Markdown
|
UTF-8
| 1,317 | 3.09375 | 3 |
[] |
no_license
|
# PG和PGP
## 定义
```text
PG = Placement Group
PGP = Placement Group for Placement purpose
pg_num = number of placement groups mapped to an OSD
When pg_num is increased for any pool, every PG of this pool splits into half, but they all remain mapped to their parent OSD.
Until this time, Ceph does not start rebalancing. Now, when you increase the pgp_num value for the same pool, PGs start to migrate from the parent to some other OSD, and cluster rebalancing starts. This is how PGP plays an important role.
```
## PG和PGP
增加pg number:
```sh
ceph osd pool set testpool pg_num 64
```
查看pg number:
```sh
ceph osd pool get testpool pg_num
```
增加PG会引起PG内的对象分裂,也就是在OSD上创建了新的PG目录,然后进行部分对象的move的操作。
增加pgp number:
```sh
ceph osd pool set testpool pgp_num 64
```
查看pgp number:
```sh
ceph osd pool get testpool pgp_num
```
调整PGP不会引起PG内的对象的分裂,但是会引起PG的分布的变动。
## 结论
* PG是指定存储池存储对象的目录有多少个,PGP是存储池PG的OSD分布组合个数。
* PG的增加会引起PG内的数据进行分裂,分裂到相同的OSD上新生成的PG当中。
* PGP的增加会引起部分PG的分布进行变化,但是不会引起 PG 内对象的变动。
|
PHP
|
UTF-8
| 5,616 | 2.59375 | 3 |
[] |
no_license
|
<?php
// Grab vars
$inp1 = $_POST['37AX-L'];
$inp2 = $_POST['42XR-j'];
$inp3 = $_POST['93ZZ-A'];
$state = $_POST['State'];
//prices correspond to part above respectively.
$price1 = '12.45';
$price2 = '15.34';
$price3 = '28.99';
//calculate hte number of items
$numItems = $inp1 + $inp2 + $inp3;
$subPrice1 = $price1 * $inp1;
$subPrice2 = $price2 * $inp2;
$subPrice3 = $price3 * $inp3;
//All the sub prices added up
$subTotal = $subPrice1 + $subPrice2 + $subPrice3;
$total = ($subTotal + calcShipping($numItems))*calcDiscount($numItems);
$tax = calcTax($state, $subTotal, $numItems);
//returns number to multiply by if there is a discount
function calcDiscount($numItems){
return ($numItems>50 ? 0.95 : 1);
}
//returns tax rate for state as a decimal representation of a percentage
function calcTax($state, $subTotal, $numItems){
switch ($state) {
case 'KS':
return number_format(round((0.04375*$subTotal + calcShipping($numItems)), 2), 2, '.', '');
case 'FL':
return number_format(round(0.06265*$subTotal, 2), 2, '.', '');
default:
return 0;
}
}
function getTaxRate($state){
switch($state){
case 'KS':
return '+ 4.375%';
case 'FL':
return '+ 6.265%';
default:
return '+ 0.000%';
}
}
//returns amount to be charged for shipping
function calcShipping($numItems){
return ($numItems < 30 ? 8.74 : 15.35);
}
function calcTotal($numItems, $tax, $subTotal){
return number_format(round(calcShipping($numItems)+ $subTotal + $tax, 2), 2, '.', '');
}
function printTax($state, $tax, $numItems){
echo '<tr><td> Taxes Due</td>';
echo '<td>State: ' . abbrevToName($state) . '</td>';
echo '<td>' . getTaxRate($state) . '</td>';
echo '<td>$' . number_format(round($tax*calcDiscount($numItems), 2), 2, '.', '') . '</td></tr>';
}
function printShipping($numItems){
echo '<tr><td>Shipping cost:</td>';
echo '<td></td>';
echo '<td></td>';
echo '<td>$' . calcShipping($numItems) . '</td></tr>';
}
function extendTable($numItems, $state, $tax, $subTotal){
if(calcDiscount($numItems) == 0.95){
echo '<tr><td>Discount:</td>';
echo '<td></td>';
echo '<td>-5%</td>';
echo '<td>$' . number_format(round(calcTotal($numItems, $tax, $subTotal)*0.05, 2), 2, '.', '') . '</td></tr>';
}
if($state == 'KS'){
printShipping($numItems);
printTax($state, $tax, $numItems);
}
else{
printTax($state, $tax, $numItems);
printShipping($numItems);
}
echo '<tr><td>Total:</td>';
echo '<td></td>';
echo '<td></td>';
echo '<td>$' . number_format(round(calcTotal($numItems, $tax, $subTotal), 2), 2, '.', '') . '</td></tr>';
}
function abbrevToName($state){
$fullName = array(
'AL'=>'Alabama',
'AK'=>'Alaska',
'AZ'=>'Arizona',
'AR'=>'Arkansas',
'CA'=>'California',
'CO'=>'Colorado',
'CT'=>'Connecticut',
'DE'=>'Delaware',
'DC'=>'District of Columbia',
'FL'=>'Florida',
'GA'=>'Georgia',
'HI'=>'Hawaii',
'ID'=>'Idaho',
'IL'=>'Illinois',
'IN'=>'Indiana',
'IA'=>'Iowa',
'KS'=>'Kansas',
'KY'=>'Kentucky',
'LA'=>'Louisiana',
'ME'=>'Maine',
'MD'=>'Maryland',
'MA'=>'Massachusetts',
'MI'=>'Michigan',
'MN'=>'Minnesota',
'MS'=>'Mississippi',
'MO'=>'Missouri',
'MT'=>'Montana',
'NE'=>'Nebraska',
'NV'=>'Nevada',
'NH'=>'New Hampshire',
'NJ'=>'New Jersey',
'NM'=>'New Mexico',
'NY'=>'New York',
'NC'=>'North Carolina',
'ND'=>'North Dakota',
'OH'=>'Ohio',
'OK'=>'Oklahoma',
'OR'=>'Oregon',
'PA'=>'Pennsylvania',
'RI'=>'Rhode Island',
'SC'=>'South Carolina',
'SD'=>'South Dakota',
'TN'=>'Tennessee',
'TX'=>'Texas',
'UT'=>'Utah',
'VT'=>'Vermont',
'VA'=>'Virginia',
'WA'=>'Washington',
'WV'=>'West Virginia',
'WI'=>'Wisconsin',
'WY'=>'Wyoming',
);
return $fullName[$state];
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="proj3.js"></script>
<link rel="stylesheet" href="proj3.css">
</head>
<table class="table-minimal">
<thead>
<tr>
<th>Unit</th>
<th>Unit Cost</th>
<th>Quantity</th>
<th>Unit Subtotal</th>
</tr>
</thead>
<tbody>
<tr>
<td>37AX-L</td>
<td>$12.45ea</td>
<?php echo '<td>' . $inp1 . '</td>';?>
<?php echo '<td>$' . number_format(round($subPrice1, 2), 2, '.', '') . '</td>';?>
</tr>
<tr>
<td>42XR-J</td>
<td>$15.34ea</td>
<?php echo '<td>' . $inp2 . '</td>';?>
<?php echo '<td>$' . number_format(round($subPrice2, 2), 2, '.', '') . '</td>';?>
</tr>
<tr>
<td>93ZZ-A</td>
<td>$28.99ea</td>
<?php echo '<td>' . $inp3 . '</td>';?>
<?php echo '<td> $' . number_format(round($subPrice3, 2), 2, '.', '') . '</td>';?>
</tr>
<tr>
<td>Your SubTotal is:</td>
<td></td>
<?php echo '<td>' . $numItems . '</td>';?>
<?php echo '<td>$' . number_format(round($subTotal, 2), 2, '.', '') . '</td>';?>
</tr>
<?php extendTable($numItems, $state, $tax, $subTotal); ?>
</tbody>
</table>
<br>
<div id="shipAgree"></div>
</html>
|
Java
|
UTF-8
| 2,889 | 2.578125 | 3 |
[] |
no_license
|
package Modelo;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import negocio.Centro;
import negocio.Cliente;
import negocio.ConjuntoDeLugares;
import negocio.Lugar;
public class Persistencia {
private String direccionClientes = "clientes.json";
private String direccionCentros = "centros.json";
public ArrayList<Cliente> importarClientes() {
Gson gson = new Gson();
ConjuntoDeLugares conjunto = new ConjuntoDeLugares();
try {
BufferedReader reader = new BufferedReader(new FileReader(direccionClientes));
conjunto = gson.fromJson(reader, ConjuntoDeLugares.class);
ArrayList<Cliente> clientes = new ArrayList<Cliente>();
for (Lugar lugar : conjunto.getLugares())
clientes.add(new Cliente(lugar.getNombre(), lugar.getUbicacion()));
return clientes;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public ArrayList<Centro> importarCentrosDeDistribucion() {
Gson gson = new Gson();
ConjuntoDeLugares conjunto = new ConjuntoDeLugares();
try {
BufferedReader reader = new BufferedReader(new FileReader(direccionCentros));
conjunto = gson.fromJson(reader, ConjuntoDeLugares.class);
ArrayList<Centro> centros = new ArrayList<Centro>();
for (Lugar lugar : conjunto.getLugares())
centros.add(new Centro(lugar.getNombre(), lugar.getUbicacion()));
return centros;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public void exportarCentros(ArrayList<Centro> centrosDeDistribucion) {
ConjuntoDeLugares conjunto = new ConjuntoDeLugares(centrosDeDistribucion);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
try {
FileWriter writer = new FileWriter(direccionCentros);
writer.write(gson.toJson(conjunto));
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void exportarClientes(ArrayList<Cliente> clientes) {
ConjuntoDeLugares conjunto = new ConjuntoDeLugares(clientes);
Gson gson = new GsonBuilder().setPrettyPrinting().create();
try {
FileWriter writer = new FileWriter(direccionClientes);
writer.write(gson.toJson(conjunto));
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// private <T> ArrayList<T> crearLista(ConjuntoDeLugares conjunto) {
// ArrayList<T> clientes = new ArrayList<T>();
// for (Lugar lugar : conjunto.getLugares())
// clientes.add(new T(lugar));
// }
//opcional:
// public void guardar(ConjuntoDePersonas array) {
// Gson gson = new GsonBuilder().setPrettyPrinting().create();
// try {
// FileWriter writer = new FileWriter("jsonPretty.json");
// writer.write(gson.toJson(array));
// writer.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
//}
}
|
Go
|
UTF-8
| 2,265 | 3.203125 | 3 |
[
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"GPL-2.0-only"
] |
permissive
|
package template
import (
"fmt"
"os"
"path"
"path/filepath"
"strings"
log "github.com/sirupsen/logrus"
)
var NodeName = os.Getenv("NODENAME")
// fileInfo describes a configuration file and is returned by fileStat.
type fileInfo struct {
Uid uint32
Gid uint32
Mode os.FileMode
Md5 string
}
func expandKeys(prefix string, keys []string) []string {
s := make([]string, len(keys))
for i, k := range keys {
// Prepend the prefix and replace "NODENAME" in the key by the actual node name.
s[i] = path.Join(prefix, strings.Replace(k, "//NODENAME", "/"+NodeName, 1))
}
return s
}
// isFileExist reports whether path exits.
func isFileExist(fpath string) bool {
if _, err := os.Stat(fpath); os.IsNotExist(err) {
return false
}
return true
}
// sameConfig reports whether src and dest config files are equal.
// Two config files are equal when they have the same file contents and
// Unix permissions. The owner, group, and mode must match.
// It return false in other cases.
func sameConfig(src, dest string) (bool, error) {
if !isFileExist(dest) {
return false, nil
}
d, err := fileStat(dest)
if err != nil {
return false, err
}
s, err := fileStat(src)
if err != nil {
return false, err
}
if d.Uid != s.Uid {
log.Debug(fmt.Sprintf("%s has UID %d should be %d", dest, d.Uid, s.Uid))
}
if d.Gid != s.Gid {
log.Debug(fmt.Sprintf("%s has GID %d should be %d", dest, d.Gid, s.Gid))
}
if d.Mode != s.Mode {
log.Debug(fmt.Sprintf("%s has mode %s should be %s", dest, os.FileMode(d.Mode), os.FileMode(s.Mode)))
}
if d.Md5 != s.Md5 {
log.Debug(fmt.Sprintf("%s has md5sum %s should be %s", dest, d.Md5, s.Md5))
}
if d.Uid != s.Uid || d.Gid != s.Gid || d.Mode != s.Mode || d.Md5 != s.Md5 {
return false, nil
}
return true, nil
}
// recursiveFindFiles find files with pattern in the root with depth.
func recursiveFindFiles(root string, pattern string) ([]string, error) {
files := make([]string, 0)
findfile := func(path string, f os.FileInfo, err error) (inner error) {
if err != nil {
return
}
if f.IsDir() {
return
} else if match, innerr := filepath.Match(pattern, f.Name()); innerr == nil && match {
files = append(files, path)
}
return
}
return files, filepath.Walk(root, findfile)
}
|
Java
|
UTF-8
| 1,316 | 2.25 | 2 |
[] |
no_license
|
package com.example.foregroundservice;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button mBtnStart,mBtnStop;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBtnStart = findViewById(R.id.BtnForeGround);
mBtnStop = findViewById(R.id.BtnStop);
mBtnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,MyService.class);
// Start foreground
// Nếu không có notification thì sau vài giây sẽ crack app
ContextCompat.startForegroundService(MainActivity.this,intent);
}
});
mBtnStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,MyService.class);
stopService(intent);
}
});
}
}
|
C#
|
UTF-8
| 3,386 | 2.71875 | 3 |
[
"MIT"
] |
permissive
|
// Copyright © Clinton Ingram and Contributors. Licensed under the MIT License.
using System;
using System.Diagnostics;
using System.Buffers.Binary;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
namespace PhotoSauce.MagicScaler;
internal unsafe ref struct SpanBufferReader
{
private readonly ReadOnlySpan<byte> span;
private nint pos;
public readonly int Position => (int)pos;
public SpanBufferReader(ReadOnlySpan<byte> buff) => span = buff;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Read<T>() where T : unmanaged
{
Debug.Assert((uint)span.Length >= (uint)(pos + sizeof(T)));
T val = Unsafe.ReadUnaligned<T>(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), pos));
pos += sizeof(T);
return val;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public T Read<T>(bool bswap) where T : unmanaged
{
T val = Read<T>();
if (sizeof(T) > sizeof(byte) && bswap)
val = BufferUtil.ReverseEndianness(val);
return val;
}
}
internal unsafe ref struct SpanBufferWriter
{
private readonly Span<byte> span;
private nint pos;
public readonly int Position => (int)pos;
public SpanBufferWriter(Span<byte> buff) => span = buff;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Write<T>(T val) where T : unmanaged
{
Unsafe.WriteUnaligned(ref Unsafe.Add(ref MemoryMarshal.GetReference(span), pos), val);
pos += sizeof(T);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Write<T>(ReadOnlySpan<T> val) where T : unmanaged
{
MemoryMarshal.AsBytes(val).CopyTo(span[(int)pos..]);
pos += val.Length;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void TryWrite<T>(ReadOnlySpan<T> val) where T : unmanaged
{
int len = Math.Min(span.Length - (int)pos, MemoryMarshal.AsBytes(val).Length);
MemoryMarshal.AsBytes(val)[..len].CopyTo(span[(int)pos..]);
pos += val.Length;
}
}
internal static class BufferUtil
{
public static SpanBufferReader AsReader(this scoped in ReadOnlySpan<byte> span, Range range) => new(span[range]);
public static SpanBufferReader AsReader(this scoped in ReadOnlySpan<byte> span, int offset, int length) => new(span.Slice(offset, length));
public static SpanBufferWriter AsWriter(this scoped in Span<byte> span, Range range) => new(span[range]);
public static SpanBufferWriter AsWriter(this scoped in Span<byte> span, int offset, int length) => new(span.Slice(offset, length));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static unsafe T ReverseEndianness<T>(T val) where T : unmanaged
{
if (typeof(T) == typeof(Rational) || typeof(T) == typeof(SRational))
{
var (n, d) = Unsafe.As<T, (uint, uint)>(ref val);
return Unsafe.As<(uint, uint), T>(ref Unsafe.AsRef((BinaryPrimitives.ReverseEndianness(n), BinaryPrimitives.ReverseEndianness(d))));
}
if (sizeof(T) == sizeof(ushort))
return Unsafe.As<ushort, T>(ref Unsafe.AsRef(BinaryPrimitives.ReverseEndianness(Unsafe.As<T, ushort>(ref val))));
if (sizeof(T) == sizeof(uint))
return Unsafe.As<uint, T>(ref Unsafe.AsRef(BinaryPrimitives.ReverseEndianness(Unsafe.As<T, uint>(ref val))));
if (sizeof(T) == sizeof(ulong))
return Unsafe.As<ulong, T>(ref Unsafe.AsRef(BinaryPrimitives.ReverseEndianness(Unsafe.As<T, ulong>(ref val))));
throw new ArgumentException($"Reverse not implemented for {typeof(T).Name}", nameof(T));
}
}
|
C++
|
UTF-8
| 446 | 2.53125 | 3 |
[] |
no_license
|
#include "Dice.h"
using namespace AxiomLib;
using namespace AxiomLib::MultiMarking;
Dice::Dice()
{
}
double Dice::compute(const std::vector<bool> &v1, const std::vector<bool> &v2)
{
int p1 = 0, p2 = 0, pI = 0;
for(int i = 0; i < (int)v1.size(); ++i) {
if(v1[i]) {
++p1;
}
if(v2[i]) {
++p2;
}
if(v1[i] && v2[i]) {
++pI;
}
}
return 1.0 - 2.0 * (double) pI / ((double) p1 + (double) p2);
}
|
Markdown
|
UTF-8
| 3,819 | 2.84375 | 3 |
[] |
no_license
|
### Podcast Response - Week 4
To [Virginia Eubanks, AUTOMATING INEQUALITY](https://www.writersvoice.net/tag/virginia-eubanks/) with Virginia Eubanks and Francesca Rheannon (2019).
* ##### *How do technical tools promise to "fair out" the remaining discrimination that exist in social/welfare systems? In how far can they succeed, in which ways do they fail?*
In the US, technical tools are used to serve as a filter of the alleged "truly worthy" people for the welfare against "discriminatory decision-making". The previous approach of in-person contact could potentially involve biased personal judgement regarding races, sex, and other factors considered as a deviant social status. Therefore, the technical approach claims to "fair out" such bias by viewing people with the same objective lens in order to decide who are worth the help. It has perhaps succeeded in directing the resources to the most desparate people according to the pre-built metric, however, definitely failed as an inhuman way of dealing with people. Tragic stories as is told by Eubanks happened, in which people in need for help are deprived of their own rights due to the less negotiable nature of the technical system. Also, such a seemingly object yet inhuman factor disovles the accountability of faulty decisions, protecting the system designers from being accused as the real decision maker.
* ##### *Imagine, what could this (following quotes) mean in the widest sense?*
> "The state doesn't need a cop to kill a person" and "electronic incarceration"
By "modernizing" the social/welfare system, the state power can easily deprive or limit people's access to essential resources, such as housing and food, sometimes without noticing it. To my understanding, people are constantly imprisoned in an "electronic incarceration", which include and not limited to being monitored by digital surveillance which other policies would act upon.
* ##### *What do you understand this to mean?*
> "systems act as a kind of 'empathy-overwrite'"
The systems try to convince us that the deprived group of people are not worth our empathy by proving them somehow inadequate or deviant according to the whatever the standard is. It is an irrational rationalization of promoting inequality in public services against our natural empathy to the poor.
* ##### *China is much more advanced and expansive when it comes to applying technical solutions to societal processes or instant challenges ([recent example](https://www.nytimes.com/2020/03/01/business/china-coronavirus-surveillance.html?)). Try to point example cases in China that are in accordance or in opposition to the problematics discussed in the podcast. Perhaps you can think of*
> "technical systems not well thought-through about what their impace on human beings is"
Facial recognition as payment method at retail stores and vending machines has been one of the most impactful but controversial technical adoption in China. Unlike the approach as on a personal mobile phone which presumeably store the more sophisticated facial features at a digital black box inside the device, most of the facial recognitions "in the wild" require online access to our biometrics, most probably a simplied one represented by 2D RGB images or sequence. Therefore, it could be significantly more vulnerable than what we already have just for the sake that one bit more of convinience. However, for technology companies, it seems absolutely appealing due to more user data collection and profitability. Besides, there have been many reports of backdoors in Chinese softwares with government association. With the technically empowered govenmental patriachy, people could hardly have an alternative to unlimitedly ceding their rights, branded as an inevitable trend of technological advancement.
|
Java
|
UTF-8
| 1,629 | 3.9375 | 4 |
[] |
no_license
|
package ca.svarb.whelper;
/**
* A Grid stores a set of Cells in a square arrangement.
* All Cells by default contain blank string ("").
* Cells can be accessed by [col,row] values (0 indexed)
* or iterated through.
*/
public class Grid extends AbstractGridGameBoard {
/**
* Makes a grid with default size of 5
*/
public Grid() {
this(5);
}
/**
* Make a square grid of blank Cells.
* Cells will be initialized with neighbours according
* to grid position.
* @param size
*/
public Grid(int size) {
super();
setSize(size);
}
/**
* Create a Grid filled with given strings into the cells
* @param gridStrings
*/
public Grid(String[][] gridStrings) {
super(gridStrings);
}
/**
* Set Cell neighbours and left/right/up/down navigation cells
* @param col
* @param row
*/
@Override
protected void initCell(int col, int row) {
Cell currentCell=this.getCell(col, row);
if(col>0) {
Cell left=this.getCell(col-1, row);
currentCell.addNeighbour(left);
currentCell.setLeftCell(left);
if(row<this.size-1) {
Cell belowLeft=this.getCell(col-1, row+1);
currentCell.addNeighbour(belowLeft);
}
}
if(row>0) {
Cell above=this.getCell(col, row-1);
currentCell.addNeighbour(above);
currentCell.setUpCell(above);
if(col>0) {
Cell aboveLeft=this.getCell(col-1, row-1);
currentCell.addNeighbour(aboveLeft);
}
}
if (row==this.size-1) {
Cell topCell=this.getCell(col, 0);
currentCell.setDownCell(topCell);
}
if (col==this.size-1) {
Cell leftEdgeCell=this.getCell(0, row);
currentCell.setRightCell(leftEdgeCell);
}
}
}
|
Markdown
|
UTF-8
| 1,176 | 3.484375 | 3 |
[] |
no_license
|
# 입출력
### Java의 입출력
- 압력 : Scanner / 출력 : System.out
```java
Scanner sc = new Scanner(System.in);
```
- 더 빠른 방법 : BufferedReader 사용
```java
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
```
- 출력이 많은 경우 StringBuilder를 사용해서 한 문자열로 만들어 출력을 한 번만 사용하거나, BufferedWriter 를 사용한다.
### C의 입출력
- 입력 : scanf / 출력: printf
---
# 문제풀이요령
### 1. 테스트 케이스 형식으로 주어지는 경우
각각의 줄을 독립적인 문제로 생각하고 푼다. (한줄한줄 입력받고 출력한다.)
```c
// t로 주어진 경우
int t;
scanf("%d", &t);
while (t-- > 0){
// 코드
}
```
```c
int t;
scanf("%d",&t);
for (int i=0; i<t; i++){
// 코드
}
```
### 2. 입력이 몇 개인지 주어지지 않은 경우
입력을 EOF 까지 받는다.
- JAVA 의 경우
```java
while (scanner.hasNextInt()){ }
```
- C 의 경우 : scanf의 리턴값은 성공적으로 입력받은 변수의 개수임을 이용한다.
```java
while (scanf("%d %d", &a,&b) == 2)
```
|
Java
|
UTF-8
| 1,385 | 1.890625 | 2 |
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.test;
import com.intellij.codeInsight.JavaCodeInsightTestCase;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.util.Ref;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.idea.test.KotlinTestUtils;
import java.io.File;
import static com.intellij.testFramework.RunAll.runAll;
/**
* Please use KotlinLightCodeInsightFixtureTestCase as the base class for all new tests.
*/
@Deprecated
public abstract class KotlinCodeInsightTestCase extends JavaCodeInsightTestCase {
private Ref<Disposable> vfsDisposable;
@Override
final protected @NotNull String getTestDataPath() {
return KotlinTestUtils.toSlashEndingDirPath(getTestDataDirectory().getAbsolutePath());
}
protected @NotNull File getTestDataDirectory() {
return new File(super.getTestDataPath());
}
@Override
protected void setUp() throws Exception {
vfsDisposable = KotlinTestUtils.allowProjectRootAccess(this);
super.setUp();
}
@Override
protected void tearDown() {
runAll(
() -> super.tearDown(),
() -> KotlinTestUtils.disposeVfsRootAccess(vfsDisposable)
);
}
}
|
Java
|
UTF-8
| 1,207 | 2.21875 | 2 |
[] |
no_license
|
package sacred.alliance.magic.debug.action;
import java.util.List;
import com.game.draco.GameContext;
import com.game.draco.app.rank.RankInitResult;
import com.game.draco.debug.message.request.C10057_RankInitReqMessage;
import com.game.draco.debug.message.response.C10057_RankInitRespMessage;
import sacred.alliance.magic.core.Message;
import sacred.alliance.magic.core.action.ActionContext;
import sacred.alliance.magic.core.action.ActionSupport;
import sacred.alliance.magic.util.Util;
public class RankInitAction extends ActionSupport<C10057_RankInitReqMessage>{
@Override
public Message execute(ActionContext context, C10057_RankInitReqMessage req) {
C10057_RankInitRespMessage resp = new C10057_RankInitRespMessage();
RankInitResult result = GameContext.getRankApp().initLogDataFormDB(req.getRankIds());
resp.setSucessRankIds(this.listToArr(result.getSuccessList()));
resp.setFailureRankIds(this.listToArr(result.getFailureList()));
return resp;
}
private int[] listToArr(List<Integer> list){
if(Util.isEmpty(list)){
return new int[0] ;
}
int[] value = new int[list.size()] ;
int index = 0 ;
for(Integer i : list){
value[index ++] = i ;
}
return value ;
}
}
|
Java
|
UTF-8
| 2,525 | 2.859375 | 3 |
[] |
no_license
|
package pt.tecnico.mydrive.domain;
import pt.tecnico.mydrive.exception.FileDoesNotExistException;
import pt.tecnico.mydrive.exception.UserIsNotInSessionException;
import java.util.ArrayList;
import java.util.List;
public class Directory extends Directory_Base {
public Directory() {
super();
}
public Directory(String path, String name)/* throws PathTooLongException */{
super();
String pathString = path.toString();
//VASCONCELOS ADDICIONA EXCEPCAO
if (pathString.length() > 1024) {
//throw new PathTooLongException(path);
}
setPath(path);
setName(name);
}
/*public Directory(User user, Element xml) {
super();
//xmlImport();
setUser(user);
}*/
/*@Override
public void setUser(User user) {
if (user == null)
super.setUser(null);
else
user.addDirectory(this);
}*/
public void delete(){
String path = getPath();
Directory directoryToRemove = getDirectoryByPath(path);
for (File f : directoryToRemove.getOwnedSet()){
f.delete();
}
setOwner(null);
setMydrive(null);
deleteDomainObject();
}
public String getPath(){
return getDir().getPath() + "/" + getName();
}
//Corrigir isto: verificar se estou a por dir ou files
public List<String> listAllFiles() {
List<String> files = new ArrayList<>();
for(File f: getOwnedSet()){
String result = f.getName();
files.add(result);
/* Nao esquecer o get content e o permission
System.out.print(f.getPermissions());
System.out.print(f.getContent());*/
}
return files;
}
public File getFileByName(String fileName) {
for(File f: getOwnedSet()){
if(f.getName().equals(fileName)){
return f;
}
}
throw new FileDoesNotExistException(fileName);
}
public boolean fileExists(int id){
MyDrive md = MyDrive.getInstance();
pt.tecnico.mydrive.domain.File file = md.getFile(id);
return (file != null);
}
public File getFileByPath(String path) {
for(pt.tecnico.mydrive.domain.File file : getOwnedSet()){
if(file.getPath().equals(path)){
return (Directory) file;
}
}
return null;
}
//CORRIGIR ISTO E POR BEM; ESTA AQUI SO PARA NAO ATORFIAR A MALTA
public Directory getDirectoryByPath(String path){
for(File f : getOwnedSet()){
if(f.getPath().equals(path))
if(f.getType().equals("Directory"))
return (Directory) f;
}
return null;
}
public void execute(User u, List<String> args){
//NOTHING TO DO
}
@Override
public String getType(){
return "Directory";
}
}
|
Java
|
UTF-8
| 7,721 | 2.03125 | 2 |
[] |
no_license
|
package com.Deadline.leon.deadline;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.content.Intent;
import android.widget.Button;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.Calendar;
public class CreateJob extends AppCompatActivity {
//Buttons
private Button Butt_Home, Butt_Create, Butt_Cancel;
//Firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseUser user;
//Spinner
private Spinner nav_spin;
private Boolean spin_Clicked = false;
//Task
private String jName, jDate, jSummary;
private Boolean jComplete;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_job);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mAuth = FirebaseAuth.getInstance();
mAuthListener = new FirebaseAuth.AuthStateListener()
{
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth)
{
/*FirebaseUser*/ user = firebaseAuth.getCurrentUser();
if(user != null)
{
Log.d(CreateAccount.class.getSimpleName(), "onAuthStateChanged:signed_in" + user.getUid());
}
else
{
Log.d(CreateAccount.class.getSimpleName(), "onAuthStateChanged:signed_out");
}
}
};
user = mAuth.getCurrentUser();
Butt_Create = (Button) findViewById(R.id.jobCreate);
Butt_Create.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
jName = ((EditText) findViewById(R.id.jobName)).getText().toString();
jDate = ((DatePicker) findViewById(R.id.datePicker)).getMonth() + 1 + "/" + ((DatePicker) findViewById(R.id.datePicker)).getDayOfMonth() + "/" + ((DatePicker) findViewById(R.id.datePicker)).getYear();
jSummary = ((EditText) findViewById(R.id.jobDescription)).getText().toString();
DatePicker tCalendar = (DatePicker) findViewById(R.id.datePicker);
Calendar validDate = Calendar.getInstance();
validDate.set(tCalendar.getYear(),tCalendar.getMonth(),tCalendar.getDayOfMonth());
jComplete = false;
if(!jName.equals("") &&
!jDate.equals(""))
{
if(!Calendar.getInstance().after(validDate))
{
CreateJob(jName,jDate,jSummary,jComplete);
Intent intent = new Intent(CreateJob.this, Tasks.class);
startActivity(intent);
}
else
{
Toast.makeText(CreateJob.this, "Please enter a valid date", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(CreateJob.this, "Please fill out the form completely", Toast.LENGTH_SHORT).show();
}
}
});
Butt_Home = (Button) findViewById(R.id.Home_Button);
Butt_Home.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(CreateJob.this, HomeScreen.class);
startActivity(intent);
}
});
Butt_Cancel = (Button) findViewById(R.id.jobCreateCancel);
Butt_Cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(CreateJob.this, Jobs.class);
startActivity(intent);
}
});
mAuth = FirebaseAuth.getInstance();
nav_spin = (Spinner) findViewById(R.id.nav_Spinner);
nav_spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String selection = parent.getSelectedItem().toString();
if (selection.equals("Projects") && spin_Clicked){
Intent intent = new Intent(CreateJob.this, Projects.class);
nav_spin.setSelection(0);
startActivity(intent);
}
else if (selection.equals("Settings") && spin_Clicked){
Intent intent = new Intent(CreateJob.this, Settings.class);
nav_spin.setSelection(0);
startActivity(intent);
}
else if (selection.equals("Account") && spin_Clicked){
Intent intent = new Intent(CreateJob.this, AccountInfo.class);
nav_spin.setSelection(0);
startActivity(intent);
}
else if (selection.equals("Invitations") && spin_Clicked){
Intent intent = new Intent(CreateJob.this, Invitations.class);
nav_spin.setSelection(0);
startActivity(intent);
}
else if (selection.equals("About") && spin_Clicked){
Toast.makeText(CreateJob.this, R.string.version_number, Toast.LENGTH_SHORT).show();
nav_spin.setSelection(0);
}
else if (selection.equals("Logout") && spin_Clicked){
mAuth.signOut();
Intent intent = new Intent(CreateJob.this, Login.class);
nav_spin.setSelection(0);
startActivity(intent);
}
spin_Clicked = true;
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
@Override
protected void onStart() {
super.onStart();
nav_spin.setSelection(0);
}
public void CreateJob(String _name, String _date, String _summary, Boolean _complete)
{
//TODO: Replace hardcoded project key with active project key as determined by CStoreIDSs
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("projects").child(((CStoreIDs)getApplication()).getProjectID()).child("tasks");
String newKey = ref.child(user.getUid()).child("jobs").push().getKey();
((CStoreIDs)getApplication()).setJobID(newKey);
//TODO: Need to replace hardcoded key with active task key as determined by CStoreIDs
ref = ref.child(((CStoreIDs)getApplication()).getTaskID()).child("jobs");
ref.child(newKey).child("name").setValue(_name);
ref.child(newKey).child("deadline").setValue(_date);
ref.child(newKey).child("summary").setValue(_summary);
ref.child(newKey).child("complete").setValue(_complete);
//Toast.makeText(CreateJob.this,"Job creation successful",Toast.LENGTH_SHORT).show();
}
}
|
Java
|
UTF-8
| 1,446 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
package com.prunatic.infrastructure.persistence.user;
import com.prunatic.domain.user.User;
import com.prunatic.infrastructure.persistence.user.InMemoryUserRepository;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
public class InMemoryUserRepositoryTest {
InMemoryUserRepository sut;
@Before
public void setUp() throws Exception {
sut = new InMemoryUserRepository();
}
@Test
public void shouldLetAddUsers() throws Exception {
String aUsername = "aUsername";
String[] someRoles = {"aRole"};
User user = User.fromRegistration(aUsername, someRoles);
sut.add(user);
assertEquals(1, sut.allUsers().length);
}
@Test
public void shouldFindUserByUsername()
{
String aUsername = "aUsername";
User expectedUser = User.fromRegistration(aUsername, new String[]{"aRole"});
sut.add(expectedUser);
User actual = sut.userByUsername(aUsername);
assertSame(expectedUser, actual);
}
@Test
public void shouldReturnNullWhenNoUserFoundByUsername() throws Exception {
String aUsername = "aUsername";
String aDifferentUsername = "aDifferentUsername";
User expectedUser = User.fromRegistration(aUsername, new String[]{"aRole"});
sut.add(expectedUser);
User actual = sut.userByUsername(aDifferentUsername);
assertNull(actual);
}
}
|
C++
|
UTF-8
| 1,324 | 2.578125 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
#define maxn 1048579
char sv[maxn + 2];
int N, B;
vector<int> P;
void Primetable()
{
int i, j;
for (i = 2; i * i < maxn;)
{
for (j = i + i; j <= maxn; j += i)
{
sv[j] = 1;
}
for (++i; sv[i]; i++)
;
}
P.push_back(2);
for (i = 3; i < maxn; i += 2)
if (sv[i] == 0)
{
P.push_back(i);
}
}
int times(int n)
{
int i, sum = 0;
for (i = n; i <= N; i *= n)
{
sum += N / i;
}
return sum;
}
int Zeros()
{
int i, k, n = B, zero = 2147483647, t, a, m;
for (i = 0; i < P.size() && n > 1; i++)
{
m = P[i];
m *= m;
if (m > n)
{
break;
}
if (n % P[i] == 0)
{
k = 0;
while (n % P[i] == 0)
{
k++;
n /= P[i];
}
t = times(P[i]);
a = t / k;
if (zero > a)
{
zero = a;
}
}
}
if (n > 1)
{
t = times(n);
}
if (zero > t)
{
zero = t;
}
return zero;
}
int digit()
{
int i, dig;
double sum = 0;
for (i = 1; i <= N; i++)
{
sum += log10(i) / log10(B);
}
sum += 1e-5;
dig = ceil(sum);
return dig;
}
void Cal()
{
int z, dig;
if (N == 0)
{
cout << "0 "
<< "1\n";
return;
}
if (N == 1)
{
cout << "0 "
<< "1\n";
return;
}
z = Zeros();
dig = digit();
cout << z << " " << dig << endl;
}
int main()
{
Primetable();
while (cin >> N >> B)
{
Cal();
}
return 0;
}
|
Markdown
|
UTF-8
| 2,927 | 2.765625 | 3 |
[] |
no_license
|
# Article L452-2
Dans le cas mentionné à l'article précédent, la victime ou ses ayants droit reçoivent une majoration des indemnités qui leur
sont dues en vertu du présent livre.
Lorsqu'une indemnité en capital a été attribuée à la victime, le montant de la majoration ne peut dépasser le montant de
ladite indemnité.
Lorsqu'une rente a été attribuée à la victime, le montant de la majoration est fixé de telle sorte que la rente majorée
allouée à la victime ne puisse excéder, soit la fraction du salaire annuel correspondant à la réduction de capacité, soit le
montant de ce salaire dans le cas d'incapacité totale.
En cas d'accident suivi de mort, le montant de la majoration est fixé sans que le total des rentes et des majorations servies
à l'ensemble des ayants droit puisse dépasser le montant du salaire annuel ; lorsque la rente d'un ayant droit cesse d'être
due, le montant de la majoration correspondant à la ou aux dernières rentes servies est ajusté de façon à maintenir le
montant global des rentes majorées tel qu'il avait été fixé initialement ; dans le cas où le conjoint, le partenaire d'un
pacte civil de solidarité ou le concubin survivant recouvre son droit à la rente en application du troisième alinéa de
l'article L. 434-9, la majoration dont il bénéficiait est rétablie à son profit.
Le salaire annuel et la majoration visée au troisième et au quatrième alinéa du présent article sont soumis à la
revalorisation prévue pour les rentes par l'article L. 434-17.
La majoration est payée par la caisse, qui en récupère le capital représentatif auprès de l'employeur dans des conditions
déterminées par décret.
**Nota:**
Loi n° 2012-1404 du 17 décembre 2012 article 86 II : Les dispositions sont applicables au titre des majorations de rente et
d'indemnités en capital ayant pris effet à compter du 1er avril 2013.
**Liens relatifs à cet article**
_Cité par_:
- Décret du 17 juin 1938 - art. 20-1 (V)
- Code de la sécurité sociale. - art. D241-2-3 (V)
- Code de la sécurité sociale. - art. D452-1 (V)
- Code de la sécurité sociale. - art. L256-4 (V)
- Code de la sécurité sociale. - art. L451-1 (M)
- Code de la sécurité sociale. - art. L452-4 (V)
- Code de la sécurité sociale. - art. L455-2 (M)
- Code de la sécurité sociale. - art. R143-21 (VT)
- Code de la sécurité sociale. - art. R452-1 (Ab)
- Code de la sécurité sociale. - art. R452-2 (V)
- Code rural - art. L753-8 (V)
- Code rural - art. L761-17 (V)
- Code rural ancien - art. 1251 (Ab)
- Code rural et de la pêche maritime - art. R751-71 (Ab)
_Modifié par_:
- Loi n°2012-1404 du 17 décembre 2012 - art. 86 (V)
_Anciens textes_:
- Code de la sécurité sociale L468 al. 1 ELEMENTS LEGISLATIFS
_Cite_:
- Code de la sécurité sociale. - art. L434-17
- Code de la sécurité sociale. - art. L434-9
|
C++
|
UTF-8
| 892 | 2.578125 | 3 |
[] |
no_license
|
#ifndef PLAYER_H
#define PLAYER_H
#include "Tile.h"
#include "string"
#include "Bag.h"
class Player {
Tile* own_tiles[no_of_tiles_for_player]{ nullptr };
int points = 0;
std::wstring name;
bool empty_tiles = true;
float scale_x = 1;
float scale_y = 1;
public:
struct EX_exchange_lack_of_tiles {};
Player(Bag &bag, std::wstring name);
~Player() = default;
void exchange_tiles(Bag &bag);
void get_tiles(Bag &bag);
std::wstring get_name();
int get_points();
void set_points(int p);
void set_name(std::wstring n);
Tile * get_tile(int index);
void set_tile(int index, Tile *t);
void set_empty_tiles(bool s);
void display_own_tiles(sf::RenderWindow &window);
Player & operator+=(int points);
Player & operator-=(int points);
bool any_last_used();
void reset_all_last_used_and_outline();
int get_no_free_tiles();
int count_points_from_tiles();
};
#endif
|
PHP
|
UTF-8
| 6,280 | 2.6875 | 3 |
[] |
no_license
|
<?php
$url = isset($_GET["url"]) ? $_GET["url"] : null;
$ispwaStudio = false;
// Normal case
$parseUrl = parse_url($url);
if (!$ispwaStudio) {
if (isset($parseUrl['path'])) {
if ($parseUrl['path'] !== '/') {
// if url is: https://abc.com/xyz/def/... -> check at: https://abc.com/
$ispwaStudio = checkPwaStudio(str_replace($parseUrl['path'], '/', $url));
}
}
}
if (!$ispwaStudio) {
// last character or url must be '/'
if (substr($url, -1) !== '/') {
$ispwaStudio = checkPwaStudio($url . '/');
} else {
$ispwaStudio = checkPwaStudio($url);
}
}
// Add www into base url
if (!$ispwaStudio && strpos($url, 'www') === false) {
// in case: url is not contain 'www' -> add 'www'
$parseUrl = parse_url(urlContainWww($url));
if (!$ispwaStudio) {
if (isset($parseUrl['path'])) {
if ($parseUrl['path'] !== '/') {
// if url is: https://abc.com/xyz/def/... -> check at: https://abc.com/
$ispwaStudio = checkPwaStudio(str_replace($parseUrl['path'], '/', urlContainWww($url)));
}
}
}
if (!$ispwaStudio) {
// last character or url must be '/'
if (substr(urlContainWww($url), -1) !== '/') {
$ispwaStudio = checkPwaStudio(urlContainWww($url) . '/');
} else {
$ispwaStudio = checkPwaStudio(urlContainWww($url));
}
}
}
if ($ispwaStudio) {
echo 'true';
} else {
echo 'false';
}
function checkPwaStudio($url)
{
$ispwaStudio = false;
if ($url) {
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_SSL_VERIFYPEER => false
));
$resp = curl_exec($curl);
curl_close($curl);
if ($resp === FALSE) {
// curl error
} else {
// find all couple tag: <script></script> that include string "client"
preg_match_all('/<script[^>]*>(.*?)<\/script[^>]*>/', $resp, $matches);
if (sizeof($matches)) {
foreach ($matches as $item) {
if (sizeof($item)) {
foreach ($item as $subItem) {
if (isset($subItem)) {
preg_match('/client/', $subItem, $matches_1);
if (sizeof($matches_1)) {
$subItemUrl = preg_replace('/<script.*src="/', '', $subItem);
$subItemUrl = preg_replace('/"><\/script>/', '', $subItemUrl);
if ($subItemUrl[0] === '/') {
$subItemUrl = substr($subItemUrl, 1);
}
$curl_1 = curl_init();
curl_setopt_array($curl_1, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url . $subItemUrl,
CURLOPT_SSL_VERIFYPEER => false
));
$resp_1 = curl_exec($curl_1);
curl_close($curl_1);
if ($resp_1 === FALSE) {
// curl error
} else {
if (strpos($resp_1, "M2_VENIA_BROWSER_PERSISTENCE") !== false || strpos($resp_1, "browserpersistence") !== false || strpos($resp_1, "NODE_ENV") !== false) {
$ispwaStudio = true;
break;
}
}
if (!$ispwaStudio) {
$parseUrl = parse_url($url);
if (isset($parseUrl['path'])) {
if ($parseUrl['path'] !== '/') {
$curl_2 = curl_init();
curl_setopt_array($curl_2, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => str_replace($parseUrl['path'], '/', $url) . $subItemUrl,
CURLOPT_SSL_VERIFYPEER => false
));
$resp_2 = curl_exec($curl_2);
curl_close($curl_2);
if ($resp_2 === FALSE) {
// curl error
} else {
if (strpos($resp_2, "M2_VENIA_BROWSER_PERSISTENCE") !== false || strpos($resp_2, "browserpersistence") !== false || strpos($resp_2, "NODE_ENV") !== false) {
$ispwaStudio = true;
break;
}
}
}
}
}
}
}
}
}
if ($ispwaStudio) {
break;
}
}
} else {
// curl error
}
}
}
return $ispwaStudio;
}
function urlContainWww($url)
{
$newUrl = null;
// url is: https://... or http://...
if (strpos($url, 'www') === false) {
if (strpos($url, 'https') !== false) {
$newUrl = str_replace('https://', 'https://www.', $url);
} else {
$newUrl = str_replace('http://', 'http://www.', $url);
}
}
return $newUrl;
}
|
Python
|
UTF-8
| 3,761 | 2.71875 | 3 |
[] |
no_license
|
from RssData import DataBase
from MeanFilter import MeanFilterClass
if __name__ == '__main__':
room = 'class'
# 概率字典
probability = {}
# 指纹库字典
finger_data = {}
# 点所有的count和字典
ap_count_data = {}
# 实时采集数据权重
all_online_count = 0
data_bayes = DataBase()
online_filter = MeanFilterClass()
# 获取指纹库的数据和实时过滤数据10s的数据
online_results = online_filter.MeanFilterMeasureData(10)
# 获取每个点的总的Count
ap_count = data_bayes.PlaceAPCount()
for item in ap_count:
ap_count_data[item[0]] = [item[1]]
for key, value in ap_count_data.items():
print(value[0])
# 获取实时数据权值
# for online_key, online_value in online_results.items():
# all_online_count += online_value[1]
for online_key, online_value in online_results.items():
finger_results = data_bayes.FingerMacAdressDataSelcet(online_key)
finger_data.clear()
# 指纹库比值计数
all_finger_count = 0
if finger_results == '':
continue
else:
for item in finger_results: # 将获取的指纹库,写入指纹库字典
finger_data[item[1]] = [item[0], item[2]]
# finger_data[place] = [rss_value, count]
for finger_data_key, finger_data_value in finger_data.items():
for ap_count_data_key, ap_count_data_value in ap_count_data.items():
# 当前AP的值与指纹库的值对比,取Δ<1的
delta_rss = finger_data_value[0] - online_value[0]
if abs(delta_rss) <= 3 and finger_data_key == ap_count_data_key:
probability[online_key, ap_count_data_key] = \
[finger_data_value[1] / ap_count_data_value[0], online_value[1] / 10]
# probability[mac_address, 地点] = [ P(点|AP),online_count ]
# 某个在线测试的AP在所有地点的概率 online_count 为信赖贝叶斯的权重
for item in probability.items():
print(item)
# 获取概率字典的地点
place = []
for probability_key, probability_value in probability.items():
place.append(probability_key[1])
place = sorted(set(place), key=place.index)
print(place)
# 统计出现位置的次数字典
place_dic = {}
for place_simple in place:
place_count = 0
for probability_key, probability_value in probability.items():
if place_simple == probability_key[1]:
place_count += 1
place_dic[place_simple] = [place_count]
# max_value = 0
for item in place_dic.items():
print(item)
# 计算每个点的概率,由上面的统计次数加权,求出最大概率出现的地点
P_dic = {}
for place_simple in place:
P = 1
for probability_key, probability_value in probability.items():
if place_simple == probability_key[1]:
P = (float(probability_value[0])*probability_value[1])*P
P_dic[place_simple] = P
for item in P_dic.items():
print(item)
print("--------------------------")
# 找出最小的键值对
P_min = (min(P_dic.items(), key=lambda x: x[1]))
del P_dic[P_min[0]]
if len(P_dic) > 1:
# 找出第二小的键值对
P_second = (min(P_dic.items(), key=lambda x: x[1]))
print("当前正在位置:")
# 求出同等数据量级下值大的
if P_second[1] / P_min[1] < 10:
print(P_second[0])
else:
print(P_min[0])
else:
print(P_min[0])
data_bayes.DbClose()
|
Java
|
UTF-8
| 2,314 | 2.640625 | 3 |
[] |
no_license
|
package lk.ac.mrt.cse.dbs.simpleexpensemanager.control;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import lk.ac.mrt.cse.dbs.simpleexpensemanager.control.exception.ExpenseManagerException;
import lk.ac.mrt.cse.dbs.simpleexpensemanager.data.AccountDAO;
import lk.ac.mrt.cse.dbs.simpleexpensemanager.data.impl.DatabaseAccountDAO;
import lk.ac.mrt.cse.dbs.simpleexpensemanager.data.impl.DatabaseTransactionDAO;
import lk.ac.mrt.cse.dbs.simpleexpensemanager.data.model.Account;
/**
* Created by bhanuka on 11/21/16.
*/
public class PersistentExpenseManager extends ExpenseManager {
private Context context;
public PersistentExpenseManager(Context context){
this.context = context;
try {
setup();
} catch (ExpenseManagerException e) {
e.printStackTrace();
}
}
/***
* This method should be implemented by the concrete implementation of this class. It will dictate how the DAO
* objects will be initialized.
*/
@Override
public void setup() throws ExpenseManagerException {
SQLiteDatabase myDatabase = context.openOrCreateDatabase("140381", context.MODE_PRIVATE, null);
myDatabase.execSQL("CREATE TABLE IF NOT EXISTS account(" +
"accountNumber VARCHAR PRIMARY KEY," +
"bank VARCHAR," +
"accountHolderName VARCHAR," +
"balance REAL" +
" );");
myDatabase.execSQL("CREATE TABLE IF NOT EXISTS transaction_Data(" +
"transactionId INTEGER PRIMARY KEY," +
"accountNumber VARCHAR," +
"type INT," +
"amount REAL," +
"date DATE," +
"FOREIGN KEY (accountNumber) REFERENCES account(accountNumber)" +
");");
AccountDAO accountDAO = new DatabaseAccountDAO(myDatabase);
setAccountsDAO(accountDAO);
setTransactionsDAO(new DatabaseTransactionDAO(myDatabase));
// Account dummyAcct1 = new Account("12345A", "Yoda Bank", "Anakin Skywalker", 10000.0);
// Account dummyAcct2 = new Account("78945Z", "Clone BC", "Obi-Wan Kenobi", 80000.0);
// getAccountsDAO().addAccount(dummyAcct1);
// getAccountsDAO().addAccount(dummyAcct2);
}
}
|
Java
|
UTF-8
| 9,972 | 2.34375 | 2 |
[] |
no_license
|
package optics.raytrace.research.skewLensImaging;
import java.awt.event.ActionEvent;
import javax.swing.JCheckBox;
import math.*;
import optics.raytrace.sceneObjects.CylinderMantle;
import optics.raytrace.sceneObjects.LensSurface;
import optics.raytrace.sceneObjects.RayTrajectoryCone;
import optics.raytrace.sceneObjects.Sphere;
import optics.raytrace.sceneObjects.solidGeometry.SceneObjectContainer;
import optics.raytrace.sceneObjects.solidGeometry.SceneObjectPrimitiveIntersection;
import optics.raytrace.surfaces.SurfaceColour;
import optics.raytrace.surfaces.SurfaceColourLightSourceIndependent;
import optics.raytrace.surfaces.RefractiveSimple;
import optics.raytrace.core.*;
import optics.raytrace.exceptions.SceneException;
import optics.raytrace.NonInteractiveTIMActionEnum;
import optics.raytrace.NonInteractiveTIMEngine;
import optics.raytrace.GUI.cameras.EditableOrthographicCameraSide;
import optics.raytrace.GUI.cameras.RenderQualityEnum;
import optics.raytrace.GUI.lowLevel.ApertureSizeType;
import optics.raytrace.GUI.lowLevel.LabelledDoublePanel;
/**
* Simulation of a combination of a perfectly collimating lens surface.
*
* @author Johannes Courtial, Jakub Belin
*/
public class CollimatingLensSurface extends NonInteractiveTIMEngine
{
// additional parameters
/**
* If true, shows a view from the side
*/
protected boolean sideView;
/**
* If true, show lens 1
*/
protected boolean showLens1;
/**
* If true, show lens 2
*/
protected boolean showLens2;
/**
* show sphere at the focus of lens 2
*/
protected boolean showSphere;
/**
* If true, show a number of light-ray trajectories
*/
protected boolean showTrajectories;
/**
* focal length of first lens
*/
protected double f1;
/**
* focal length of 2nd lens
*/
protected double f2;
/**
* thickness of the lens at the centre
*/
protected double lensThickness;
/**
* refractive index of the lens glass
*/
protected double refractiveIndex;
/**
* the maximum aperture radius of the two lenses
*/
protected double maxApertureRadius;
// internal variables
// GUI panels
private LabelledDoublePanel f1Panel, f2Panel, lensThicknessPanel, refractiveIndexPanel, maxApertureRadiusPanel;
private JCheckBox sideViewCheckBox, showLens1CheckBox, showLens2CheckBox, showSphereCheckBox, showTrajectoriesCheckBox;
/**
* Constructor.
* Sets all parameters.
*/
public CollimatingLensSurface()
{
// set all standard parameters, including those for the camera
super();
// set all parameters
f1 = 1;
f2 = 1;
lensThickness = 0.5;
refractiveIndex = 1.5;
maxApertureRadius = 0.2;
sideView = true;
showSphere = true;
showTrajectories = true;
showLens1 = true;
showLens2 = true;
renderQuality = RenderQualityEnum.DRAFT;
nonInteractiveTIMAction = NonInteractiveTIMActionEnum.INTERACTIVE;
windowTitle = "Dr TIM -- CollimatingLensSurface";
windowWidth = 1100;
windowHeight = 650;
// camera parameters are set in populateStudio()
}
@Override
public String getClassName()
{
return "CollimatingLensSurface " // the name
+ " f1 "+f1
+ " f2 "+f2
+ " lensThickness "+lensThickness
+ " refractiveIndex "+refractiveIndex
+ " maxApertureRadius "+maxApertureRadius
+ " ("
+ (showLens1?" L1":"")
+ (showLens2?" L2":"")
+ (showSphere?" sphere":"")
+ ((sideView && showTrajectories)?" trajectories":"")
+ " shown)"
+ (sideView?" (side view)":"")
;
}
@Override
public void populateStudio()
throws SceneException
{
super.populateSimpleStudio();
SceneObjectContainer scene = (SceneObjectContainer)studio.getScene();
// add the lens surfaces, which will be surfaces in a glass cylinder
// create a scene-object-primitive intersection, ...
SceneObjectPrimitiveIntersection lens = new SceneObjectPrimitiveIntersection(
"Scene-object-primitive intersection", // description
scene, // parent
studio
);
scene.addSceneObject(lens);
// ... and add the cylinder, ...
lens.addPositiveSceneObjectPrimitive(new CylinderMantle(
"cylinder providing maximum lens aperture", // description
new Vector3D(0, 0, -10), // startPoint
new Vector3D(0, 0, 10), // endPoint
maxApertureRadius, // radius
new RefractiveSimple(refractiveIndex, SurfacePropertyPrimitive.DEFAULT_TRANSMISSION_COEFFICIENT, false), // surfaceProperty
lens, // parent
studio
));
LensSurface lensSurface1 = new LensSurface(
"Lens surface 1", // description
new Vector3D(0, 0, -0.5*lensThickness-f1), // focal point
f1, // focalDistance
refractiveIndex, // refractiveIndex
new Vector3D(0, 0, -1), // opticalAxisDirectionOutwards
SurfacePropertyPrimitive.DEFAULT_TRANSMISSION_COEFFICIENT, // transmissionCoefficient
false, // shadowThrowing
lens, // parent
studio
);
// lensSurface1.setSurfaceProperty(Reflective.PERFECT_MIRROR);
// lensSurface1.setSurfaceProperty(SurfaceColour.CYAN_MATT);
if(showLens1) lens.addPositiveSceneObjectPrimitive(lensSurface1);
LensSurface lensSurface2 = new LensSurface(
"Lens surface 2", // description
new Vector3D(0, 0, 0.5*lensThickness+f2), // principal point
f2, // focalDistance
refractiveIndex, // refractiveIndex
new Vector3D(0, 0, 1), // opticalAxisDirectionOutwards
SurfacePropertyPrimitive.DEFAULT_TRANSMISSION_COEFFICIENT, // transmissionCoefficient
false, // shadowThrowing
lens, // parent
studio
);
// lensSurface.setSurfaceProperty(SurfaceColour.GREEN_SHINY);
if(showLens2) lens.addPositiveSceneObjectPrimitive(lensSurface2);
if(sideView && showTrajectories) scene.addSceneObject(new RayTrajectoryCone(
"ray cone", // description
new Vector3D(0, 0, -0.5*lensThickness-f1), // cone apex
(f1<0?2*f1:0), // start a distance 10 in front of the cone apex
0, // startTime
new Vector3D(0, 0, 1), // axisDirection
MyMath.deg2rad(10), // coneAngle
10, // numberOfRays
0.01, // rayRadius
SurfaceColourLightSourceIndependent.RED, // surfaceProperty
100, // maxTraceLevel
scene, // parent
studio
));
if(showSphere) scene.addSceneObject(new Sphere(
"tiny sphere, imaged to camera", // description
new Vector3D(0, 0, 0.5*lensThickness+f2), // centre
0.01, // radius
SurfaceColour.YELLOW_MATT, // surfaceProperty
scene, // parent
studio
));
cameraMaxTraceLevel = 100;
cameraPixelsX = 640;
cameraPixelsY = 480;
if(sideView)
{
studio.setCamera(new EditableOrthographicCameraSide(
"Side view",
0, // yCentre
0, // zCentre
4, // zLength
cameraPixelsX, cameraPixelsY, // logical number of pixels
cameraMaxTraceLevel, // maxTraceLevel
renderQuality.getAntiAliasingQuality() // anti-aliasing quality
));
}
else
{
cameraViewDirection = new Vector3D(0, 0, 1);
cameraViewCentre = new Vector3D(0, 0, 0);
cameraDistance = 0.5*lensThickness+f1; // camera is located at (0, 0, 0)
cameraFocussingDistance = 0.5*lensThickness+f1;
cameraHorizontalFOVDeg = 20;
cameraApertureSize =
ApertureSizeType.PINHOLE;
// ApertureSizeType.SMALL;
studio.setCamera(getStandardCamera());
}
}
@Override
protected void createInteractiveControlPanel()
{
super.createInteractiveControlPanel();
// testCheckBox = new JCheckBox("Test");
// testCheckBox.setSelected(test);
// testCheckBox.addActionListener(this);
// interactiveControlPanel.add(testCheckBox);
f1Panel = new LabelledDoublePanel("f_1");
f1Panel.setNumber(f1);
interactiveControlPanel.add(f1Panel, "span");
f2Panel = new LabelledDoublePanel("f_2");
f2Panel.setNumber(f2);
interactiveControlPanel.add(f2Panel, "span");
lensThicknessPanel = new LabelledDoublePanel("lens thickness");
lensThicknessPanel.setNumber(lensThickness);
interactiveControlPanel.add(lensThicknessPanel, "span");
refractiveIndexPanel = new LabelledDoublePanel("refractive index");
refractiveIndexPanel.setNumber(refractiveIndex);
interactiveControlPanel.add(refractiveIndexPanel, "span");
maxApertureRadiusPanel = new LabelledDoublePanel("max aperture radius");
maxApertureRadiusPanel.setNumber(maxApertureRadius);
interactiveControlPanel.add(maxApertureRadiusPanel, "span");
sideViewCheckBox = new JCheckBox("Side view");
sideViewCheckBox.setSelected(sideView);
interactiveControlPanel.add(sideViewCheckBox, "span");
showLens1CheckBox = new JCheckBox("Show lens 1");
showLens1CheckBox.setSelected(showLens1);
interactiveControlPanel.add(showLens1CheckBox, "span");
showLens2CheckBox = new JCheckBox("Show lens 2");
showLens2CheckBox.setSelected(showLens2);
interactiveControlPanel.add(showLens2CheckBox, "span");
showSphereCheckBox = new JCheckBox("Show sphere at focus of lens 2");
showSphereCheckBox.setSelected(showSphere);
interactiveControlPanel.add(showSphereCheckBox, "span");
showTrajectoriesCheckBox = new JCheckBox("Show trajectories (side view only)");
showTrajectoriesCheckBox.setSelected(showTrajectories);
interactiveControlPanel.add(showTrajectoriesCheckBox, "span");
}
@Override
protected void acceptValuesInInteractiveControlPanel()
{
f1 = f1Panel.getNumber();
f2 = f2Panel.getNumber();
lensThickness = lensThicknessPanel.getNumber();
refractiveIndex = refractiveIndexPanel.getNumber();
maxApertureRadius = maxApertureRadiusPanel.getNumber();
sideView = sideViewCheckBox.isSelected();
showLens1 = showLens1CheckBox.isSelected();
showLens2 = showLens2CheckBox.isSelected();
showSphere = showSphereCheckBox.isSelected();
showTrajectories = showTrajectoriesCheckBox.isSelected();
}
@Override
public void actionPerformed(ActionEvent e)
{
super.actionPerformed(e);
// if(e.getSource().equals(testCheckBox))
// {
// setTest(testCheckBox.isSelected());
// // render();
// }
}
public static void main(final String[] args)
{
(new CollimatingLensSurface()).run();
}
}
|
Java
|
UTF-8
| 7,693 | 3.234375 | 3 |
[] |
no_license
|
package prototype.core;
import java.util.Random;
import java.util.Scanner;
import main.Game;
import misc.Tools;
import prototype.being.Alloy;
import prototype.being.Ray;
import prototype.being.Bug;
import prototype.items.ConcreteBasicItem;
import prototype.items.Inventory;
import prototype.items.BugHammer;
import prototype.room.*;
public class PrototypeGame extends Game {
//end game condition
public static boolean endGame = false;
/**
* This method is called to start the game
*/
public void startGame() {
//Create Rooms
EntryRoom entryRoom = new EntryRoom();
CockpitRoom cockpit = new CockpitRoom();
EngineRoom engineRoom = new EngineRoom();
CargoRoom cargoBay = new CargoRoom();
//Create Layout
entryRoom.doors.add(cockpit);
entryRoom.doors.add(engineRoom);
entryRoom.doors.add(cargoBay);
cockpit.doors.add(entryRoom);
engineRoom.doors.add(entryRoom);
cargoBay.doors.add(entryRoom);
cargoBay.doors.add(engineRoom);
engineRoom.doors.add(cargoBay);
//Create and Place Beings
Ray ray = new Ray(entryRoom);
Alloy alloy = new Alloy(cockpit);
Bug bug = new Bug(cargoBay);
//Update Room Beings List
entryRoom.beings.add(ray);
cockpit.beings.add(alloy);
cargoBay.getBeings().add(bug);
//Instantiating Ray's Inventory:
Inventory rayInventory = new Inventory();
rayInventory.BasicInventory();
//Instantiating Room Inventories:
ConcreteBasicItem cockpitPamphlet = new ConcreteBasicItem("Pamphlet for the DXP Diamond Bar", "colorful folded paper");
ConcreteBasicItem cockpitSnack = new ConcreteBasicItem("DXP Diamond Bar Snacks!", "hard candies in various shades of blue");
ConcreteBasicItem blankSpace = new ConcreteBasicItem("Empty", "there is nothing here");
BugHammer bugHammer = new BugHammer();
entryRoom.items.add(blankSpace);
cockpit.items.add(blankSpace);
//cockpit.items.add(cockpitPamphlet);
//cockpit.items.add(cockpitSnack);
engineRoom.items.add(blankSpace);
engineRoom.items.add(bugHammer);
cargoBay.items.add(blankSpace);
//Introductory Text
System.out.println("------------------------------------------------------------");
System.out.println("");
System.out.println("You find yourself waking up in a vacant-looking space ship..." +
"what were you\ndoing here, again? You see the name 'Ray' printed on your" +
" spacesuit. As you\nlook around, you see a plaque above a door calling" +
" this space 'Entry Room'.\nThis doesn't satisfy your questions though...");
//this starts the command line interactions with the player
makeChoice(ray, alloy, bug, rayInventory);
}
/**
* This method is called to end the game
* @param being is the being that just died, determining how the game ends
*/
public static void endGame(BasicBeing being) {
if(being instanceof Ray) {
System.out.println("How sad, Ray's space adventures have come to an end!");
}
else if(being instanceof Bug) {
System.out.println("Our hero has saved the day, hurrah! Now work can"
+ " begin on all \nthose ship feature requests you've "
+ "been receiving from Alloy...");
}
endGame = true;
}
/**
* This provides transition text for easier reading
*/
public static void transitionText() {
Scanner scan = new Scanner(System.in);
System.out.println();
System.out.println("Press 'Enter' to continue");
scan.nextLine();
}
/**
* This allows the user to make choices and advance through the game
*/
public void makeChoice(Ray ray, Alloy alloy, Bug bug, Inventory rayInventory) {
//this forever loop ensures the game continually presents choices to the user
while(!endGame) {
//If the bug is present, there is a 50% chance the bug will attack either
// Ray or Alloy each time makeChoice is called
if (bug.getLocation() == ray.getLocation()) {
Random rand = new Random();
//decide if the bug will attack
if (rand.nextInt(2) == 0) {
//decide if it will attack Ray or Alloy
if (alloy.getLocation() == ray.getLocation()) {
if (rand.nextInt(2) == 0) {
System.out.println("The bug just bit you! Ouch!");
ray.changeHealth(-10);
} else {
System.out.println("The bug just bit Alloy! Ouch!");
alloy.changeHealth(-10);
}
} else {
System.out.println("The bug just bit you! Ouch!");
ray.changeHealth(-10);
}
transitionText();
}
//the game will end if endGame is true
if (endGame) {
break;
}
}
System.out.println();
System.out.println("You are in the " + ray.getLocation().getName() + ".");
System.out.println();
System.out.println("What do you want to do?");
System.out.println();
System.out.println("1 - Inspect the room.");
System.out.println("2 - Inspect the items you are carrying.");
System.out.println("3 - Go to another room.");
// this will print out interaction options if there is another being in the room
int choiceNumber = 4;
int offset = choiceNumber;
for (int i = 0; i < ray.getLocation().getBeings().size(); i++) {
// make sure we only try to interact with a being that isn't Ray
if (!(ray.getLocation().getBeings().get(i) instanceof Ray)) {
System.out.println(choiceNumber + " - Interact with " +
ray.getLocation().getBeings().get(i).getName() + ".");
choiceNumber++;
}
}
System.out.println();
int choice = Tools.getWholeNumberInput();
System.out.println();
//Displays the contents of the room's inventory
//This needs to somehow determine both Ray's location and call the array for that location
if (choice == 1) {
System.out.println("This room contains:");
if(ray.getLocation().items.size() == 1){
System.out.println(" Nothing!");
transitionText();
}
else{
for (int i = 1; i < ray.getLocation().items.size(); i++) {
System.out.print(" ");
//This is a debugging print and won't be needed later on if we can work out
//how to safely implement an inventory management system that takes
//into account arrays starting with 0
System.out.print(i + ": ");
//This prints out the item at the i location
System.out.println(ray.getLocation().items.get(i));
}
System.out.println();
System.out.println("Would you like to pick up an item?");
//System.out.println("Would you like to pick up or drop an item?");
System.out.println("1. Pick up");
//System.out.println("2. Drop");
System.out.println("2. No");
//System.out.println("3. No");
int itemChoice = Tools.getWholeNumberInput();
//Moving an item from the room's inventory to Ray's inventory
if (itemChoice == 1) {
Inventory.InventoryPickup(ray, rayInventory);
} //else if (itemChoice == 2) {
//Inventory.InventoryDrop(ray, rayInventory);
//}
}
}
// Displays the contents of Ray's inventory.
else if (choice == 2) {
rayInventory.InventoryList();
System.out.println();
transitionText();
}
else if(choice==3) {
ray.goToAnotherRoom(alloy, bug);
}
// check if the choice is to interact with the other being
else if(choice <= choiceNumber) {
// don't interact with Ray in the room's being list
if(ray.getLocation().getBeings().get(choice-offset) instanceof Ray) {
ray.getLocation().getBeings().get(choice-offset+1).interact();
}
else {
ray.getLocation().getBeings().get(choice-offset).interact();
}
}
else {
System.out.println("You must be confused, that isn't an option.");
}
}
}
}
|
C++
|
UTF-8
| 1,451 | 2.96875 | 3 |
[] |
no_license
|
#include "Wall.h"
Wall::Wall(point v1, point v2) {
vertexes.first = v1;
vertexes.second = v2;
hp = 100;
width = 5;
lenght = sqrt(pow(v2.x - v1.x, 2) + pow(v2.y - v1.y, 2));
line[0] = sf::Vertex(sf::Vector2f(v1.x, v1.y));
line[1] = sf::Vertex(sf::Vector2f(v2.x, v2.y));
rectangle.setSize(sf::Vector2f(sqrt(pow(v2.x - v1.x, 2) + pow(v2.y - v1.y, 2)), width));
if (v2.x - v1.x >= 0.01)
angle = atan((v2.y - v1.y) / (v2.x - v1.x));
else if (v2.x - v1.x <= -0.01)
angle = 3.14159 + atan((v2.y - v1.y) / (v2.x - v1.x));
else
angle = 3.14159 / 2. * (double)(v2.y - v1.y > 0 ? 1 : -1);
rectangle.rotate(angle * 180. / 3.14159);
rectangle.setPosition(v1.x + width / 2. * sin(angle), v1.y - width / 2. * cos(angle));
}
void Wall::changeHp(double damage) {
hp = hp + damage;
if (hp < 0)
hp = 0;
if (hp > 100)
hp = 100;
cout << "new hp = " << hp << endl;
}
void Wall::makeDoorway(double startcoord, double doorsize) {
sf::RectangleShape temp;
temp.setSize(sf::Vector2f(doorsize, width));
temp.rotate(angle * 180. / 3.14159);
temp.setPosition(vertexes.first.x + width / 2. * sin(angle) + startcoord * cos(angle), vertexes.first.y - width / 2. * cos(angle) + startcoord * sin(angle));
sf::Color black = sf::Color::Black;
temp.setFillColor(black);
doorwaypars.push_back({ startcoord,doorsize });
doorway.push_back(temp);
}
|
Markdown
|
UTF-8
| 2,229 | 3.203125 | 3 |
[
"Elastic-2.0"
] |
permissive
|
---
title: Screenshot
---
At any point during or after program execution, you can
take a screenshot of what appears on its virtual terminal.
favoritecolor.py:
```python
import sys
answer = input("favorite color:")
sys.stdout.write(answer.upper())
sys.stdout.flush()
```
With code:
```python
from icommandlib import ICommand, IProcessTimeout
from commandlib import python
process = ICommand(python("favoritecolor.py")).run()
process.wait_until_output_contains("favorite color:")
process.send_keys("red\n")
process.wait_until_output_contains("RED")
```
## Taking a screenshot
```python
with open("screenshot-before-finish.txt", "w") as handle:
handle.write(process.screenshot())
process.wait_for_finish()
with open("stripshot-after-finish.txt", "w") as handle:
handle.write(process.stripshot())
```
* When the code is run to completion.
The file contents of `screenshot-before-finish.txt` will then be:
```
favorite color:red
RED
```
The file contents of `stripshot-after-finish.txt` will then be:
```
favorite color:red
RED
```
## Waiting for stripshot to match string and succeeding
```python
process.wait_for_stripshot_to_match("favorite color:red\nRED")
process.wait_for_finish()
```
* When the code is run to completion.
## Waiting for stripshot to match string and failing
With code:
```python
from icommandlib import ICommand, IProcessTimeout
from commandlib import python
process = ICommand(python("favoritecolor.py")).run()
process.wait_until_output_contains("favorite color:")
```
```python
try:
process.wait_for_stripshot_to_match("notthis", timeout=0.1)
except IProcessTimeout as error:
with open("timeout-stripshot.txt", "w") as handle:
handle.write("Did not match. This was the output instead:\n")
handle.write(error.stripshot)
```
* When the code is run to completion.
The file contents of `timeout-stripshot.txt` will then be:
```
Did not match. This was the output instead:
favorite color:
```
!!! note "Executable specification"
Documentation automatically generated from
<a href="https://github.com/crdoconnor/icommandlib/blob/master/hitch/story/screenshot.story">screenshot.story
storytests.</a>
|
C#
|
UTF-8
| 9,034 | 3.03125 | 3 |
[] |
no_license
|
using DAL.Mapping;
using DAL.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;
namespace DAL
{
public class UserDAO
{
//Error logging
private static ErrorLogger logger = new ErrorLogger();
//Mapper
private static UserMapper mapper = new UserMapper();
//SQL Connection
private readonly string connectionStrings;
public UserDAO(string connectionString)
{
connectionStrings = connectionString;
}
//View all users.
public List<UserDO> ViewAllUsers()
{
List<UserDO> displayUsers = new List<UserDO>();
try
{
using (SqlConnection connection = new SqlConnection(connectionStrings))
using (SqlCommand viewUsers = new SqlCommand("VIEW_ALL_USERS", connection))
{
viewUsers.CommandType = CommandType.StoredProcedure;
connection.Open();
using (SqlDataReader sqlDataReader = viewUsers.ExecuteReader())
{
while (sqlDataReader.Read())
{
UserDO user = mapper.MapReaderToSingle(sqlDataReader);
displayUsers.Add(user);
}
}
}
}
catch (SqlException sqlex)
{
logger.ErrorLog(MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, sqlex);
}
catch (Exception ex)
{
logger.ErrorLog(MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ex);
}
return displayUsers;
}
//View one user by username for logging in.
public UserDO ViewUser(string username)
{
UserDO user = new UserDO();
try
{
using (SqlConnection connection = new SqlConnection(connectionStrings))
using (SqlCommand command = new SqlCommand("VIEW_USER", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("@Username", username);
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.Read())
{
//Ternary to get proper values for the user.
user.UserId = reader["UserId"] != DBNull.Value ? (long)reader["UserId"] : 0;
user.Username = reader["Username"] != DBNull.Value ? (string)reader["Username"] : null;
user.Password = reader["Password"] != DBNull.Value ? (string)reader["Password"] : null;
user.FirstName = reader["FirstName"] != DBNull.Value ? (string)reader["FirstName"] : null;
user.Email = reader["Email"] != DBNull.Value ? (string)reader["Email"] : null;
user.Role = reader["Role"] != DBNull.Value ? (int)reader["Role"] : 0;
user.RoleName = reader["RoleName"] != DBNull.Value ? (string)reader["RoleName"] : null;
}
}
}
}
catch (SqlException sqlex)
{
logger.ErrorLog(MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, sqlex);
}
catch (Exception ex)
{
logger.ErrorLog(MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ex);
}
return user;
}
//View user by id.
public UserDO ViewUserByID(long userID)
{
UserDO user = new UserDO();
try
{
using (SqlConnection connection = new SqlConnection(connectionStrings))
using (SqlCommand viewOneTheory = new SqlCommand("VIEW_USER_BY_ID", connection))
{
viewOneTheory.CommandType = CommandType.StoredProcedure;
viewOneTheory.Parameters.AddWithValue("@UserId", userID);
connection.Open();
using (SqlDataReader reader = viewOneTheory.ExecuteReader())
{
if (reader.Read())
{
user = mapper.MapReaderToSingle(reader);
}
}
}
}
catch (SqlException sqlex)
{
logger.ErrorLog(MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, sqlex);
}
catch (Exception ex)
{
logger.ErrorLog(MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ex);
}
return user;
}
//Add a new user
public void RegisterUser(UserDO userRegister)
{
try
{
using (SqlConnection connection = new SqlConnection(connectionStrings))
using (SqlCommand command = new SqlCommand("REGISTER_USER", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("@Username", userRegister.Username);
command.Parameters.AddWithValue("@Password", userRegister.Password);
command.Parameters.AddWithValue("@FirstName", userRegister.FirstName);
command.Parameters.AddWithValue("@Email", userRegister.Email);
command.Parameters.AddWithValue("@RoleName", userRegister.RoleName);
connection.Open();
command.ExecuteNonQuery();
}
}
catch (SqlException sqlex)
{
logger.ErrorLog(MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, sqlex);
}
catch (Exception ex)
{
logger.ErrorLog(MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ex);
}
}
//Update a user
public void UpdateUser(UserDO userUpdate)
{
try
{
using (SqlConnection connection = new SqlConnection(connectionStrings))
using (SqlCommand command = new SqlCommand("UPDATE_USERS", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("@UserId", userUpdate.UserId);
command.Parameters.AddWithValue("@Username", userUpdate.Username);
command.Parameters.AddWithValue("@Password", userUpdate.Password);
command.Parameters.AddWithValue("@FirstName", userUpdate.FirstName);
command.Parameters.AddWithValue("@Email", userUpdate.Email);
command.Parameters.AddWithValue("@Role", userUpdate.Role);
command.Parameters.AddWithValue("@RoleName", userUpdate.RoleName);
connection.Open();
command.ExecuteNonQuery();
}
}
catch (SqlException sqlex)
{
logger.ErrorLog(MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, sqlex);
}
catch (Exception ex)
{
logger.ErrorLog(MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ex);
}
}
//Delete by id.
public void DeleteUser(long userID)
{
try
{
using (SqlConnection connection = new SqlConnection(connectionStrings))
using (SqlCommand deleteUser = new SqlCommand("DELETE_USER", connection))
{
deleteUser.CommandType = CommandType.StoredProcedure;
deleteUser.Parameters.AddWithValue("@UserId", userID);
connection.Open();
deleteUser.ExecuteNonQuery();
}
}
catch (SqlException sqlex)
{
logger.ErrorLog(MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, sqlex);
}
catch (Exception ex)
{
logger.ErrorLog(MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ex);
}
}
}
}
|
C#
|
UTF-8
| 574 | 3.25 | 3 |
[] |
no_license
|
private DateTime[] GetDatesOfSundays(DateTime DatMonth)
{
List<DateTime> lst = new List<DateTime>();
int iDayOffset = DatMonth.Day - 1;
DatMonth = DatMonth.AddDays(System.Convert.ToDouble(-DatMonth.Day + 1));
DateTime DatMonth2 = DatMonth.AddMonths(1).AddDays(System.Convert.ToDouble(-1));
while (DatMonth < DatMonth2)
{
if (DatMonth.DayOfWeek == System.DayOfWeek.Sunday)
lst.Add(DatMonth);
DatMonth = DatMonth.AddDays(1);
}
return lst.ToArray();
}
|
Java
|
UTF-8
| 2,216 | 2.171875 | 2 |
[] |
no_license
|
package com.luteh.kampusonlinenonakademik.ui.activities.dashboard;
import android.content.Context;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.luteh.kampusonlinenonakademik.common.AccountHelper;
import com.luteh.kampusonlinenonakademik.common.Common;
import com.luteh.kampusonlinenonakademik.model.User;
import durdinapps.rxfirebase2.RxFirebaseDatabase;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import timber.log.Timber;
import static com.luteh.kampusonlinenonakademik.common.AppConstant.ARG_USERS;
/**
* Created by Luthfan Maftuh on 14/01/2019.
* Email luthfanmaftuh@gmail.com
*/
public class DashboardPresenterImp implements IDashboardPresenter {
private Context context;
private IDashboardView iDashboardView;
public DashboardPresenterImp(Context context, IDashboardView iDashboardView) {
this.context = context;
this.iDashboardView = iDashboardView;
}
@Override
public void getUserInfo() {
if (AccountHelper.getToken() != null) {
Common.showProgressBar(context);
DatabaseReference databaseReference =
FirebaseDatabase.getInstance().getReference()
.child(ARG_USERS)
.child(AccountHelper.getToken());
RxFirebaseDatabase.observeSingleValueEvent(databaseReference,
dataSnapshot -> dataSnapshot.getValue(User.class))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(user -> {
Common.dismissProgressBar();
AccountHelper.saveUser(user);
Timber.d("User Info: %s", AccountHelper.getUser().toString());
iDashboardView.onRetrieveUserInfoSuccess();
}, throwable -> {
Common.dismissProgressBar();
Timber.e(throwable.getMessage());
}
);
}
}
}
|
C++
|
UTF-8
| 3,216 | 2.671875 | 3 |
[] |
no_license
|
/*
The file observationTest.cpp is part of the Harmony software.
Harmony is a software that provides tools for the detection of wildlife in series of images.
Copyright 2014-2016 WIPSEA SARL, contact@wipsea.com
Author(s) : Romain Dambreville
Creation date : 2015/03/26
Tous droits réservés - All rights reserved
Library used :
- Boost : custom license => http://www.boost.org/users/license.html
- OpenCV 3.0.0 : BSD 3-Clause license => http://opensource.org/licenses/BSD-3-Clause
*/
#include <gmock/gmock.h>
using ::testing::Eq;
#include <gtest/gtest.h>
using ::testing::Test;
#include <string>
#include <vector>
#include <fstream>
#include "Observation.hpp"
namespace testing {
class ObservationTest : public Test {
protected:
ObservationTest() {}
~ObservationTest() {}
virtual void SetUp() {}
virtual void TearDown() {}
Observation myObservation;
};
TEST_F(ObservationTest, constructor_withName) {
std::string imgPath("/home/romain/code/wildlifeCounter/images/logo.png");
Observation testObservation(imgPath);
EXPECT_THAT(testObservation.getFilePath(), Eq(imgPath));
EXPECT_THAT(testObservation.getItemCount(), Eq(static_cast<int>(0)));
}
TEST_F(ObservationTest, copy_constructor) {
std::string imgPath("/home/romain/code/wildlifeCounter/images/logo.png");
myObservation.setFilePath(imgPath);
Observation testObservation(myObservation);
EXPECT_THAT(testObservation.getFilePath(), Eq(imgPath));
EXPECT_THAT(testObservation.getItemCount(), Eq(static_cast<int>(0)));
}
TEST_F(ObservationTest, copy_operator) {
std::string imgPath("/home/romain/code/wildlifeCounter/images/logo.png");
myObservation.setFilePath(imgPath);
Observation testObservation = myObservation;
EXPECT_THAT(testObservation.getFilePath(), Eq(imgPath));
EXPECT_THAT(testObservation.getItemCount(), Eq(static_cast<int>(0)));
}
TEST_F(ObservationTest, addremoveItem) {
myObservation.addItem(cv::Point(50, 50), 4, "Turtle", 1);
myObservation.addItem(cv::Point(50, 25), 5, "Turtle", 1);
EXPECT_THAT(myObservation.getItemCount(), Eq(2)); // test addMember
myObservation.removeItem(0);
EXPECT_THAT(myObservation.getItemCount(), Eq(1)); // test removeMember
EXPECT_THAT(myObservation.getItemCount(), Eq(1));
Item it = *(myObservation.getItem(0));
EXPECT_THAT(it.getClass(), Eq("Turtle"));
}
TEST_F(ObservationTest, writeReadJsonItem) {
std::string imgPath("/home/romain/code/wildlifeCounter/images/logo.png");
myObservation.setFilePath(imgPath);
myObservation.addItem(cv::Point(50, 50), 4, "Turtle", 1);
myObservation.addItem(cv::Point(50, 25), 5, "Turtle", 1);
Json::Value save;
myObservation.writeJsonItem(&save);
std::ofstream out("testObservationItem.txt", std::ofstream::out);
out << save;
out.close();
std::ifstream in("testObservationItem.txt");
Json::Value reading;
in >> reading;
Observation test;
std::vector<std::string>* speciesList = new std::vector<std::string>;
test.readJsonItem(reading, speciesList);
delete speciesList;
in.close();
EXPECT_THAT(myObservation.getItemCount(), Eq(2));
EXPECT_THAT(myObservation.getFilePath(), Eq(imgPath));
Item it = *(myObservation.getItem(0));
EXPECT_THAT(it.getClass(), Eq("Turtle"));
}
} // namespace testing
|
Markdown
|
UTF-8
| 1,203 | 2.6875 | 3 |
[] |
no_license
|
---
title: About
author: Lynn Rainville
layout: page
date: 2007-02-03
menu: main
---
This blog was created by [Dr. Lynn Rainville](http://www.lynnrainville.org/) to share information about Albemarle County History (including the City of Charlottesville, Virginia). Human history in the area begins 1000s of years ago with Native American villages. This blog focuses on the past 300 years of history in the region, ca. 1700-2000 CE. Most importantly it's about getting out and exploring community histories and sharing local knowledge. Please contribute historical tidbits that pertain to Albemarle County. And don't forget to visit the homepage for this site to view links to local history websites.
Important note to Students & Researchers: This is an informal blog, NOT a fully cited, academic resource. If you are researching any of the topics discusssed here you should hunt down the original sources. While I will make every effort to fact-check my posts, the motivation behind this blog is to share my enthusiasm for local history and point out the abundant historic clues that surround us through place names, documents, landscapes, and artifacts. It is not a substitute for original, archeo-historic research.
|
TypeScript
|
UTF-8
| 4,385 | 2.609375 | 3 |
[] |
no_license
|
import { PREFIX_TABLOCK } from '../shared/utils';
import {
setLocalItems,
getAllLocalItems,
setLocalItem,
removeLocalItems,
} from '../shared/storageUtils';
const isChrome = BROWSER === 'chrome';
interface TablockCache {
tabId: number;
windowId: number;
index: number;
title: string;
url?: string;
}
interface TablockCaches {
[tabId: number]: TablockCache;
}
// Map tab position to IDs so that Tablock persists through sessions.
const tablockCaches: TablockCaches = {};
const previousTablockCaches: TablockCache[] = [];
let previousCrashed = false;
const debounce = <T extends any[]>(func: (...args: T) => any, wait = 250) => {
let timer: any;
return (...args: T) => {
clearTimeout(timer);
timer = setTimeout(() => func(...args), wait);
};
};
function _recalculateTabPositionToId(windowId: number) {
const tabIds = Object.keys(tablockCaches).map(parseInt);
chrome.tabs.query({ windowId }, function (tabs) {
tabs.forEach((tab) => {
const { index, id: tabId, url } = tab;
if (!tabId) return;
if (tabIds.includes(tabId)) {
const prev = tablockCaches[tabId];
tablockCaches[tabId] = {
tabId,
windowId,
index,
url,
title: prev.title,
};
}
});
// use local storage since it should not be synced
setLocalItems({
tablockCaches,
});
});
}
const recalculateTabPositionToId = debounce(
(windowId: number) => _recalculateTabPositionToId(windowId),
200
);
// Restore stored tablocks if possible
chrome.windows.onCreated.addListener(function (window) {
if (window.type !== 'normal') return;
window.tabs?.forEach((tab) => {
if (tab.id === undefined || tab.id in tablockCaches) return;
const matchedTab = previousTablockCaches.find(
(t) => t.url === tab.url && t.index === tab.index
);
if (!matchedTab) return;
const obj = {
...matchedTab,
windowId: window.id,
};
setLocalItem(`${PREFIX_TABLOCK}${tab.id}`, obj);
tablockCaches[tab.id] = obj;
});
});
chrome.tabs.onCreated.addListener(function (tab) {
recalculateTabPositionToId(tab.windowId);
});
// When closing a tab, clean up tab lock titles
chrome.tabs.onRemoved.addListener(function (tabId, info) {
// Do not delete Tablock info when the window is closing.
if (!info.isWindowClosing) {
recalculateTabPositionToId(info.windowId);
removeLocalItems(`${PREFIX_TABLOCK}${tabId}`);
}
});
// Keep track of tab position to tabID
chrome.tabs.onMoved.addListener(function (tabId, info) {
const windowId = info.windowId;
// no need for debounce
_recalculateTabPositionToId(windowId);
});
chrome.tabs.onDetached.addListener(function (tabId, info) {
const windowId = info.oldWindowId;
// no need for debounce
_recalculateTabPositionToId(windowId);
});
chrome.tabs.onAttached.addListener(function (tabId, info) {
const windowId = info.newWindowId;
// no need for debounce
_recalculateTabPositionToId(windowId);
});
chrome.tabs.onUpdated.addListener(function (tabId, info, tab) {
if (tabId in tablockCaches) {
tablockCaches[tabId] = {
tabId,
windowId: tab.windowId,
index: tab.index,
title: tab.title || '',
url: tab.url,
};
}
});
// Get tablock caches when extension startsup
chrome.runtime.onStartup.addListener(function () {
// tablock caches are stored locally
getAllLocalItems().then(function (items) {
const hasCrashed = items['crash'] as boolean | undefined;
const tlc = items['tablockCaches'] as Record<string, TablockCache>;
Object.keys(tlc).forEach((tabId) => {
previousTablockCaches.push({
...tlc[tabId],
});
});
previousCrashed = hasCrashed || false;
setLocalItem('crash', true);
});
getAllLocalItems().then(function (items) {
// Clean up residual Tablock keys stored in storage, since we fill those up through cache
Object.keys(items).forEach((itemKey) => {
if (itemKey.startsWith(PREFIX_TABLOCK)) {
removeLocalItems(itemKey);
}
});
});
});
if (isChrome) {
// Indicate that all states are saved successfully
chrome.runtime.onSuspend.addListener(function () {
removeLocalItems('crash');
});
// // Flag that won't be cleaned if crashed
chrome.runtime.onSuspendCanceled.addListener(function () {
setLocalItem('crash', true);
});
}
|
Java
|
UTF-8
| 381 | 2.421875 | 2 |
[
"Zlib"
] |
permissive
|
package com.ktxsoftware.kore;
public class KoreTouchEvent {
public int index;
public int x;
public int y;
public int action;
public static int ACTION_DOWN = 0;
public static int ACTION_MOVE = 1;
public static int ACTION_UP = 2;
public KoreTouchEvent(int index, int x, int y, int action) {
this.index = index;
this.x = x;
this.y = y;
this.action = action;
}
}
|
PHP
|
UTF-8
| 470 | 2.703125 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace App\Http\Library;
class Text
{
private $help_command;
private $false_command;
public function getHelpCommand()
{
$this->help_command = json_decode(file_get_contents(url('message/help.json')), true);
return $this->help_command;
}
public function getFalseCommand()
{
$this->false_command = json_decode(file_get_contents(url('message/false.json')), true);
return $this->false_command;
}
}
|
PHP
|
UTF-8
| 2,917 | 2.734375 | 3 |
[] |
no_license
|
<?php
if(isset($_POST['submit'])){
$dbHost = "localhost"; //Location Of Database usually its localhost
$dbUser = "myworld"; //Database User Name
$dbPass = "eituv7"; //Database Password
$dbDatabase = "myworld_paper_ballot"; //Database Name
$db = mysql_connect($dbHost,$dbUser,$dbPass)or die("Error connecting to database.");
//Connect to the databasse
mysql_select_db($dbDatabase, $db)or die("Couldn't select the database.");
//Selects the database
/*
The Above code can be in a different file, then you can place include'filename.php'; instead.
*/
//Lets search the databse for the user name and password
//Choose some sort of password encryption, I choose sha256
//Password function (Not In all versions of MySQL).
/*$usr1 = mysql_real_escape_string($_POST['s1']);
$usr2 = mysql_real_escape_string($_POST['s2']);
$usr3 = mysql_real_escape_string($_POST['s3']);
$usr4 = mysql_real_escape_string($_POST['s4']);
$usr5 = mysql_real_escape_string($_POST['s5']);
$usr6 = mysql_real_escape_string($_POST['s6']);
$usr7 = mysql_real_escape_string($_POST['s7']);
$usr8 = mysql_real_escape_string($_POST['s8']);
$usr = $usr1.$usr2.$usr3.$usr4.$usr5.$usr6.$usr7.$usr8;*/
$usr = mysql_real_escape_string($_POST['s']);
//echo $usr;
//echo "<br>";
$pas = mysql_real_escape_string($_POST['p1']);
//echo $pas;
//$pas = hash('sha256', mysql_real_escape_string($_POST['p1']));
$sql = mysql_query("SELECT * FROM volunteers
WHERE volunteer_id='$usr' AND
password='$pas'
LIMIT 1");
if(mysql_num_rows($sql) == 1 && $usr != "" && $pas != "" && $user != " " && $pas != " "){
$row = mysql_fetch_array($sql);
session_start();
$_SESSION['scoutid'] = $row['volunteer_id'];
/*$_SESSION['s1'] = $usr1;
$_SESSION['s2'] = $usr2;
$_SESSION['s3'] = $usr3;
$_SESSION['s4'] = $usr4;
$_SESSION['s5'] = $usr5;
$_SESSION['s6'] = $usr6;
$_SESSION['s7'] = $usr7;
$_SESSION['s8'] = $usr8;*/
$_SESSION['s'] = $usr;
$_SESSION['fname'] = $row['first_name'];
$_SESSION['lname'] = $row['last_name'];
$_SESSION['admin'] = $row['admin'];
$_SESSION['logged'] = TRUE;
if($_SESSION['admin'] == '1'){
echo $_SESSION['admin'];
header("Location: volunteers.php");
exit;
}else{
echo $_SESSION['admin'];
header("Location: media.php");
exit;
}
}else{
?><script>alert('Login failed: Invalid Volunteer ID and/or password.'); window.location = 'index.php'</script><?php // Modify to go to the page you would like
}
}else{ //If the form button wasn't submitted go to the index page, or login page
?><script>alert('Login failed: Bad Volunteer ID and/or password.'); window.location = 'index.php'</script><?php
exit;
}
?>
|
Python
|
UTF-8
| 879 | 2.90625 | 3 |
[] |
no_license
|
import sys
readline = sys.stdin.readline
MOD = 10 ** 9 + 7
INF = float('INF')
sys.setrecursionlimit(10 ** 5)
def main():
def query(x):
print(x)
ret = input()
if ret == "Vacant":
sys.exit()
return ret
n = int(readline())
l = 0
r = n - 1
op = {"Male": "Female", "Female": "Male"}
ls = query(l)
rs = query(r)
while r - l > 1:
mid = (l + r) // 2
ms = query(mid)
if (mid - l) % 2 == 0:
if ls == ms:
l = mid + 1
ls = op[ms]
else:
r = mid - 1
rs = op[ms]
else:
if ls == ms:
r = mid - 1
rs = op[ms]
else:
l = mid + 1
ls = op[ms]
query(l)
query(r)
if __name__ == '__main__':
main()
|
JavaScript
|
UTF-8
| 2,797 | 3.453125 | 3 |
[] |
no_license
|
/*
Player ( un simplu div ),
iar daca apasam arrow down, sa il miscam in jos
*/
class Player {
constructor(gameContainer) {
this.div = Player.display();
this.move();
this.gameContainer = gameContainer;
}
// logica de miscare
move() {
console.log('miscare', this)
// https://keycode.info/ de intrat pentru a testa codurile
document.addEventListener('keyup', (event) => {
// aici avem un arrow function,
// aceste "arrow function" sunt speciale pentru ca:
// -copiaza contextul de mai sus
// ( in cazul nostru, this din metoda miscare())
console.log(this);
const oldTop = parseInt(this.div.style.top);
const oldLeft = parseInt(this.div.style.left);
const minTop = parseInt(this.div.style.height);
const maxTop = gameContainer.offsetHeight - minTop;
const minLeft = parseInt(this.div.style.width);
const maxLeft = gameContainer.offsetWidth - minLeft;
// logica de miscare in jos - fara a iesi din container
if (event.keyCode === 40 && oldTop < maxTop) { // key down
this.div.style.top = `${oldTop + 20}px`;
console.log('arrow down', this.div.style.top);
// logica de miscare in sus - fara a iesi din container
} else if (event.keyCode === 38 && oldTop >= minTop){ // key up
this.div.style.top = `${oldTop - 20}px`;
console.log('arrow up', this.div.style.top);
// logica de miscare in stanga - fara a iesi din container
} else if (event.keyCode === 37 && oldLeft >= minLeft) { // key left
this.div.style.left = `${oldLeft - 20}px`;
console.log('arrow left', this.div.style.left);
// logica de miscare in dreapta - fara a iesi din container
} else if (event.keyCode === 39 && oldLeft < maxLeft) { // key right
this.div.style.left = `${oldLeft + 20}px`;
console.log('arrow right', this.div.style.left)
}
})
}
// afisarea div-ului
static display() {
const div = document.createElement('div');
const { style } = div;
style.width = "20px";
style.height = "20px";
style.backgroundColor = "red";
style.position = "absolute";
style.top = "20px";
style.left = "20px";
gameContainer.appendChild(div);
return div;
}
}
const gameContainer = document.getElementById('gameContainer');
const player = new Player(gameContainer);
document.getElementById('startGame').addEventListener('click', function(){
window.location.reload();
})
|
Python
|
UTF-8
| 11,733 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/bin/env python3
# Prints color cube for XTerm
import re
SYSTEM_TEMPLATE = "\x1B[{fgbg};5;{color}m-{color:02X}-\x1B[0m"
CUBE_TEMPLATE = "\x1B[{fgbg};5;{color}m{color:02X}\x1B[0m"
RAMP_TEMPLATE = CUBE_TEMPLATE
PALETTE_SYSTEM = {
0x0: [0x00, 0x00, 0x00],
0x1: [0x80, 0x00, 0x00],
0x2: [0x00, 0x80, 0x00],
0x3: [0x80, 0x80, 0x00],
0x4: [0x00, 0x00, 0x80],
0x5: [0x80, 0x00, 0x80],
0x6: [0x00, 0x80, 0x80],
0x7: [0xC0, 0xC0, 0xC0],
0x8: [0x80, 0x80, 0x80],
0x9: [0xFF, 0x00, 0x00],
0xA: [0x00, 0xFF, 0x00],
0xB: [0xFF, 0xFF, 0x00],
0xC: [0x00, 0x00, 0xFF],
0xD: [0xFF, 0x00, 0xFF],
0xE: [0x00, 0xFF, 0xFF],
0xF: [0xFF, 0xFF, 0xFF],
}
PALETTE_256 = {
0x10: [0x00, 0x00, 0x00],
0x11: [0x00, 0x00, 0x5F],
0x12: [0x00, 0x00, 0x87],
0x13: [0x00, 0x00, 0xAF],
0x14: [0x00, 0x00, 0xD7],
0x15: [0x00, 0x00, 0xFF],
0x16: [0x00, 0x5F, 0x00],
0x17: [0x00, 0x5F, 0x5F],
0x18: [0x00, 0x5F, 0x87],
0x19: [0x00, 0x5F, 0xAF],
0x1A: [0x00, 0x5F, 0xD7],
0x1B: [0x00, 0x5F, 0xFF],
0x1C: [0x00, 0x87, 0x00],
0x1D: [0x00, 0x87, 0x5F],
0x1E: [0x00, 0x87, 0x87],
0x1F: [0x00, 0x87, 0xAF],
0x20: [0x00, 0x87, 0xD7],
0x21: [0x00, 0x87, 0xFF],
0x22: [0x00, 0xAF, 0x00],
0x23: [0x00, 0xAF, 0x5F],
0x24: [0x00, 0xAF, 0x87],
0x25: [0x00, 0xAF, 0xAF],
0x26: [0x00, 0xAF, 0xD7],
0x27: [0x00, 0xAF, 0xFF],
0x28: [0x00, 0xD7, 0x00],
0x29: [0x00, 0xD7, 0x5F],
0x2A: [0x00, 0xD7, 0x87],
0x2B: [0x00, 0xD7, 0xAF],
0x2C: [0x00, 0xD7, 0xD7],
0x2D: [0x00, 0xD7, 0xFF],
0x2E: [0x00, 0xFF, 0x00],
0x2F: [0x00, 0xFF, 0x5F],
0x30: [0x00, 0xFF, 0x87],
0x31: [0x00, 0xFF, 0xAF],
0x32: [0x00, 0xFF, 0xD7],
0x33: [0x00, 0xFF, 0xFF],
0x34: [0x5F, 0x00, 0x00],
0x35: [0x5F, 0x00, 0x5F],
0x36: [0x5F, 0x00, 0x87],
0x37: [0x5F, 0x00, 0xAF],
0x38: [0x5F, 0x00, 0xD7],
0x39: [0x5F, 0x00, 0xFF],
0x3A: [0x5F, 0x5F, 0x00],
0x3B: [0x5F, 0x5F, 0x5F],
0x3C: [0x5F, 0x5F, 0x87],
0x3D: [0x5F, 0x5F, 0xAF],
0x3E: [0x5F, 0x5F, 0xD7],
0x3F: [0x5F, 0x5F, 0xFF],
0x40: [0x5F, 0x87, 0x00],
0x41: [0x5F, 0x87, 0x5F],
0x42: [0x5F, 0x87, 0x87],
0x43: [0x5F, 0x87, 0xAF],
0x44: [0x5F, 0x87, 0xD7],
0x45: [0x5F, 0x87, 0xFF],
0x46: [0x5F, 0xAF, 0x00],
0x47: [0x5F, 0xAF, 0x5F],
0x48: [0x5F, 0xAF, 0x87],
0x49: [0x5F, 0xAF, 0xAF],
0x4A: [0x5F, 0xAF, 0xD7],
0x4B: [0x5F, 0xAF, 0xFF],
0x4C: [0x5F, 0xD7, 0x00],
0x4D: [0x5F, 0xD7, 0x5F],
0x4E: [0x5F, 0xD7, 0x87],
0x4F: [0x5F, 0xD7, 0xAF],
0x50: [0x5F, 0xD7, 0xD7],
0x51: [0x5F, 0xD7, 0xFF],
0x52: [0x5F, 0xFF, 0x00],
0x53: [0x5F, 0xFF, 0x5F],
0x54: [0x5F, 0xFF, 0x87],
0x55: [0x5F, 0xFF, 0xAF],
0x56: [0x5F, 0xFF, 0xD7],
0x57: [0x5F, 0xFF, 0xFF],
0x58: [0x87, 0x00, 0x00],
0x59: [0x87, 0x00, 0x5F],
0x5A: [0x87, 0x00, 0x87],
0x5B: [0x87, 0x00, 0xAF],
0x5C: [0x87, 0x00, 0xD7],
0x5D: [0x87, 0x00, 0xFF],
0x5E: [0x87, 0x5F, 0x00],
0x5F: [0x87, 0x5F, 0x5F],
0x60: [0x87, 0x5F, 0x87],
0x61: [0x87, 0x5F, 0xAF],
0x62: [0x87, 0x5F, 0xD7],
0x63: [0x87, 0x5F, 0xFF],
0x64: [0x87, 0x87, 0x00],
0x65: [0x87, 0x87, 0x5F],
0x66: [0x87, 0x87, 0x87],
0x67: [0x87, 0x87, 0xAF],
0x68: [0x87, 0x87, 0xD7],
0x69: [0x87, 0x87, 0xFF],
0x6A: [0x87, 0xAF, 0x00],
0x6B: [0x87, 0xAF, 0x5F],
0x6C: [0x87, 0xAF, 0x87],
0x6D: [0x87, 0xAF, 0xAF],
0x6E: [0x87, 0xAF, 0xD7],
0x6F: [0x87, 0xAF, 0xFF],
0x70: [0x87, 0xD7, 0x00],
0x71: [0x87, 0xD7, 0x5F],
0x72: [0x87, 0xD7, 0x87],
0x73: [0x87, 0xD7, 0xAF],
0x74: [0x87, 0xD7, 0xD7],
0x75: [0x87, 0xD7, 0xFF],
0x76: [0x87, 0xFF, 0x00],
0x77: [0x87, 0xFF, 0x5F],
0x78: [0x87, 0xFF, 0x87],
0x79: [0x87, 0xFF, 0xAF],
0x7A: [0x87, 0xFF, 0xD7],
0x7B: [0x87, 0xFF, 0xFF],
0x7C: [0xAF, 0x00, 0x00],
0x7D: [0xAF, 0x00, 0x5F],
0x7E: [0xAF, 0x00, 0x87],
0x7F: [0xAF, 0x00, 0xAF],
0x80: [0xAF, 0x00, 0xD7],
0x81: [0xAF, 0x00, 0xFF],
0x82: [0xAF, 0x5F, 0x00],
0x83: [0xAF, 0x5F, 0x5F],
0x84: [0xAF, 0x5F, 0x87],
0x85: [0xAF, 0x5F, 0xAF],
0x86: [0xAF, 0x5F, 0xD7],
0x87: [0xAF, 0x5F, 0xFF],
0x88: [0xAF, 0x87, 0x00],
0x89: [0xAF, 0x87, 0x5F],
0x8A: [0xAF, 0x87, 0x87],
0x8B: [0xAF, 0x87, 0xAF],
0x8C: [0xAF, 0x87, 0xD7],
0x8D: [0xAF, 0x87, 0xFF],
0x8E: [0xAF, 0xAF, 0x00],
0x8F: [0xAF, 0xAF, 0x5F],
0x90: [0xAF, 0xAF, 0x87],
0x91: [0xAF, 0xAF, 0xAF],
0x92: [0xAF, 0xAF, 0xD7],
0x93: [0xAF, 0xAF, 0xFF],
0x94: [0xAF, 0xD7, 0x00],
0x95: [0xAF, 0xD7, 0x5F],
0x96: [0xAF, 0xD7, 0x87],
0x97: [0xAF, 0xD7, 0xAF],
0x98: [0xAF, 0xD7, 0xD7],
0x99: [0xAF, 0xD7, 0xFF],
0x9A: [0xAF, 0xFF, 0x00],
0x9B: [0xAF, 0xFF, 0x5F],
0x9C: [0xAF, 0xFF, 0x87],
0x9D: [0xAF, 0xFF, 0xAF],
0x9E: [0xAF, 0xFF, 0xD7],
0x9F: [0xAF, 0xFF, 0xFF],
0xA0: [0xD7, 0x00, 0x00],
0xA1: [0xD7, 0x00, 0x5F],
0xA2: [0xD7, 0x00, 0x87],
0xA3: [0xD7, 0x00, 0xAF],
0xA4: [0xD7, 0x00, 0xD7],
0xA5: [0xD7, 0x00, 0xFF],
0xA6: [0xD7, 0x5F, 0x00],
0xA7: [0xD7, 0x5F, 0x5F],
0xA8: [0xD7, 0x5F, 0x87],
0xA9: [0xD7, 0x5F, 0xAF],
0xAA: [0xD7, 0x5F, 0xD7],
0xAB: [0xD7, 0x5F, 0xFF],
0xAC: [0xD7, 0x87, 0x00],
0xAD: [0xD7, 0x87, 0x5F],
0xAE: [0xD7, 0x87, 0x87],
0xAF: [0xD7, 0x87, 0xAF],
0xB0: [0xD7, 0x87, 0xD7],
0xB1: [0xD7, 0x87, 0xFF],
0xB2: [0xD7, 0xAF, 0x00],
0xB3: [0xD7, 0xAF, 0x5F],
0xB4: [0xD7, 0xAF, 0x87],
0xB5: [0xD7, 0xAF, 0xAF],
0xB6: [0xD7, 0xAF, 0xD7],
0xB7: [0xD7, 0xAF, 0xFF],
0xB8: [0xD7, 0xD7, 0x00],
0xB9: [0xD7, 0xD7, 0x5F],
0xBA: [0xD7, 0xD7, 0x87],
0xBB: [0xD7, 0xD7, 0xAF],
0xBC: [0xD7, 0xD7, 0xD7],
0xBD: [0xD7, 0xD7, 0xFF],
0xBE: [0xD7, 0xFF, 0x00],
0xBF: [0xD7, 0xFF, 0x5F],
0xC0: [0xD7, 0xFF, 0x87],
0xC1: [0xD7, 0xFF, 0xAF],
0xC2: [0xD7, 0xFF, 0xD7],
0xC3: [0xD7, 0xFF, 0xFF],
0xC4: [0xFF, 0x00, 0x00],
0xC5: [0xFF, 0x00, 0x5F],
0xC6: [0xFF, 0x00, 0x87],
0xC7: [0xFF, 0x00, 0xAF],
0xC8: [0xFF, 0x00, 0xD7],
0xC9: [0xFF, 0x00, 0xFF],
0xCA: [0xFF, 0x5F, 0x00],
0xCB: [0xFF, 0x5F, 0x5F],
0xCC: [0xFF, 0x5F, 0x87],
0xCD: [0xFF, 0x5F, 0xAF],
0xCE: [0xFF, 0x5F, 0xD7],
0xCF: [0xFF, 0x5F, 0xFF],
0xD0: [0xFF, 0x87, 0x00],
0xD1: [0xFF, 0x87, 0x5F],
0xD2: [0xFF, 0x87, 0x87],
0xD3: [0xFF, 0x87, 0xAF],
0xD4: [0xFF, 0x87, 0xD7],
0xD5: [0xFF, 0x87, 0xFF],
0xD6: [0xFF, 0xAF, 0x00],
0xD7: [0xFF, 0xAF, 0x5F],
0xD8: [0xFF, 0xAF, 0x87],
0xD9: [0xFF, 0xAF, 0xAF],
0xDA: [0xFF, 0xAF, 0xD7],
0xDB: [0xFF, 0xAF, 0xFF],
0xDC: [0xFF, 0xD7, 0x00],
0xDD: [0xFF, 0xD7, 0x5F],
0xDE: [0xFF, 0xD7, 0x87],
0xDF: [0xFF, 0xD7, 0xAF],
0xE0: [0xFF, 0xD7, 0xD7],
0xE1: [0xFF, 0xD7, 0xFF],
0xE2: [0xFF, 0xFF, 0x00],
0xE3: [0xFF, 0xFF, 0x5F],
0xE4: [0xFF, 0xFF, 0x87],
0xE5: [0xFF, 0xFF, 0xAF],
0xE6: [0xFF, 0xFF, 0xD7],
0xE7: [0xFF, 0xFF, 0xFF],
}
PALETTE_GRAYSCALE = {
0xE8: [0x08, 0x08, 0x08],
0xE9: [0x12, 0x12, 0x12],
0xEA: [0x1C, 0x1C, 0x1C],
0xEB: [0x26, 0x26, 0x26],
0xEC: [0x30, 0x30, 0x30],
0xED: [0x3A, 0x3A, 0x3A],
0xEE: [0x44, 0x44, 0x44],
0xEF: [0x4E, 0x4E, 0x4E],
0xF0: [0x58, 0x58, 0x58],
0xF1: [0x62, 0x62, 0x62],
0xF2: [0x6C, 0x6C, 0x6C],
0xF3: [0x76, 0x76, 0x76],
0xF4: [0x80, 0x80, 0x80],
0xF5: [0x8A, 0x8A, 0x8A],
0xF6: [0x94, 0x94, 0x94],
0xF7: [0x9E, 0x9E, 0x9E],
0xF8: [0xA8, 0xA8, 0xA8],
0xF9: [0xB2, 0xB2, 0xB2],
0xFA: [0xBC, 0xBC, 0xBC],
0xFB: [0xC6, 0xC6, 0xC6],
0xFC: [0xD0, 0xD0, 0xD0],
0xFD: [0xDA, 0xDA, 0xDA],
0xFE: [0xE4, 0xE4, 0xE4],
0xFF: [0xEE, 0xEE, 0xEE],
}
CUBE_256 = '''
#00f#06f#08f#0af#0df#0ff
#60f#00d#06d#08d#0ad#0dd#0fd
#80f#60d#00a#06a#08a#0aa#0da#0fa
#a0f#80d#60a#008#068#088#0a8#0d8#0f8
#d0f#a0d#80d#608#006#066#086#0a6#0d6#0f6
#f0f#d0d#a0a#808#606#000#060#080#0a0#0d0#0f0#0f6#0f8#0fa#0fd#0ff
#f0d#d0a#a08#806#600#660#680#6a0#6d0#6f0#6f6#6f8#6fa#6fd#6ff#0df
#f0a#d08#a06#800#860#880#8a0#8d0#8f0#8f6#8f8#8fa#8fd#8ff#6df#0af
#f08#d06#a00#a60#a80#aa0#ad0#af0#af6#af8#afa#afd#aff#8df#6af#08f
#f06#d00#d60#d80#da0#dd0#df0#df6#df8#dfa#dfd#dff#adf#8af#68f#06f
#f00#f60#f80#fa0#fd0#ff0#ff6#ff8#ffa#ffd#fff#ddf#aaf#88f#66f#00f
#fd0#fd6#fd8#fda#fdd#fdf#daf#a8f#86f#60f
#66d#68d#6ad#6dd #fa0#fa6#fa8#faa#fad#faf#d8f#a6f#80f
#86d#66a#68a#6aa#6da #f80#f86#f88#f8a#f8d#f8f#d6f#a0f
#a6d#86a#668#688#6a8#6d8 #f60#f66#f68#f6a#f6d#f6f#d0f
#d6d#a6a#868#666#686#6a6#6d6#6d8#6da#6dd #f00#f06#f08#f0a#f0d#f0f
#d6a#a68#866#886#8a6#8d6#8d8#8da#8dd#6ad
#d68#a66#a86#aa6#ad6#ad8#ada#add#8ad#68d
#d66#d86#da6#dd6#dd8#dda#ddd#aad#88d#66d
#da6#da8#daa#dad#a8d#86d
#88a#8aa #d86#d88#d8a#d8d#a6d
#a8a#888#8a8#8aa #d66#d68#d6a#d6d
#a88#aa8#aaa#88a
#a88#a8a
'''.strip('\n')
def strip_escape_codes(text):
return re.sub('\x1B.*?m', '', text)
def join_templates(templates, separator=' '):
''' Merges text templates side by side. '''
templates = [template.split('\n') for template in templates]
template_sizes = []
for template in templates:
template_sizes.append(
max(len(strip_escape_codes(line)) for line in template))
merged_template = ['' for _ in templates[0]]
for i, template in enumerate(templates):
for j, line in enumerate(template):
real_length = len(strip_escape_codes(line))
merged_template[j] += line
merged_template[j] += ' ' * (template_sizes[i] - real_length)
merged_template[j] += separator
return '\n'.join(merged_template)
def render_system_colors():
''' Renders basic system color (i.e. the 16 color palette) ramp. '''
templates = []
for fgbg in [48, 38]:
template = ''
for color in range(16):
template += SYSTEM_TEMPLATE.format(fgbg=fgbg, color=color)
template += '\n' if color % 8 == 7 else ''
templates.append(template.strip())
print(join_templates(templates))
print()
def render_grayscale_ramp():
''' Renders basic grayscale ramp. '''
for fgbg in [48, 38]:
print('', end='')
for color in range(232, 256):
print(RAMP_TEMPLATE.format(fgbg=fgbg, color=color), end='')
print('')
print('')
def render_color_cube():
''' Renders the XTerm 216 color cube. '''
templates = []
for fgbg in [48, 38]:
def _replace_callback(match):
color = [int(x, 16) * 16 + int(x, 16) for x in match.group(1)]
min_diff = None
ret = ''
for key, other_color in PALETTE_256.items():
diff = sum(abs(other_color[i] - color[i]) for i in range(3))
if min_diff is None or diff < min_diff:
ret = CUBE_TEMPLATE.format(fgbg=fgbg, color=key)
min_diff = diff
return ret
template = re.sub(r'([^#\s]{3})', _replace_callback, CUBE_256)
template = re.sub('#', '', template)
template = re.sub(' ', ' ', template)
templates.append(template)
print(join_templates(templates))
def main():
render_system_colors()
render_grayscale_ramp()
render_color_cube()
if __name__ == '__main__':
main()
|
Java
|
UTF-8
| 300 | 2.6875 | 3 |
[] |
no_license
|
package com.simon.javase.interfacedemo.teacher_sporter;
public class BasketTeacher extends Teacher {
@Override
public void teach() {
System.out.println("篮球教练教学!");
}
@Override
public void eat() {
System.out.println("篮球教练吃饭");
}
}
|
Java
|
UTF-8
| 3,394 | 3.203125 | 3 |
[] |
no_license
|
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class App {
public static void main(String[] args) throws Exception {
String pattern = "abab";
String str = "redblueredblue";
boolean res = solution(pattern, str);
System.out.println(res);
// better solution
boolean res2 = wordPatternMatch(pattern, str);
System.out.println(res2);
}
public static boolean wordPatternMatch(String pattern, String str) {
Map<Character, String> map = new HashMap<>();
Set<String> set = new HashSet<>();
return isMatch(str, 0, pattern, 0, map, set);
}
private static boolean isMatch(String str, int i, String pattern, int j, Map<Character, String> map,
Set<String> set) {
if (i == str.length() && j == pattern.length())
return true;
if (i == str.length() || j == pattern.length())
return false;
char c = pattern.charAt(j);
if (map.containsKey(c)) {
String s = map.get(c);
if (!str.startsWith(s, i))
return false;
else
return isMatch(str, i + s.length(), pattern, j + 1, map, set);
}
for (int k = i; k < str.length(); k++) {
String p = str.substring(i, k + 1);
if (set.contains(p)) {
continue;
}
map.put(c, p);
set.add(p);
if (isMatch(str, k + 1, pattern, j + 1, map, set)) {
return true;
}
map.remove(c);
set.remove(p);
}
return false;
}
private static boolean solution(String pattern, String str) {
int len = pattern.length();
if (str.length() < len)
return false;
char[] c = pattern.toCharArray();
List<String[]> res = new LinkedList<>();
dfs(res, new String[len], str, 0);
for (String[] s : res) {
if (legal(c, s))
return true;
}
return false;
}
private static void dfs(List<String[]> res, String[] path, String str, int index) {
if (index == path.length) {
res.add(Arrays.copyOf(path, path.length));
return;
}
int l1 = str.length();
int l2 = path.length - index - 1;
int l = l1 - l2;
for (int i = 1; i <= l; i++) {
path[index] = str.substring(0, i);
dfs(res, path, str.substring(i), index + 1);
path[index] = null;
}
}
private static boolean legal(char[] c, String[] s) {
Map<Character, String> map = new HashMap<>();
Map<String, Character> map1 = new HashMap<>();
for (int i = 0; i < s.length; i++) {
if (!map.containsKey(c[i])) {
map.put(c[i], s[i]);
} else {
String cur = map.get(c[i]);
if (!cur.equals(s[i]))
return false;
}
if (!map1.containsKey(s[i])) {
map1.put(s[i], c[i]);
} else {
char cur = map1.get(s[i]);
if (cur != c[i])
return false;
}
}
return true;
}
}
|
Python
|
UTF-8
| 550 | 3.40625 | 3 |
[] |
no_license
|
# 프로그래머스 큰 수 만들기
def solution(number, k):
ans = [number[0]]
for i in range(1, len(number)):
if ans[-1] > number[i]:
ans.append(number[i])
else:
while True:
if k != 0 and len(ans) != 0 and number[i] > ans[-1]:
ans.pop(-1)
k -= 1
else:
ans.append(number[i])
break
if k != 0:
return "".join(ans)[:-k]
return "".join(ans)
print(solution("4177252841", 4))
|
Ruby
|
UTF-8
| 1,790 | 2.78125 | 3 |
[] |
no_license
|
require 'sinatra'
require 'sinatra/reloader'
require 'sqlite3'
require 'pry'
# show the add character form
get '/characters/add' do
erb :character_add
end
# add character to database
post '/characters/add' do
query = "INSERT INTO characters (first_name, last_name, age, gender, occupation, aliases, image) VALUES ('#{ params[:first_name] }', '#{ params[:last_name] }', #{ params[:age] }, '#{ params[:gender] }', '#{ params[:occupation] }', '#{ params[:aliases] }', '#{ params[:image] }')"
query_db(query)
redirect to('/characters')
end
# get all characters
get '/characters' do
query = 'SELECT * FROM characters'
@characters = query_db(query)
# @characters = result.first
# binding.pry
erb :characters
end
# get a character
get '/characters/:id' do
query = "SELECT * FROM characters WHERE id=#{ params[:id] }"
@character = query_db(query).first
erb :character_show
end
# delete a record from the database
get '/characters/:id/delete' do
query = "DELETE FROM characters WHERE id=#{ params[:id] }"
query_db(query)
redirect to('/characters')
end
# show edit form
get '/characters/:id/edit' do
query = "SELECT * FROM characters WHERE id=#{ params[:id] }"
result = query_db(query)
@character = result.first
erb :character_edit
end
post '/characters/:id' do
query = "UPDATE characters SET first_name='#{ params[:first_name] }', last_name='#{ params[:last_name] }', age=#{ params[:age] }, gender='#{ params[:gender] }', occupation='#{ params[:occupation] }', aliases='#{ params[:aliases] }', image='#{ params[:image] }' WHERE id=#{ params[:id] }"
query_db(query)
redirect to("/characters/#{ params[:id] }")
end
def query_db(sql)
db = SQLite3::Database.new('characters.db')
db.results_as_hash = true
puts(sql)
result = db.execute(sql)
end
|
Markdown
|
UTF-8
| 1,966 | 2.8125 | 3 |
[] |
no_license
|
---
layout: interior-post
title: Learn Experience
categories: experience-information-architecture
categoryheader: no
tags:
- Information Architecture
---
<p>On the Learn side of the site, we are proposing a dramatic departure from our past. Not because it’s novel, but because we think it’s right for our audience. The new “Learn” side will be flatter, simplified, and more adaptable than its predecessor. We have learned a lot over the last three years and need to build on that knowledge. We need to continue to learn and grow. And we need to continue to help our audience learn and grow and move through a challenging set of hurdles.</p>
<h3>Three big themes run through the architecture of the Learn experience:</h3>
<p><strong><a href="/experience-information-architecture/favor-most-needed-content/" title="Favor Most Needed Content">1. Favor the most needed content</a> </strong>- Based on data and research, get the most critical information into the hands of our users quickly.</p>
<p><strong><a href="/experience-information-architecture/flat-architecture/" title="Flat Architecture">2. Flatten our hierarchies</a></strong> - Reduce the number of steps people need to go through to get what they need, while building a system that is easily adaptable to change.</p>
<p><strong><a href="/experience-information-architecture/structure-our-content/" title="Structure Our Content">3. Structure our content</a></strong> - Think of content as data to make it findable, reusable and adaptable.</p>
<p><a href="../../images/Sitemap-Flows-Doc-04.png"><img width="1650" height="2550" src="../../images/Sitemap-Flows-Doc-04.png" alt="Sitemap-Flows-Doc-04" class="alignnone size-full wp-image-1349"></a></p>
<div class="article-end"><a title="Favor Most Needed Content" href="/experience-information-architecture/favor-most-needed-content/"><button type="button" class="btn btn-large">Next: Favor most needed content</button></a></div>
|
Ruby
|
UTF-8
| 312 | 3.140625 | 3 |
[] |
no_license
|
class Guest
attr_accessor :name, :money, :fav_song
def initialize(name, money, fav_song)
@name = name
@money = money
@fav_song = fav_song
end
def charge(amount)
return @money -= amount
end
def customer_can_afford_drink(drinks_hash, drink)
return @money <= drinks_hash[drink][:info].price
end
end
|
Java
|
UTF-8
| 5,034 | 2.265625 | 2 |
[] |
no_license
|
package frc.robot;
import edu.wpi.first.wpilibj.Joystick;
import edu.wpi.first.wpilibj2.command.button.JoystickButton;
import frc.robot.commands.climber.ClimberCommand;
import frc.robot.commands.climber.TurnOffClimberCommand;
import frc.robot.commands.compressor.StartCompressorCommand;
import frc.robot.commands.compressor.StopCompressorCommand;
import frc.robot.commands.driving.DirectDriveCommand;
import frc.robot.commands.index.IndexIntakeCommand;
import frc.robot.commands.index.IndexShooterCommand;
import frc.robot.commands.index.StopIndexCommand;
import frc.robot.commands.intake.IntakeCommand;
import frc.robot.commands.intake.IntakeOffCommand;
import frc.robot.commands.shooter.ShooterOnCommand;
import frc.robot.commands.tilt.CannonClimbMode;
import frc.robot.commands.tilt.CannonIntakeMode;
import frc.robot.commands.tilt.CannonShootMode;
import frc.robot.commands.tilt.StopTiltCommand;
import frc.robot.subsystems.CannonTiltSubsystem;
import frc.robot.subsystems.ClimberSubsystem;
import frc.robot.subsystems.DrivingSubsystem;
import frc.robot.subsystems.IntakeAndShootSubsystem;
import frc.robot.subsystems.PnuematicSubsystem;
import frc.robot.subsystems.WomfSubsystem;
public class RobotContainer {
// public XboxController1 controller1;
Joystick joshJoystick = new Joystick(2);
// XboxController controller1 = new
// XboxController(Constants.XBOX_CONTROLLER_1_PORT);
Joystick zachRightJoystick = new Joystick(0);
Joystick zachLeftJoystick = new Joystick(1);
DrivingSubsystem drivingSubsystem = new DrivingSubsystem();
ClimberSubsystem climberSubsystem = new ClimberSubsystem();
PnuematicSubsystem pnuematicSubsystem = new PnuematicSubsystem();
IntakeAndShootSubsystem intakeAndShootSubsystem = new IntakeAndShootSubsystem();
WomfSubsystem womfSubsystem = new WomfSubsystem();
CannonTiltSubsystem cannonTiltSubsystem = new CannonTiltSubsystem();
public RobotContainer() {
configureButtonBindings();
drivingSubsystem.setDefaultCommand(
new DirectDriveCommand(drivingSubsystem, () -> getLeftDrive(), () -> getRightDrive()));
}
public double getRightDrive() {
return zachRightJoystick.getY();
}
public double getLeftDrive() {
return zachLeftJoystick.getY();
}
private void configureButtonBindings() {
//womfButton, climberButton, cannonShoot, cannonIntake, climbModeCannon, cannonTiltIntake, cannonTiltShoot
final JoystickButton cannonTiltIntake = new JoystickButton(joshJoystick, 8);
final JoystickButton climberButton = new JoystickButton(joshJoystick, 6);
final JoystickButton climbModeCannon = new JoystickButton(joshJoystick, 12);
final JoystickButton cannonShoot = new JoystickButton(joshJoystick, 2);
final JoystickButton cannonIntake= new JoystickButton(joshJoystick, 7);
final JoystickButton indexerShoot= new JoystickButton(joshJoystick, 1);
final JoystickButton indexerIntake = new JoystickButton(joshJoystick, 9);
final JoystickButton compressor = new JoystickButton(zachRightJoystick, 1);
climberButton.whenPressed(new ClimberCommand(climberSubsystem));
climberButton.whenReleased(new TurnOffClimberCommand(climberSubsystem));
cannonTiltIntake.whenPressed(new CannonIntakeMode(cannonTiltSubsystem));
cannonTiltIntake.whenReleased(new StopTiltCommand(cannonTiltSubsystem));
climbModeCannon.whenPressed(new CannonClimbMode(cannonTiltSubsystem));
climbModeCannon.whenReleased(new StopTiltCommand(cannonTiltSubsystem));
// cannonTiltShoot.whenPressed(new CannonShootMode(cannonTiltSubsystem));
indexerIntake.whenPressed(new IndexIntakeCommand(intakeAndShootSubsystem));
indexerIntake.whenReleased(new StopIndexCommand(intakeAndShootSubsystem));
compressor.whenPressed(new StartCompressorCommand(pnuematicSubsystem));
compressor.whenReleased(new StopCompressorCommand(pnuematicSubsystem));
// cannonTiltShoot.whenReleased(new StopTiltCommand(cannonTiltSubsystem));
cannonShoot.whenPressed(new ShooterOnCommand(intakeAndShootSubsystem).alongWith(new CannonShootMode(cannonTiltSubsystem)));
cannonShoot.whenReleased(new IntakeOffCommand(intakeAndShootSubsystem).alongWith(new StopTiltCommand(cannonTiltSubsystem)));
cannonIntake.whenPressed(new IntakeCommand(intakeAndShootSubsystem));
cannonIntake.whenReleased(new StopTiltCommand(cannonTiltSubsystem).alongWith(new IntakeOffCommand(intakeAndShootSubsystem)));
indexerShoot.whenPressed(new IndexShooterCommand(intakeAndShootSubsystem));
indexerShoot.whenReleased(new StopIndexCommand(intakeAndShootSubsystem));
}
/**
* Use this to pass the autonomous command to the main {@link Robot} class.
*
* @return the command to run in autonomous
*/
// public Command getAutonomousCommand() {
// // An ExampleCommand will run in autonomous
// return autoDefault;
// }
}
|
Java
|
UTF-8
| 1,557 | 2.71875 | 3 |
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Layout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.TextField;
import java.security.cert.PKIXReason;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
/**
*
* @author ADMIN
*/
public class Boxlayour extends JFrame{
public Boxlayour() {
initUI();
}
public final void initUI(){
JPanel basic=new JPanel();
basic.setLayout(new BoxLayout(basic,BoxLayout.Y_AXIS));
add(basic);
basic.add(Box.createVerticalGlue());
basic.add(new TextField(" Tu hocj javaSwing"));
JPanel bottom=new JPanel();
bottom.setAlignmentX(Component.RIGHT_ALIGNMENT);
bottom.setLayout(new BoxLayout(bottom,BoxLayout.X_AXIS));
JButton ok=new JButton("OK");
JButton close=new JButton("CLOSE");
bottom.add(ok);
bottom.add(Box.createRigidArea(new Dimension(5,0)));
bottom.add(close);
bottom.add(Box.createRigidArea(new Dimension(15,0)));
basic.add(bottom);
basic.add(Box.createRigidArea(new Dimension(0,15)));
setTitle("Box layout");
setSize(300,200);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
}
}
|
Python
|
UTF-8
| 236 | 3.140625 | 3 |
[] |
no_license
|
# cook your dish here
from math import floor
t = int(input())
for _ in range(t):
n = int(input())
r,z = 1,0
remain = 1
while(remain != 0):
remain = floor(n/(5**r))
z += remain
r += 1
print(z)
|
Python
|
UTF-8
| 1,208 | 3.515625 | 4 |
[
"MIT"
] |
permissive
|
import time
import math
import operator
import sys
start = time.time()
# Returns the n factorial (n!) for the given argument.
# This is the same as the number of permutations for a list
# with n members.
def factorial(n):
if n == 1 or n == 0:
return 1
return reduce(operator.mul, xrange(2,n+1))
# Returns the number of _ordered_ k item subsets in the
# a list with n members.
#
# For example:
# n = 4, k = 2 = 4!/2! = 12 two element subsets in the list (1, 2, 3, 4):
# (1,2), (1,3), (1,4),
# (2,1), (2,3), (2,4),
# (3,1), (3,2), (3,4),
# (4,1), (4,2), (4, 3)
def permutations(n,k):
return factorial(n) / factorial(n-k)
# Returns the humber of _unordered_ k item subsets in the
# list with n members
#
# For example:
# n = 4, k=2 = n!/(k!(n-k)!) = 6 two element subsets for the list (1, 2, 3, 4)
# {1,2}, {1,3}, {1,4},
# {2,3}, {2,4}, {3,4}
def combinations(n, k):
return factorial(n)/(factorial(k)*factorial(n-k))
c = 0
for i in range(1, 101):
for j in range(1, i):
if combinations(i, j) > 1000000:
c += 1
print (i, c)
end = time.time() - start
print "Total time was " + str(end)+ " seconds"
|
Shell
|
UTF-8
| 2,026 | 3.640625 | 4 |
[
"MIT"
] |
permissive
|
#!/bin/bash
[[ ${CONFIG} ]] && CONFIG=$(printf "%q\n" "$(realpath "${CONFIG}")")
export PATH="${PATH}:/usr/lib/java-ebuilder/bin"
export EROOT=$(dirname /etc)
if [[ $# -gt 0 ]]; then
if [[ "$1" == "-h" || "$1" == "--help" ]]; then
echo This is a helper to automagically generate ebuild for
echo Maven artifacts defined in ${EROOT}/etc/java-ebuilder.conf
echo
echo Usage: movl [options] [target] ...
echo Options: please refer to \`make -h\`
echo Targets:
echo " all alias for stage2 and post-stage2"
echo " build alias for stage2 and post-stage2"
echo " stage1 resolve the dependency graph of the provided Maven artifact"
echo " stage2 generate ebuild files of the whole dep graph"
echo " force-stage2 force generate stage2 ebuild files"
echo " post-stage2 generate digests for ebuilds"
echo " clean-cache remove cache files"
echo " clean-stage1 remove stage1-related stuffs"
echo " clean-stage2 remove stage2-related stuffs"
echo " clean remove all the generated stuffs"
echo "Bash Variables:"
echo " CONFIG path to the config file"
echo " default: ${EROOT}/etc/java-ebuilder.conf"
echo " DEFAULT_CATEGORY the default category of the generated ebuilds"
echo " default: app-maven"
echo " MAVEN_NODEP set this variable to stop tree.sh from recursively resolving"
echo " the dependencies of MAVEN_ARTS"
echo " REPOSITORY where to find the pom and jar files"
echo " default: https://repo1.maven.org/maven2"
echo " TSH_NODEBUG set this variable to make \`movl build\` more silent"
exit
fi
else
movl -h
exit 0
fi
cd "${EROOT}/usr/lib/java-ebuilder/Makefiles"
make $@
|
Markdown
|
UTF-8
| 26,692 | 2.5625 | 3 |
[] |
no_license
|
# Basic Template Structure & Working
[](https://github.com/cicirello/pyaction/blob/master/LICENSE)
[](https://github.com/cicirello/pyaction/releases)
# AWS IAM USER
* HawkVisum_Deployment-CI for user based CI-CD Pipeline
* HawkVisum_Website_Ci-Cd-Proxy for proxt based CI-CD Pipeline
#### NOTE :: DON'T DELETE ANY OF THE USER.
### Dockerfile
* apk referes alpine package manager.
* The first app under copy is project directory in local environment.
* The second app under copy is project directory name in docker container.
* adduser --disabled-password --no-create-home app, this line will create a user by the name app.
* USER app, the name of the user provide above.
* apk add --update --no-cache postgresql-client; will download the postgresql client required for the connection of postgresql database.
* apk add --update --no-cache --virtual .tmp-deps; will consider only the main files and delete the dependencies to make the container light weight.
* mkdir -p /vol/web/static && \ considers the static files of application.
* mkdir -p /vol/web/media && \ considers the media files uplodaded post production.
* -R means recursive
### docker-compose.yml
* The services refer to create different containers named as app and db.
* Content refers the root directory.
* Ports refer to the working ports.
* The volumes refer the django project directory in local environment to the django directory in docker container
* THis will manually restart the server to consider the changes by docker.
* We named both directories with same name so don't get confused.
* It's a fake secret key updated under the environment variables; and debug=1 because we want to run the code in debug mode.
* Created new service called db, which uses the postgres database image. As we need a database for further usecases.
* depends_on=db will help in the network connection in between services.
* Created command under the build, becuase we want to make sure the process gets automated and follows a sequential method in running.
### Commands
* docker-compose run --rm app sh -c "django-admin startproject project name ." This will help in creating a djangoproject in root directory.
* docker-compose run --rm app sh -c "python manage.py startapp appname" This will help in creating the application using django cli.
* Every time we do any changes in the files related to docker and in settings.py we need to run docker-compose build in order to make sure the container considers all the updated changes and creates new image container.
* docker-compose run --rm app sh -c "python manage.py startapp makemigrations" This will help in running the migrations related to the project.
* docker-compose -f docker-compose-deploy.yml down --volumes is used in order to run the production level deploy method of yml file.
* docker-compose -f docker-compose-deploy.yml build to build thev container by considering the docker-compose-deploy.yml file.
* docker-compose -f docker-compose-deploy.yml up to run the production level docker container.
### Configure Settings.py for production based environment.
* In debug mode we create a bool value in which we provided 0; which means its a default value when we are running it locally.
* Change the database to postgres and connected with docker-compose.yml where we can update the postgres changes dynamically.
### Configured wait_db.py
* The reason to create wait_db.py is to create a gap between the connection of django sql server and python code.
* As the project gonna be in production server, if there's no proper wait time the database will ge crashed or shows unkown error. So by telling user to wait for couple of seconds will help the server connect to django sql up and runing.
### proxy Folder
* The proxy folder hold the data of the uwsgi params, which are used for the nginx server.
* usgi_params file will hold all the parameters of the nginx server.
* default.conf.tpl is the nginx configuration and helps nginx how to handle our files.
* run.sh is used to run the proxy folder.
* daemon refers the docker.
* The reason to again create a Dockerfile inside proxy is to help in the production server environment.
### Configuring our application to run as a uWSGI service ( In Production Environment )
* For this we created a fodler by the name scripts which hold the run.sh file and the commands that help to run server in production environment.
### Configuring docker-compose for production level environment
* docker-compose-deploy.yml will hold all the configuration required for the production level deployment.
* The environment under services will hold the configuration of postgresql database and the allowed_host we are gonna use.
* From now on we wont be using any files that are related to docker-compose.yml which we used to the development environment.
* We will be using docker-compose-deploy.yml for the production level, for this we will be using the command docker-compose -f docker-compose-deploy.yml down --volumes
* The reason to use docker-compose-deploy.yml down --volumes will delete all the previous volumes created and which gonna conflict with the main files.
* Once the volumes are deleted we need to run the command docker-compose -f docker-compose-deploy.yml build inorder to build the container of production level.
## Configuring AWS CLI In Local
* Follow this link to install the AWS-CLI updated version https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2-mac.html#cliv2-mac-install-cmd
* Post installation of AWS CLI configure the AWS Credentials by following the link:https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html
* The credentials required are IAM user credentials not the ROOT User Credentials.
* aws configure list to list out the profiles registered in AWS CLI.
* aws configure list-profiles this will list out different profile names, there will be a profile by name default initially.
* aws configure --profile profile_user_name this will help in storing of the default credentials in AWS CLI.
## AWS Vault Configuration
* Inorder to create AWS Vault in out local machine we need to install using home brew.
* Search for AWS Vault in google and you will get the latest version of it available in github.com/. Run the link in brew and it gets installed.
* Now we need to store the IAM user credentials in AWS Vault.
* For this we need to run aws-vault add iamuser name
* This will ask for AccessKey Id & Secret AccessKey, provide them and type in system password to store them.
* From next time when we want to use AWS Vault we need to type in the MFA code to run AWS Vault.
* sudo nano ~/.aws/config this will open a config file where our IAM user config file is being stored.
* Type in region=our s3bucket region
* mfa_serial=our mfa serial key available at iam user.
* aws-vault exec iamusername to run the aws-vault command.
* DON'T CHANGE ANYTHING IN THIS CONFIGURATION.
* https://github.com/99designs/aws-vault/blob/master/USAGE.md#overriding-the-aws-cli-to-use-aws-vault
* If aws-vault comes with any problem, like this unset AWS_VAULT to force. Run the command in terminal export AWS_VAULT="" this will make aws-vault clear and perfect. Makes sure the aws-vault runs again perfectly.
* aws-vault remove iamusername to delete the iam user credentials.
* aws-vault clear iamusername to delete the iam user session.
* aws-vault exec iamusername --duration=35h to run for stipulated time session only.
* aws-vault list provides the list of users created in aws-vault, by default we will be having dedault value as a user.
## Terraform
* Using terraform helps in maintaining our code and deployment process much easier and faster.
* We can configure anything that need to be created in the aws/gcp/azure directly from here that helps in the CI-CD Pipeline.
* For creating terraform locally we need to have a mandatory files like
* main.tf which holds the terraform image and cloud bucket configurations.
* bastion.tf which holds the server configuration which need to be run automatically for making the website run smoothly.
*
* In s3 bucket created a file called hawkvisum-devops-terraform and in permissions enabled versioning.
* Created table in dynamo db by the name hawkvisum-devops-terraform-lock and lockID as Partition Key / Primary Key where the terraform lock files are being stored.
* Created File with name main.tf and entered names of the bucker names created in s3 & dynamo db.
* Under s3 bucket we need to provide the key name in which the terraform lock files are being stored which will end with .tfstate
* Provided information to terraform that to create a table in the dynamodb by the name hawkvisum-devops-terraform-lock-dynamodb-table".
* Run aws-vault exec iam_user_name in the terminal, this is mainly used for the integration of aws keys we linked in our local machine with the folder aws keys which we installed earlier by the name aws-keys using git.
* Once We run in terminal it will ask for Multi Factor Authentication we setup for the IAM user, need to provide keys and run it.
* After Clearing the passwords open terminal and again type the same command, if we dont get any error we ar good to go. If there are any errors we need to follow the above steps again.
* Run this command inorder to initialise terraform in our project. docker-compose -f deploy/docker-compose.yml run --rm terraform init. The initialised prompt will help in creating a teraaform server locally and helps in connecting to the cloud server from our local environment.
* If you ever set or change modules or backend configuration for Terraform, rerun this command to reinitialize your working directory. If you forget, other commands will detect it and remind you to do so if necessary. Inorder to reinitialize terraform we need to run the following command docker-compose -f deploy/docker-compose.yml run --rm terraform init-reconfigure
* Once we run the git init command it will create a folder by the name .terraform which include linux based os which helps the terraform to run in local development environment.
* Post the creation of .terraform folder in our local machine we need to check whether the terraform is valid ornot for this we need to run the following command docker-compose -f deploy/docker-compose.yml run --rm terraform validate. This command will tell whether the terraform is valid or not, if it's not valid we need to make changes for the main.tf file and rerun the initialisation process.
* Once we are successfully validated the terraform we need to plan the terraform for further processing. For this we need to run the following command docker-compose -f deploy/docker-compose.yml run --rm terraform plan. This command will provide all the information all the necessary tasks that terraform need to run/gonna update in the apply state.
* In order to create the terraform instance over cloud and make webstie up and running we need to run, docker-compose -f deploy/docker-compose.yml run --rm terraform apply. This command is also used to aply any cnfiguration changes that has been taken over for the terraform files. The apply command will consider all the configured information from bastion.tf and creates instances in the ec2console and a .tfstate folder in s3 bucket.
* In order to destory the terraform instance over cloud we need to run the following command docker-compose -f deploy/docker-compose.yml run --rm terraform destroy. -- Heavy Risk to run this command in production level.
* When we are using terraform it will by default create a workspace which helps us in the development of our environment by the name default. Inorder list the different workspaces we are using or created under terraform we need to run the following command docker-compose -f deploy/docker-compose.yml run --rm terraform workspace list. This will list all of the workspace environments under terraform.
* Inorder to create a new terraform workspace we need to run the following command docker-compose -f deploy/docker-compose.yml run --rm terraform workspace new workspace_name.
* Once the terraform server is up and running we will get many ec2 instances creeated in aws, differentiating between these instances for debugging will be tiresome as we couldn't find which instance refer to which system, so we will be suing variables.tf file for creation and storing of the instance names. variables.tf hold the names of the instance names which we desire to provide to the instance. Terraform will does this automatically for us.
* For this we can provide a default prefix name for the instance.
* Once we updated the default instance name in varibales.tf, we need to open main.tf and add locals and add the prefix.
* The prefix will hold the prefix variable name and terraform work space name, for now we created a workspace called dev.
* Navigate to bastion.tf and add tags under resources. This will create the tag name which ends with bastion.
<img src='https://quintagroup.com/services/service-images/terraform.jpg/@@images/b2bc0e63-614c-4c37-a369-3e2943091ebf.jpeg' width='100%' align='center'></img>
## VPC Network -- Virtual Private Cloud
* VPC is mainly used in order to assign the application to cloud which will be used for our network requirements.
* The requirements include subnets, internet gateway & nat gateway.
* This will help in isoalting the different environments like development, staging and production, over the cloud inorder to makesure there won't be any conflicts in between other environments.
* If someone breaks in to our one specific environment, they won't be able to access other environments.
<img src='https://cloudonaut.io/images/2016/10/vpc@730w2x.webp' width='100%' align='center'></img>
<img src='https://cpb-us-e1.wpmucdn.com/blogs.cornell.edu/dist/b/5998/files/2016/04/Typical-Cornell-VPC-Configuration-1f8gtsn.png' width='100%' align='center'></img>
* Classless Inter-Domain Routing == cidr_block, is a method for allocating IP addresses and for IP routing.
* <a href="https://www.aelius.com/njh/subnet_sheet.html">Inorder to understand more on the cidr_block, refer the link.</a>
* The link mentioned above will help in understand the different numbers and the usecases of it.
* For creating VPC network we need to have a cidr_block which refers to the Id's. These Id's are important inorder to run the website.
* In this project this is our cidr_block of subnet 'cidr_block = "10.1.1.0/24"', in this we are using /24 as our netmask. The netmask /24 is capable of providing 254 different hosts. Which means per subnet we create we have 254 different host names. We can even update the subnet i'd numbers. Refer the above link in order to change with new subnet values.
<img src='https://www.tutorialspoint.com/ipv4/images/class_a_subnets.jpg' width='50%' align='center'></img>
* The VPC we are using will be created across two different region's. Each region will include public and private subnets. The main reason to create two VPC across different regions to balance the load on servers so that the latency will reduce.
* In network.tf file we will be differentiating the network subnet vpc's with the letter's a & b. If we look in the AWS-REGIONS, we will be seeing the regions like us-east-1, us-east-2, us-west-1, us-west-2, like this. If we choose the default region provided for the S3 bucket, this will consider us-east-1 and under this region this will create us-east-1a and us-east-1b.
* Inorder to create sub-regions under the region, initially we mentioned the alphabets at the end of resource.
* If we look at the network.tf under Public Subnets - Inbound/Outbound Internet Access; we created two different regions called a-side and b-side regions.
* The template code of aws_subnet, aws_route_table, aws_route_table_association, aws_route, aws_eip, aws_nat_gateway are similar; but the main changes are in the cidr_block.
* The cidr_block for the region-a is 10.1.1.0 and the cidr_block for the region-b is 10.1.2.0 and the public subnet region is varied by the alphabets a & b. This is to make sure that the sub regions are created under the main region.
* Example of private subnets is our database in the cloud provider, no need to have a direct internet access, because this happens in the backend of our infrastructure. This will help in the more secure way of connecting to our website and reduce attack vectors.
* As similar to the public subnets need to create private subnet will less access and more security to it.
#### Note :: Public Subnets are required for the Inbound/Outbound Internet Access && Private Subnets are required only for the Outbound Internet Access
## Issues with GitHub
* The file sizes of the terraform is huge whcih makes git to stop from uploading to cloud.
* To overcome the problem we need to follow the following steps.
* git rm --cached giant_file (In the place of giant file we need to provide the file and path of the huge file which we can get from error logs of git in terminal. By running this command Stage our giant file for removal, but leave it on disk)
* git commit --amend -CHEAD (Amend the previous commit with your change, Simply making a new commit won't work, as you need to remove the file from the unpushed history as well)
* git push (code gets pushed in to cloud by ignoring the huge file.)
## GITLAB CI-CD Pipeline
* In the gitlab pipleine we mainly created following stages;
* Test and Lint
* Build and Push
* Staging Plan
* Staging Apply
* Production Plan
* Production Apply
* Destroy
* In the gitlab pipleine we mainly created staging env, productionenv and destruction env.
* The usages vary from one to other.
* Staging Environment will consider all the changes in code commited and will create a staging environment, which is mandatory for checking any errors in the website before pushing in to production environment.
* The test cases passed in the staging environment will be then pushed in to production environment for updating the website for user interaction.
* The Reason to create staging plan, staging apply, production plan and production apply is to check in which stage the website testing is facing issue.
* In production environment which include staging and apply we aren't commiting any thing to git branches, this is because we want the commits to be applied to the production level website. So we directly mentioned it "production" with out any branch name.
* Destroy is one another rule we are using as this helps in killing the enviroment branches that has been created for different usecases. Which include staging & production.
* In the .yml file whie installing docker-compose by default we will face errors W.R.T rust-compiler which was downgraded by the cryptography wheels for the latest version of docker-compose. Inorder to overcome the issue we need to stop exporting & building the rust-compiler in to the docker-environment. For this, we need to add the following command before installing docker-compose with pip.
* export CRYPTOGRAPHY_DONT_BUILD_RUST=1
## Overcoming flake8 Error Handling
* flake8 is mainly used in making our application more understandable to new people, by removing the unqanted stuff and indentation properly.
* For this there are two ways to overcome the problem of linting.
* Type-1 :: Add .flake8 in the project root directory and update with following commands.
* [flake8]
* exclude = .git,*migrations*
* max-line-length = 119
* Type-2 :: Adding the linting directly to flake8.
* flake8 --max-line-length 119
* In Type-1, this consider all the files & folders and bypasses the error outcome. We can add other error file's aswell. We can directly provide .py files and flake8 won't consider python files for the error poppings.
* In Type-2, this can be only done for the characters count.
# Connecting CI-CD Pipeline -> AWS Instances Configuration
<h4 align='center'>Gitlab CI-CD
<span>
<img src='https://about.gitlab.com/images/press/logo/png/gitlab-icon-rgb.png' width='10%' align='center'>
</span>
+ Terraform
<span>
<img src='https://www.scalefactory.com/blog/2021/04/30/hashicorp-terraform-release-key-rotation/Terraform.png' width='10%' align='center'>
</span>
+ AWS ECR
<span>
<img src='https://www.nclouds.com/img/services/toolkit/ecr.png' width='15%' align='center'>
</span>
+ AWS EC2
<span>
<img src='https://miro.medium.com/max/1400/1*LdDE1ymsojPJ5nmH9S28uQ.png' width='15%' align='center'>
</span>
</h4>
<h1 align='center'> Full Structure
<span>
<img src='https://raw.githubusercontent.com/NVISIA/gitlab-terraform/master/blog-images/figure1.png' align='center'>
</span>
</h1>
* Inorder to the changes we did to the project that are perfectly aligned or not, we will be using local deployment server.
* But when we are pushing the changes over the cloud we need to have two environments called as Staging & Production environments.
* Staging environment will helps us to check whether all the changes updated are implementes or not. This also helps us to make sure if there's any errors that gonna effect the main page will display the errors.
* If we don't use the staging environment and directly push the code to cloud if there are no errors everything is well and good and if there are any errors in the code and pushed to the production environment this will effect the page very badly.
* So first we need to test out our servers working process and code deployed in the staging environment.
* Once the code passes the staging environment we need to push it in to the production environment for user testing.
* Inorder to bypass the process we are using terraform as out IAAS and GITLAB as out CI-CD Pipeline tool.
* Now, inorder to make the process smooth, we need to create a new IAM user specifically only for the Integration of code pushed to gitlab will be pushed to the AWS cloud servers. A <a href="https://gitlab.com/LondonAppDev/recipe-app-api-devops-course-material/-/snippets/1944972">specific policy</a> is required to create that user.
* Create a new policy, Copy and Paste the configuration in the json section of policies and update the configuration with our S3 bucket name specifically created for storing tf-state files, ECR folder name and dynamodb_table name. Save it and assign the created policy to the CI - IAMUser profile.
* Open GITLAB headover to Settings -> CI/CD -> Variables -> Update the AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, ECR_REPO URI in the settings and save the configuration.
* Open .gitlab.yml file in project folder update the yaml file with the terraform image configuration, which include the recent commit ID collects from gitlab, ecr_repo, access key and secret key stored in the variables section.
* Once the above process is done, the configuration is ready to be pushed over the cloud provider.
#### Note :: We want to make sure the process of pushing code to cloud server (AWS) is automated, which helps us reduce time on the creation of servers manually and connecting them with gitlab.
## Staging Level Deployment
* Staging environment include two stages,
* Stage-1 :: Planning
* Stage-2 :: Apply Changes
* In Stage-1, we will plan the actions that the process need to be carried out to the cloud provider, which include navigation to the project folder.
* Exporting the terraform image in to the docker container and initialising the terraform.
* Once terraform is initialised and read to next process, need to create a new environment for the staging section.
* The next process will be planning what actions need to be applied for the servers. For this we need to run terraform plan, this will provide detailed information on the changes/updations that gonna be done to the servers in aws/gcp/azure.
* In stage-2, we the changes/updation that all are planned need to be applied to the servers, for this we need to run a terraform command. terraform apply.
* For this the basic process of navigation to the deployment folder and initialising the terraform need to be done.
* The terraform environment created previously should need to be considered as main workspace for pushing the code in to staging section.
* Finally we need to run the command which will apply the changes, terraform apply.
## Production Level Deployment
* Production environment include two stages,
* Stage-1 :: Planning
* Stage-2 :: Apply Changes
* In Stage-1, we will plan the actions that the process need to be carried out to the cloud provider, which include navigation to the project folder.
* Exporting the terraform image in to the docker container and initialising the terraform.
* Once terraform is initialised and read to next process, need to create a new environment for the production section.
* The next process will be planning what actions need to be applied for the servers. For this we need to run terraform plan, this will provide detailed information on the changes/updations that gonna be done to the servers in aws/gcp/azure.
* In stage-2, we the changes/updation that all are planned need to be applied to the servers, for this we need to run a terraform command. terraform apply.
* For this the basic process of navigation to the deployment folder and initialising the terraform need to be done.
* The terraform environment created previously should need to be considered as main workspace for pushing the code in to staging section.
* Finally we need to run the command which will apply the changes, terraform apply.
#### Note :: The main diffence b/w staging and production environment's is, in staging we can check our website working process in actual cloud infrastructure.
|
C++
|
UTF-8
| 3,996 | 2.734375 | 3 |
[] |
no_license
|
#include "CommandResponder.hpp"
#include <sstream>
#include <algorithm>
namespace sbash64::finances {
CommandResponder::CommandResponder(Model &model, View &view)
: model{model}, view{view} {}
static auto integer(const std::string &s) -> int { return std::stoi(s); }
static auto cents(const std::string &s) -> int { return integer(s) * 100; }
static auto twoDecimalPlaces(const std::string &s) -> std::string {
return s +
std::string(2 - std::min(s.size(), std::string::size_type{2}), '0');
}
static auto amount(const std::string &s) -> Amount {
const auto decimal{s.find('.')};
if (decimal == std::string::npos)
return Amount{cents(s)};
const auto *const sign{s.front() == '-' ? "-" : ""};
const auto beforeDecimalMark{s.substr(0, decimal)};
const auto firstDecimalPlace{decimal + 1};
const auto afterDecimalMark{s.substr(firstDecimalPlace)};
return Amount{cents(beforeDecimalMark) +
integer(sign + twoDecimalPlaces(afterDecimalMark))};
}
static auto next(std::stringstream &s) -> std::string {
std::string next;
s >> next;
return next;
}
static auto matches(const std::string &a, const std::string &b) -> bool {
return a == b;
}
static auto matches(const std::string &a, Command c) -> bool {
return matches(a, name(c));
}
static auto amount(std::stringstream &stream) -> Amount {
return amount(next(stream));
}
static auto transaction(std::stringstream &stream) -> Transaction {
const auto amount_{amount(stream)};
auto label{next(stream)};
auto date{next(stream)};
return {amount_, std::move(label), std::move(date)};
}
static void show(View &view, const Transactions &t) { view.show(t); }
static auto date(const std::string &first, const std::string &month,
const std::string &year) -> std::string {
if (first.find('/') != std::string::npos)
return first;
return month + '/' + first + '/' + year;
}
static void add(Model &model, const Transaction &t) { model.add(t); }
void CommandResponder::enter(const std::string &s) {
try {
std::stringstream stream{s};
const auto command{next(stream)};
if (matches(command, Command::print))
show(view, model.transactions());
else if (matches(command, Command::printVerified))
show(view, model.verifiedTransactions());
else if (matches(command, Command::printUnverified))
show(view, model.unverifiedTransactions());
else if (matches(command, Command::netIncome))
view.show(model.netIncome());
else if (matches(command, Command::verify))
model.verify(amount(stream));
else if (matches(command, Command::add))
add(model, transaction(stream));
else if (matches(command, Command::remove))
model.remove(transaction(stream));
else if (matches(command, Command::month))
state = CommandState::aboutToSetMonth;
else if (state == CommandState::aboutToSetMonth) {
month = command;
state = CommandState::aboutToSetYear;
} else if (state == CommandState::aboutToSetYear) {
year = command;
state = CommandState::normal;
} else if (state ==
CommandState::aboutToEnterDateForAddingTransaction) {
transactionToAdd.date = date(command, month, year);
add(model, transactionToAdd);
state = CommandState::normal;
} else if (state ==
CommandState::aboutToEnterLabelForAddingTransaction) {
transactionToAdd.label = command;
state = CommandState::aboutToEnterDateForAddingTransaction;
} else {
transactionToAdd.amount = amount(command);
state = CommandState::aboutToEnterLabelForAddingTransaction;
}
} catch (const std::invalid_argument &) {
}
}
auto CommandResponder::prompt() -> Prompt {
return Prompt{finances::prompt(state), level(state)};
}
}
|
Rust
|
UTF-8
| 885 | 2.71875 | 3 |
[
"MIT"
] |
permissive
|
use futures_util::Stream;
use std::{
io::{BufReader, Read},
pin::Pin,
task::{Context, Poll},
};
const BUF_CAP: usize = 8 * 1024;
pub struct ReaderStream<R>(BufReader<R>);
impl<R: std::io::Read> ReaderStream<R> {
pub fn new(r: R) -> Self {
Self(BufReader::with_capacity(BUF_CAP, r))
}
}
impl<R: std::io::Read + Send + Sync + Unpin + 'static> Stream for ReaderStream<R> {
type Item = Result<Vec<u8>, crate::Error>;
fn poll_next(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let mut buf = vec![0; BUF_CAP];
let res = Pin::into_inner(self).0.read(&mut buf);
match res {
Ok(0) => Poll::Ready(None),
Ok(n) => {
buf.truncate(n);
Poll::Ready(Some(Ok(buf)))
}
Err(e) => Poll::Ready(Some(Err(e.into()))),
}
}
}
|
C#
|
UTF-8
| 1,257 | 2.515625 | 3 |
[] |
no_license
|
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Webdictaat.Core;
using Webdictaat.Core.Helper;
using Microsoft.AspNetCore.Http;
using System.IO;
namespace Webdictaat.Api.Models
{
public interface IImageRepository
{
string CreateImage(string dictaatName, IFormFile file);
}
public class ImageRepository : IImageRepository
{
private PathHelper _pathHelper;
public ImageRepository(
IOptions<ConfigVariables> appSettings,
Core.IDirectory directory,
Core.IFile file)
{
_pathHelper = new PathHelper(appSettings.Value);
}
public string CreateImage(string dictaatName, IFormFile file)
{
var path = _pathHelper.ImagesPath(dictaatName);
var extension = System.IO.Path.GetExtension(file.FileName);
var myUniqueFileName = string.Format(@"{0}{1}", Guid.NewGuid(), extension);
using (var fileStream = new FileStream(Path.Combine(path, myUniqueFileName), FileMode.Create))
{
file.CopyTo(fileStream);
}
return myUniqueFileName;
}
}
}
|
Markdown
|
UTF-8
| 3,547 | 2.71875 | 3 |
[] |
no_license
|
---
layout: page
title: Visual Factory
hero: assets/heroes/unsplash-LvOGj1X2jHE.jpg
logo: assets/products/vf-h1.svg
slides: ['assets/photo/visual_factory/20140404_124210.jpg', 'assets/photo/visual_factory/20160705_135303.jpg','assets/photo/visual_factory/VF-new-material-handling-cropped.png']
---
## Streamline all production processes to reduce waste
> "We are able to get more from our resources than we thought was possible. And we are just getting started."<span>Frank Iepema<br>Managing Director Hydro Hungary</span>
All the information you need to make decisions and improve OEE, based on accurate and up to date data. Live charts and reports means you can get updates when you need them.
Visual Factory has been developed over the last six years.
The enabling platform has been under development for over a
decade already and powers several applications beyond Visual
Factory. The underlying foundations have been researched
extensively in collaboration with the Delft University of
Technology.
<a name="visual-factory-features"></a>
## Features
- Real time information about production slow-down or issues,
<br>Using emails, screens, lamps.
- OEE reports,
<br>To help analyze lost production.
- Realistic information about what products cost to produce,
<br>Based on actual historical data, not estimates.
- Grip on material,
<br>Real time information about how much material there is and where.
- Real time information about production progress,
<br>Helping you improve your schedule over time.
{% include slideshow.html %}
<a name="visual-factory-benefits"></a>
## Goals & Benefits
The main goal of Visual Factory is streamlining processes
by having a feedback loop from gathering data to real-time responses,
issue analysis and better planning and cost estimation.
Streamlined processes deliver better results, starting the feedback loop again,
but from a better starting point.
- Cost savings by improving on-time delivery.
- Cost savings by needing less overtime hours.
- Lowering capital expenditure on resources by improving efficiency.
- Showing compliance to certification requirements.
- Minimizing rework and losses through a detailed traceability chain.
<a name="visual-factory-choose"></a>
## Why choose Visual Factory
- If you need to adapt quickly to the changing needs of your customers for a wide set of products.
- If you need a quick and safe return on your investment.
- When you want to connect to your existing ERP system, MES system or other custom system, levering as much of its data as possible to prevent double entry. And with the possibility to send back data from Visual Factory as it becomes available. All without project risk.
- Flexibility in financing: we offer 2 options to match your preferred finance method: both capex (single upfront investment, low monthly maintenance fee) or opex (monthly fee) are possible.
- Low impact on local IT organization: The physical Visual Factory terminals are included in the project and are remotely managed, upgraded and monitored by us. This means there is no additional yearly fee for MS Windows or extra maintenance overhead for your IT department.
- Short times from start of project until an up and running system. Usually new software packages take a long time to finish because of the challenges of integrating the solution with the existing environment. Visual Factory comes with an integration toolkit that has been proven to speed up integration to days or weeks at most.
|
Java
|
UTF-8
| 2,059 | 2.296875 | 2 |
[
"Apache-2.0"
] |
permissive
|
package io.choerodon.iam.api.validator;
import java.util.List;
import org.springframework.stereotype.Component;
import io.choerodon.core.exception.CommonException;
import io.choerodon.core.oauth.CustomUserDetails;
import io.choerodon.iam.api.dto.MemberRoleDTO;
import io.choerodon.iam.infra.dataobject.MemberRoleDO;
import io.choerodon.iam.infra.dataobject.RoleDO;
import io.choerodon.iam.infra.mapper.MemberRoleMapper;
import io.choerodon.iam.infra.mapper.RoleMapper;
/**
* @author wuguokai
*/
@Component
public class MemberRoleValidator {
private RoleMapper roleMapper;
private MemberRoleMapper memberRoleMapper;
public MemberRoleValidator(RoleMapper roleMapper, MemberRoleMapper memberRoleMapper) {
this.roleMapper = roleMapper;
this.memberRoleMapper = memberRoleMapper;
}
public void distributionRoleValidator(String level, List<MemberRoleDTO> memberRoleDTOS) {
memberRoleDTOS.forEach(memberRoleDTO -> {
if (memberRoleDTO.getRoleId() == null) {
throw new CommonException("error.roleId.null");
}
RoleDO roleDO = roleMapper.selectByPrimaryKey(memberRoleDTO.getRoleId());
if (roleDO == null) {
throw new CommonException("error.role.not.exist");
}
if (!roleDO.getLevel().equals(level)) {
throw new CommonException("error.roles.in.same.level");
}
});
}
public Boolean userHasRoleValidator(CustomUserDetails userDetails, String sourceType, Long sourceId, Boolean isAdmin) {
if (!isAdmin) {
MemberRoleDO memberRoleDO = new MemberRoleDO();
memberRoleDO.setMemberId(userDetails.getUserId());
memberRoleDO.setMemberType("user");
memberRoleDO.setSourceType(sourceType);
memberRoleDO.setSourceId(sourceId);
if (memberRoleMapper.select(memberRoleDO).isEmpty()) {
throw new CommonException("error.memberRole.select");
}
}
return true;
}
}
|
C
|
UTF-8
| 3,526 | 3.515625 | 4 |
[
"MIT"
] |
permissive
|
/**
coo
color.c
Purpose : Provide definitions of the various color classes and their methods
@author Kuntal Majumder ( zee at hellozee dot me )
**/
#include "color.h"
/**
* @brief new_rgb_color creates a new RGB color object returns it
* @param red
* @param green
* @param blue
* @return
*/
c_rgb
new_rgb_color(double red, double green, double blue)
{
c_rgb col;
col.r = red;
col.g = green;
col.b = blue;
return col;
}
/**
* @brief new_material_rgb_color creates a new RGB material object returns it
* @param red
* @param green
* @param blue
* @param spec
* @return
*/
c_material_rgb
new_material_rgb_color(double red, double green, double blue, double spec)
{
c_material_rgb col;
col.color = new_rgb_color(red,green,blue);
col.specular = spec;
return col;
}
/**
* @brief color_brightness returns the grayscaled version of the current color
* @param col
* @return
*/
double
color_brightness(c_material_rgb col)
{
return (col.color.b + col.color.g + col.color.r)/3;
}
/**
* @brief cap_value keeps the color values from overflowing or underflowing
* @param col
* @return
*/
c_material_rgb
color_cap_value(c_material_rgb col)
{
if(col.color.r > 1) col.color.r = 1;
if(col.color.g > 1) col.color.g = 1;
if(col.color.b > 1) col.color.b = 1;
if(col.specular > 1) col.specular = 1;
if(col.color.r < 0) col.color.r = 0;
if(col.color.g < 0) col.color.g = 0;
if(col.color.b < 0) col.color.b = 0;
if(col.specular < 0) col.specular = 0;
return col;
}
/**
* @brief color_multiply_scalar multiplies the color with a scalar factor
* @param factor
* @param col
* @return
*/
c_material_rgb
color_multiply_scalar(double factor, c_material_rgb col)
{
c_material_rgb return_color = new_material_rgb_color(col.color.r * factor,
col.color.g * factor,
col.color.b * factor ,
col.specular);
return return_color;
}
/**
* @brief color_add adds 2 colors
* @param c1
* @param c2
* @return
*/
c_material_rgb
color_add(c_material_rgb c1, c_material_rgb c2)
{
c_material_rgb return_color = new_material_rgb_color(c1.color.r + c2.color.r,
c1.color.g + c2.color.g,
c1.color.b + c2.color.b ,
c1.specular + c2.specular);
return return_color;
}
/**
* @brief color_multipy multiplies 2 colors
* @param c1
* @param c2
* @return
*/
c_material_rgb
color_multipy(c_material_rgb c1, c_material_rgb c2)
{
c_material_rgb return_color = new_material_rgb_color(c1.color.r * c2.color.r,
c1.color.g * c2.color.g,
c1.color.b * c2.color.b,
c1.specular * c2.specular);
return return_color;
}
/**
* @brief color_average returns the average of 2 colors
* @param c1
* @param c2
* @return
*/
c_material_rgb
color_average(c_material_rgb c1, c_material_rgb c2)
{
return new_material_rgb_color((c1.color.r + c2.color.r)/2,
(c1.color.g + c2.color.g)/2,
(c1.color.b + c2.color.b)/2,
(c1.specular + c2.specular)/2);
}
|
Python
|
UTF-8
| 3,288 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
import numpy as np
import argparse
import json
import os
import xlrd
import pandas as pd
import numpy as np
from sklearn.cluster import KMeans
import ssl
ssl._create_default_https_context = ssl._create_unverified_context
ap = argparse.ArgumentParser()
ap.add_argument("-s", "--selectedFeatures", help="Selected features")
args = vars(ap.parse_args())
def createDataFrame():
book = xlrd.open_workbook("./temp/excel/input.xlsx")
sheet = book.sheet_by_index(0)
data = []
sheet.row_values(0)
for i in range(sheet.nrows):
if i > 0:
data.append(sheet.row_values(i))
df = pd.DataFrame(data, columns = sheet.row_values(0))
return df
def categoricalFeaturesGrouping(df, categoricalFeatures):
categoricalGroups = df.groupby(by=categoricalFeatures, axis = 0)
return categoricalGroups
def inertiaCalculationFunction(categoricalGroups, categoricalGroup, categoricalGroupMembers, numericalFeatures, maxDiffList):
members = categoricalGroups.get_group(categoricalGroup)
membersNumerical = members[numericalFeatures]
ks = range(1,len(members) + 1) # ks represents the number of division to be made
for k in ks:
model = KMeans(n_clusters = k, random_state = 42)
model.fit(membersNumerical)
label = model.predict(membersNumerical)
inertia = np.nan_to_num(model.inertia_)
members.loc[:,"LABEL"] = label
membersGrouped = members.groupby("LABEL")
diffList = list()
for feature in numericalFeatures:
diff = membersGrouped[feature].aggregate(np.max) - membersGrouped[feature].aggregate(np.min)
#print(diff[0])
diffList.append(diff[0])
#print(diffList)
if diffList < maxDiffList:
return members, np.mean(inertia)
elif k == ks:
return members, np.mean(inertia)
else:
pass
def numericalFeaturesGrouping(categoricalGroups, categoricalFeatures, numericalFeatures, maxDiffList):
corrosionLoops = pd.DataFrame()
corrosionLoopName = list()
inertiaList = list()
for categoricalGroup, categoricalGroupMembers in categoricalGroups:
loops, inertia = inertiaCalculationFunction(categoricalGroups, categoricalGroup, categoricalGroupMembers, numericalFeatures, maxDiffList)
corrosionLoops = corrosionLoops.append(loops)
inertiaList.append(inertia)
#Naming the corrosion loops
for index, row in corrosionLoops.iterrows():
name = ""
for feature in categoricalFeatures:
name = name + str(row[feature]) + "-"
name = name + str(row["LABEL"])
corrosionLoopName.append(name)
corrosionLoops["CORROSION_LOOP"] = corrosionLoopName
# numberOfCorrLoop = len(corrosionLoops["CORROSION_LOOP"].unique())
return corrosionLoops
if __name__ == "__main__":
df = createDataFrame()
selectedFeatures = eval(args["selectedFeatures"])
categoricalFeatures = []
numericalFeatures = []
maxDiffList = []
for feature in selectedFeatures:
if selectedFeatures[feature][0] == "Categorical":
categoricalFeatures.append(feature)
elif selectedFeatures[feature][0] == "Numerical":
numericalFeatures.append(feature)
maxDiffList.append(float(selectedFeatures[feature][1]))
categoricalGroups = categoricalFeaturesGrouping(df, categoricalFeatures)
corrosionLoops = numericalFeaturesGrouping(categoricalGroups, categoricalFeatures, numericalFeatures, maxDiffList)
del corrosionLoops['LABEL']
corrosionLoops.to_excel("./temp/result/output.xlsx")
|
PHP
|
UTF-8
| 567 | 2.890625 | 3 |
[] |
no_license
|
<?php
//connect to the database
require 'databaseConnect.php';
//receive beach zone variable from javascript
if(isset($_POST['beachZone'])){
$sql = "SELECT no, name, address,longitude, latitude from info WHERE zone = '{$_POST['beachZone']}' ";
$result = mysqli_query($dbc, $sql);
$locationInfo = array();
// retrive data from database and sent into an array
while ($data = mysqli_fetch_array($result)){
$locationInfo[] = $data;
}
}
//convert array to json
echo json_encode($locationInfo);
?>
|
Python
|
UTF-8
| 1,398 | 2.828125 | 3 |
[] |
no_license
|
from keras.models import Model
from keras.layers import Input, LSTM, Dense
# Define an input sequence and process it.
encoder_inputs = Input(shape=(None, num_encoder_tokens))
encoder = LSTM(latent_dim, return_state=True)
encoder_outputs, state_h, state_c = encoder(encoder_inputs)
# We discard `encoder_outputs` and only keep the states.
encoder_states = [state_h, state_c]
# Set up the decoder, using `encoder_states` as initial state.
decoder_inputs = Input(shape=(None, num_decoder_tokens))
# We set up our decoder to return full output sequences,
# and to return internal states as well. We don't use the
# return states in the training model, but we will use them in inference.
decoder_lstm = LSTM(latent_dim, return_sequences=True, return_state=True)
decoder_outputs, _, _ = decoder_lstm(decoder_inputs,
initial_state=encoder_states)
decoder_dense = Dense(num_decoder_tokens, activation='softmax')
decoder_outputs = decoder_dense(decoder_outputs)
# Define the model that will turn
# `encoder_input_data` & `decoder_input_data` into `decoder_target_data`
model = Model([encoder_inputs, decoder_inputs], decoder_outputs)
model.compile(optimizer='rmsprop', loss='categorical_crossentropy')
model.fit([encoder_input_data, decoder_input_data], decoder_target_data,
batch_size=batch_size,
epochs=epochs,
validation_split=0.2)
|
Java
|
UTF-8
| 1,332 | 2.28125 | 2 |
[] |
no_license
|
package com.worknomads.worknomads.dao.impl;
import com.worknomads.worknomads.dao.Contracts2Repository;
import com.worknomads.worknomads.dao.RetrieveContractsDAO;
import com.worknomads.worknomads.models.SmartContract;
import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
@Component
public class RetrieveContractsDAOImpl implements RetrieveContractsDAO {
@Autowired
private Contracts2Repository contractsRepository;
@Override
public List<String> retrieveContractAddressesForWallet(String walletAddress) {
return contractsRepository.findByBusinessPartnerWalletAddress(walletAddress);
}
@Override
public List<String> retrieveAllContractAddresses() {
Iterable<SmartContract> contracts = contractsRepository.findAll();
Iterator<SmartContract> it = contracts.iterator();
List<String> contractAddresses = new ArrayList<>();
while (it.hasNext()) {
String contractAddress = it.next().getAddress();
if (StringUtils.isNotEmpty(contractAddress))
contractAddresses.add(contractAddress);
}
return contractAddresses;
}
}
|
Java
|
UTF-8
| 134 | 1.757813 | 2 |
[] |
no_license
|
public class InsertionSortTests extends SortTests {
@Override
protected Sort createSort() {
return new InsertionSort();
}
}
|
Java
|
UTF-8
| 1,180 | 2.234375 | 2 |
[] |
no_license
|
package com.codec;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import java.net.InetSocketAddress;
/**
* Created by laiwenqiang on 2019/5/28.
*/
public class Server {
public static void main(String[] args) {
EventLoopGroup boss = new NioEventLoopGroup();
EventLoopGroup worker = new NioEventLoopGroup();
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(boss, worker)
.channel(NioServerSocketChannel.class)
.localAddress(new InetSocketAddress(8888))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ch.pipeline()
.addLast(new Encoder())
.addLast(new BizHandler());
}
});
}
}
|
Java
|
UTF-8
| 5,537 | 1.921875 | 2 |
[] |
no_license
|
package com.example.administrator.expressuserclient.view.activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.example.administrator.expressuserclient.R;
import com.example.administrator.expressuserclient.base.BaseActivity;
import com.example.administrator.expressuserclient.commonUtil.GlideRoundTransform;
import com.example.administrator.expressuserclient.contract.home.NewsActivityContract;
import com.example.administrator.expressuserclient.entity.NewsEntity;
import com.example.administrator.expressuserclient.presenter.home.NewsActivityPresenter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import java.util.ArrayList;
import java.util.List;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class NewsActivity extends BaseActivity implements NewsActivityContract.View {
@InjectView(R.id.ry_news)
RecyclerView ryNews;
@InjectView(R.id.smart_layout)
SmartRefreshLayout smartLayout;
private NewsActivityPresenter presenter = new NewsActivityPresenter(this);
private int index = 2;
List<NewsEntity> list = new ArrayList<>();
NewsAdapter adapter;
@Override
public int intiLayout() {
return R.layout.activity_news;
}
@Override
public void initView(Bundle savedInstanceState) {
ButterKnife.inject(this);
ryNews.setLayoutManager(new LinearLayoutManager(NewsActivity.this));
smartLayout.autoRefresh();
smartLayout.setOnRefreshListener(new OnRefreshListener() {
@Override
public void onRefresh(@NonNull RefreshLayout refreshLayout) {
new Thread(new Runnable() {
@Override
public void run() {
presenter.loadNews(index);
}
}).start();
smartLayout.finishRefresh(1000);
}
});
smartLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
@Override
public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
Log.i(TAG, "onLoadMore: " + index++);
new Thread(new Runnable() {
@Override
public void run() {
presenter.loadMore(index++);
}
}).start();
smartLayout.finishLoadMore(500);
}
});
initToolBar().setToolNavigationIco(R.mipmap.ic_back)
.setToolNavigationIcoOnClickListener(new OnClickListener() {
@Override
public void OnClickListener() {
finish();
}
});
}
@Override
public void initData() {
}
@Override
public void loadNews(final List<NewsEntity> newsEntities) {
Log.i(TAG, "loadNews: " + newsEntities.size());
if (newsEntities.size() > 0) {
runOnUiThread(new Runnable() {
@Override
public void run() {
list.addAll(newsEntities);
adapter = new NewsAdapter(list);
ryNews.setAdapter(adapter);
}
});
}
}
@Override
public void loadMore(final List<NewsEntity> newsEntities) {
Log.i(TAG, "loadNews: " + newsEntities.size());
if (newsEntities.size() > 0) {
runOnUiThread(new Runnable() {
@Override
public void run() {
list.addAll(newsEntities);
adapter.notifyDataSetChanged();
adapter.addData(newsEntities);
}
});
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// TODO: add setContentView(...) invocation
}
private class NewsAdapter extends BaseQuickAdapter<NewsEntity, BaseViewHolder> {
public NewsAdapter(List<NewsEntity> data) {
super(R.layout.ry_item_news_layout, data);
}
@Override
protected void convert(BaseViewHolder helper, final NewsEntity item) {
helper.setText(R.id.tv_title, item.getTitle())
.setText(R.id.tv_content, item.getContent())
.setOnClickListener(R.id.ry_item, new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(NewsActivity.this, NewsDetailActivity.class);
intent.putExtra("url", item.getUrl());
startActivity(intent);
}
});
ImageView view = helper.getView(R.id.img_news);
Glide.with(NewsActivity.this).load(item.getImg()).transform(new GlideRoundTransform(NewsActivity.this)).into(view);
}
}
}
|
Java
|
UTF-8
| 1,112 | 2.546875 | 3 |
[] |
no_license
|
package core.gui.listeners;
import core.Main;
import core.gui.JFrameManager;
import core.gui.panels.FirstPanel;
import core.gui.panels.SecondPanel;
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class ChangeFirstScreenActionListener implements ActionListener {
private JFrame oldPanel;
private String newPanelName;
private JFrameManager frameManager = JFrameManager.getInstance();
public ChangeFirstScreenActionListener(JFrame oldPanel, String newPanelName) {
this.oldPanel = oldPanel;
this.newPanelName = newPanelName;
}
public void actionPerformed(ActionEvent e) {
oldPanel.setVisible(false);
JFrame newFrame = frameManager.getFrame(newPanelName);
if(newFrame == null){
newFrame = frameManager.createFrame(newPanelName);
}
newFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
newFrame.getContentPane().add(new SecondPanel(newFrame));
newFrame.pack();
newFrame.setVisible(true);
frameManager.pushFrame(newFrame);
}
}
|
C
|
UTF-8
| 2,372 | 2.703125 | 3 |
[] |
no_license
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* list.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dtedgui <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/03/21 19:23:32 by dtedgui #+# #+# */
/* Updated: 2016/03/21 19:23:38 by dtedgui ### ########.fr */
/* */
/* ************************************************************************** */
#include "ft_select.h"
void free_args_list(t_args_list *head)
{
t_args_list *next;
while (head)
{
ft_memdel((void **)&(head->value));
next = head->next;
ft_memdel((void **)&head);
head = next;
}
}
void free_select_struct(t_select **params)
{
free_args_list((*params)->list);
ft_memdel((void **)params);
}
void return_list(t_select *params)
{
t_args_list *current;
int space;
space = 0;
current = params->list;
while (current)
{
if (current->selected)
{
if (space)
ft_putchar(' ');
ft_putstr(current->value);
space = 1;
}
current = current->next;
}
free_select_struct(¶ms);
}
void print_list(t_select *params)
{
t_args_list *element;
element = params->list;
ft_tputs("cl");
if (params->curs_y == params->size_list)
params->curs_y = 0;
if (params->curs_y == -1)
params->curs_y = params->size_list - 1;
while (element)
{
add_visual_effects(element, params);
element = element->next;
}
ft_move_cursor(params);
}
void parse_arguments(int argc, char **argv, t_select *params)
{
int i;
t_args_list *new;
t_args_list *list;
list = params->list;
list->value = ft_strdup(argv[0]);
params->max_length = ft_strlen(argv[0]);
i = 1;
while (i < argc)
{
new = (t_args_list *)ft_memalloc(sizeof(t_args_list));
new->value = ft_strdup(argv[i]);
list->next = new;
list = list->next;
if (params->max_length < ft_strlen(argv[i]))
params->max_length = ft_strlen(argv[i]);
i++;
}
params->size_list = i;
}
|
Java
|
UTF-8
| 1,637 | 2.265625 | 2 |
[] |
no_license
|
package com.le.core.config.shiro;
import com.le.system.entity.SysUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
/**
* @ClassName ShiroUtil
* @Author lz
* @Description Shiro工具类
* @Date 2018/10/10 9:40
* @Version V1.0
**/
public class ShiroUtil {
public static Session getSession() {
return SecurityUtils.getSubject().getSession();
}
public static Subject getSubject() {
return SecurityUtils.getSubject();
}
public static SysUser getUser() {
return (SysUser)SecurityUtils.getSubject().getPrincipal();
}
public static Long getUserId() {
return getUser().getId();
}
public static String getUsername() {
return getUser().getUsername();
}
public static void setSessionAttribute(Object key, Object value) {
getSession().setAttribute(key, value);
}
public static Object getSessionAttribute(Object key) {
return getSession().getAttribute(key);
}
public static boolean isLogin() {
return SecurityUtils.getSubject().getPrincipal() != null;
}
public static void logout() {
SecurityUtils.getSubject().logout();
}
public static void clearAllCache(){
DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager)SecurityUtils.getSecurityManager();
ShiroRealm shiroRealm = (ShiroRealm) securityManager.getRealms().iterator().next();
//清除权限 相关的缓存
shiroRealm.clearAllCache();
}
}
|
Java
|
UTF-8
| 435 | 2.4375 | 2 |
[] |
no_license
|
import javax.swing.UIManager;
public class MainDriver {
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Game of Life");
try {
//UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel" );
UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel" );
}
catch (Exception e) { }
MainController application = new MainController();
}
}
|
Python
|
UTF-8
| 745 | 3.234375 | 3 |
[] |
no_license
|
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import matplotlib.pyplot as plt
import numpy as np
from io import BytesIO
import pprint
# 生成画布
fig=plt.figure()
#生成子图,将画布分割成1行1列,图像画在从左到右从上到下的第1块
ax1=fig.add_subplot(111)
#设置子图横坐标范围
ax1.set_xlim(0, 5)
#设置子图纵坐标范围
ax1.set_ylim(0, 5)
ax1.plot([1,2,3,4])
ax1.set_title("sample1")
#写入到本地的文件
plt.savefig('to_img.jpg')
#写入到内存中
file=BytesIO()
plt.savefig(file,format="png")
img=file.getvalue()
#读取到的是numpy矩阵的格式
img=plt.imread('to_img.jpg')
#将numpy矩阵保存为图片
plt.imsave('to_img.jpg',img)
#img为numpy矩阵格式
plt.imshow(img)
plt.show()
|
C++
|
UTF-8
| 2,217 | 2.796875 | 3 |
[] |
no_license
|
#include <Render/Camera.h>
namespace Commons
{
namespace Render
{
CameraPtr Camera::MakePerspectiveCamera(float fovy, float aspect, float far, float near)
{
CameraPtr result = CameraPtr(new Camera());
result->setPerspective(fovy, aspect, far, near);
return result;
}
CameraPtr Camera::MakeOrthoCamera(float left, float top, float right, float bottom, float far, float near)
{
CameraPtr result = CameraPtr(new Camera());
result->setOrtho(left, top, right, bottom, far, near);
return result;
}
Camera::Camera()
: m_proj()
, mPos()
, m_rot()
, mIsModelViewDirty(true)
, mFrustum()
, mIsFrustumDirty(true)
{
}
Camera::~Camera()
{
}
void Camera::setPerspective(float fovy, float aspect, float far, float near)
{
m_proj = glm::perspective(fovy, aspect, near, far);
mIsFrustumDirty = true;
}
void Camera::setOrtho(float left, float top, float right, float bottom, float far, float near)
{
m_proj = glm::ortho(left, right, bottom, top, near, far);
mIsFrustumDirty = true;
}
const glm::vec3 Camera::getTranslation() const
{
return mPos;
}
void Camera::setTranslation(const glm::vec3& pos)
{
mPos = pos;
mIsModelViewDirty = true;
mIsFrustumDirty = true;
}
const glm::quat Camera::getRotation() const
{
return m_rot;
}
void Camera::setRotation(const glm::quat& rotation)
{
m_rot = rotation;
mIsModelViewDirty = true;
mIsFrustumDirty = true;
}
const glm::mat4 Camera::getModelview() const
{
if (mIsModelViewDirty)
{
mModelView = glm::mat4(); // TODO: optimize
mModelView *= glm::mat4_cast(-m_rot);
mModelView *= glm::translate(-mPos);
mIsModelViewDirty = false;
}
return mModelView;
}
const glm::mat4 Camera::getMatrix() const
{
return getProjection() * getModelview();
}
const Frustum& Camera::getFrustum() const
{
if (mIsFrustumDirty)
{
mFrustum.setFromCamMatrix(getMatrix());
mIsFrustumDirty = false;
}
return mFrustum;
}
}
}
|
Markdown
|
UTF-8
| 1,663 | 2.5625 | 3 |
[
"MIT"
] |
permissive
|
# Fitness-Workout-App
## Project Title; Fitness-Workout-App.
## Description of App;
The design and function of the APP is to allow the user to track their exercises throughout their time at the gym or home. Any workout can be created with a simple buttton and exercises for both resistence and cardio can be added. If the user wishes to see the total output they had throughout the last 7 days.
## Screenshot

## Heroku
https://secret-forest-57902.herokuapp.com/
## Code Style; HTML, CSS &Javascript/Node.js
## Credit-
To the Columbia bootcamp team. Editor Nick Dyke
## License- MIT license
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
Markdown
|
UTF-8
| 1,594 | 3.6875 | 4 |
[] |
no_license
|
# [820. Short Encoding of Words](https://leetcode.com/problems/short-encoding-of-words)
[中文文档](/leetcode/0800-0899/0820.Short%20Encoding%20of%20Words/README.md)
## Description
<p>Given a list of <code>words</code>, we may encode it by writing a reference string <code>s</code> and a list of indexes <code>a</code>.</p>
<p>For example, if the list of <code>words</code> is <code>["time", "me", "bell"]</code>, we can write it as <code>s = "time#bell#"</code> and <code>indexes = [0, 2, 5]</code>.</p>
<p>Then for each index, we will recover the word by reading from the reference string from that index until we reach a <code>"#"</code> character.</p>
<p>Return <em>the length of the shortest reference string </em><code>s</code><em> possible that encodes the given </em><code>words</code><em>.</em></p>
<p> </p>
<p><strong>Example 1:</strong></p>
<pre>
<strong>Input:</strong> words = ["time", "me", "bell"]
<strong>Output:</strong> 10
<strong>Explanation:</strong> s = <code>"time#bell#" and indexes = [0, 2, 5</code>].
</pre>
<p><strong>Example 2:</strong></p>
<pre>
<strong>Input:</strong> words = ["t"]
<strong>Output:</strong> 2
</pre>
<p> </p>
<p><strong>Constraints:</strong></p>
<ul>
<li><code>1 <= words.length <= 2000</code></li>
<li><code>1 <= words[i].length <= 7</code></li>
<li><code>words[i]</code> consists of only lowercase letters.</li>
</ul>
## Solutions
<!-- tabs:start -->
### **Python3**
```python
```
<!-- tabs:end -->
|
Rust
|
UTF-8
| 2,420 | 3.15625 | 3 |
[] |
no_license
|
use std::collections::VecDeque;
fn print_matrix(matrix: [[&str; 5]; 5]) {
for x in &matrix {
let mut display_row = " ".to_owned();
for y in x {
display_row.push_str(y.to_string().as_ref());
display_row.push(' ');
}
println!("{}", display_row);
}
}
fn depth_first_search(mut matrix: [[&str; 5]; 5], start: (isize, isize)) -> [[&str; 5]; 5] {
let mut stack: VecDeque<(isize, isize)> = VecDeque::new();
let path_traveled: Vec<(isize, isize)> = Vec::new();
stack.push_back(start);
while ! stack.is_empty() {
let (current_node_row, current_node_column) = stack.pop_back().unwrap();
matrix[current_node_row as usize][current_node_column as usize] = "X";
for valid_next_nodes in valid_next_nodes(
matrix,
(current_node_row, current_node_column),
path_traveled.to_owned()
) {
stack.push_back(valid_next_nodes);
}
}
matrix
}
fn valid_next_nodes(
matrix: [[&str; 5]; 5],
current_pos: (isize, isize),
path_traveled: Vec<(isize, isize)>,
) -> Vec<(isize, isize)> {
// UP, DOWN, LEFT, RIGHT
let mut valid_next_nodes = Vec::new();
let directions_offset: [(isize, isize); 4] = [(-1, 0), (1, 0), (0, -1), (0, 1)];
let (current_node_row, current_node_column) = current_pos;
for (row_offset, column_offset) in directions_offset.iter() {
let (next_row, next_col) = (
current_node_row + row_offset,
current_node_column + column_offset,
);
if is_valid_node(matrix, next_row, next_col)
&& !path_traveled.contains(&(next_row, next_col))
{
valid_next_nodes.push((next_row, next_col));
}
}
valid_next_nodes
}
fn is_valid_node(matrix: [[&str; 5]; 5], row: isize, column: isize) -> bool {
column >= 0
&& row >= 0
&& (column as usize) < matrix.len()
&& (row as usize) < matrix.len()
&& matrix[row as usize][column as usize]
== "0"
}
fn main() {
let mut matrix: [[&str; 5]; 5] = [
["0", "1", "1", "0", "0"],
["1", "1", "0", "0", "0"],
["1", "0", "0", "1", "0"],
["1", "1", "0", "1", "1"],
["0", "1", "0", "0", "0"],
];
print_matrix(matrix);
println!("\n");
matrix = depth_first_search(matrix, (0, 4));
print_matrix(matrix);
}
|
JavaScript
|
UTF-8
| 1,789 | 3.5 | 4 |
[] |
no_license
|
$(document).ready(function() {
var wins = 0;
var losses = 0;
var targetNumber = Math.floor(Math.random() * 120) + 19;
var crystals = $("#crystals");
var counter = 0;
var numberOptions = [Math.floor(Math.random()* 12) + 1, Math.floor(Math.random()* 12) + 1, Math.floor(Math.random()* 12) + 1, Math.floor(Math.random()* 12) + 1];
$("#number-to-guess").text(targetNumber);
$("#times-won").text(wins);
$("#times-lost").text(losses);
function resetGame() {
var numberOptions = [Math.floor(Math.random()* 12) + 1, Math.floor(Math.random()* 12) + 1, Math.floor(Math.random()* 12) + 1, Math.floor(Math.random()* 12) + 1];
var targetNumber = Math.floor(Math.random() * 120) + 19;
$("#number-to-guess").text(targetNumber);
$("#times-won").text(wins);
$("#times-lost").text(losses);
}
for (var i = 0; i < numberOptions.length; i++) {
var imageCrystal = $("<img>");
imageCrystal.addClass("crystal-image");
imageCrystal.attr("src", "http://cdn.playbuzz.com/cdn/35910209-2844-45c0-b099-f4d82878d54f/00261fda-4062-4096-81fd-8cf96b9034e8.jpg");
imageCrystal.attr("data-crystalvalue", numberOptions[i]);
crystals.append(imageCrystal);
}
crystals.on("click", ".crystal-image", function() {
var crystalValue = ($(this).attr("data-crystalvalue"));
crystalValue = parseInt(crystalValue);
counter += crystalValue;
alert("New score: " + counter);
if (counter === targetNumber) {
alert("You win!");
wins ++;
resetGame();
counter=0;
}
else if (counter >= targetNumber) {
alert("You lose!!");
losses ++;
resetGame();
counter=0;
}
});
});
|
C++
|
GB18030
| 2,171 | 2.875 | 3 |
[] |
no_license
|
#pragma once
#include <string>
#include <vector>
#include <map>
#include <set>
using namespace std;
//
struct Server {
string type; //ͺ
int cpu_num; //CPU
int mem_num; //ڴС
double mech_cost; //Ӳɱ
double day_cost; //ÿܺijɱ
};
struct ServersAll {
int type_num = 0; //
map<string, Server> servers;
//cpuСķtype
map<int, set<string>> cpuMap;
//memСķtpye
map<int, set<string>> memMap;
};
//
struct VirtualMachine {
string type; //ͺ
int cpu_num; //CPU
int mem_num; //ڴС
int is_double; //Ƿ˫ڵ㲿
};
struct VirtualMachinesAll {
int type_num = 0; //
map<string, VirtualMachine> virtual_machines;
};
//
struct Request {
int is_add; //ͣ0-del1-add
string type; //ͺ(עaddҪtypeϢdelֻҪid)
int virtual_machine_id; //ID
};
struct DayRequest {
int request_num = 0;
int request_add_num = 0;
vector<Request> day_requests;
};
struct RequestsAll {
int day_num = 0; //
map<int, DayRequest> requests;
};
struct Migration {
int virtual_machine_id;
int dest_machine_id;
string dest_node="";
};
struct DaySchdule {
//ҪķϢ
int mach_tpye_num = 0;
map<string, int> PurchaseList;
//ҪǨƵϢ
int migration_num = 0;
vector<Migration> MigrationList;
//˳ڵǰһÿһ
int request_add_num = 0;
vector<Migration> RequestAddList;
};
struct DaySchedulesAll {
int day_num = 0;
vector<DaySchdule> schedules;
};
//ʵʱԴϢ
struct ServerRemain {
string type; //ͺ
int remian_cpu_num; //ʣCPU
int remain_mem_num; //ʣڴС
map<int, VirtualMachine> A_virtual_machines; //AڵϱϢ<IDͺϢ>
map<int, VirtualMachine> B_virtual_machines; //BڵϱϢ<IDͺϢ>
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.