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
| 3,172 | 3.40625 | 3 |
[] |
no_license
|
๏ปฟ// Ionia Flemming
// Recitation 930am
// https://ide.c9.io/joph0114/cs1300s18
// Recitation 5, Problem 1
// February 12, 2018 // cant figure out how to traverse or keep a counter going to compare the next substring set
#include <iostream>
#include <string>
using namespace std;
/*
set up function that accepts two string parameters and returns int value
redefine parameters
set up conditional that check to see if either string is empty
if true. return -1
set up conditional that checks to see if the substring is longer than the string
if true, return -2
else
define new int variable that finds the length of given substring
intialize a match counter
initialize indexer variable
set up while loop that terminates at end of string
if substring is matching substring point of the string
update match count by one
i = i + 1 , this part changes the starting position of gathering the substring of the long string
else
i = i + 1, if no matches are found the indexer will move on
after while loop has terminated, return match count.
*/
int getMatchCount(string g_substring, string g_string)
{
string given_substring = g_substring;
string given_string = g_string;
if (given_substring == "" || given_string == "")
{
return -1;
}
if (given_substring.length() > given_string.length())
{
return -2;
}
else
{
int given_substring_length = given_substring.length(); // gets length of given substring
int newStringStartingPosition = given_substring_length;
//string substring_given_substring; // variable of substring of given string
// string substring_given_string = given_string.substr(0,given_substring_length); // matches amount of characters of string to amount of char in given substring
int match_count = 0; // define variables
int i = 0;
while (i < given_string.length()) // terminating while loop
{
if (given_substring == given_string.substr(i,given_substring_length)) // i is passed here because it changes the starting position of gathering the substring
{
match_count = match_count + 1; // update matches
i = i + 1;
//substring_given_string == given_string.length(newStringStartingPosition, given_substring_length);
}
else
{
i = i + 1; // move indexer foward
}
}
return match_count; // return
}
}
int main()
{
cout << getMatchCount("si","si") << endl; // test cases
cout << getMatchCount("si","mississippi") << endl;
cout << getMatchCount("o","lollipop") << endl;
cout << getMatchCount("moo","moodle") << endl;
}
|
Python
|
UTF-8
| 772 | 3.640625 | 4 |
[] |
no_license
|
'''
Created on 21/09/2013
Largest prime factor
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
@author: Antek
'''
from problem_7.problem_7 import prime_numbers
def prime_factors(n):
factors = []
step = 100
length = step
numbers = prime_numbers(length)
remnant = n
i = 0
while remnant != 1:
while remnant % numbers[i] != 0:
i += 1
if i >= len(numbers):
length +=step
numbers = prime_numbers(length)
remnant = remnant / numbers[i]
factors.append(numbers[i])
return factors
if __name__ == '__main__':
print prime_factors(600851475143)[-1]
|
SQL
|
UTF-8
| 26,566 | 3.75 | 4 |
[] |
no_license
|
-- This file will create entries in the database for all schools for 2014 that are NEW
-- to dot-art schools. So, no need to enter schools from last year if they have entered
-- again this year.
-- For schools that HAVE re-entered from last year, please list their names below.
-- Gateacre Comprehensive school
INSERT INTO n_school_year (school, year)
VALUES(5, 2014);
-- broadgreen international
INSERT INTO n_school_year (school, year)
VALUES(3, 2014);
-- holly lodge
INSERT INTO n_school_year (school, year)
VALUES(6, 2014);
-- bluecoat school
INSERT INTO n_school_year (school, year)
VALUES(14, 2014);
-- cardinal heenan
INSERT INTO n_school_year (school, year)
VALUES(19, 2014);
-- alsop high school
INSERT INTO n_school_year (school, year)
VALUES(1, 2014);
-- archbishop beck
INSERT INTO n_school_year (school, year)
VALUES(2, 2014);
-- the belvedere academy
INSERT INTO n_school_year (school, year)
VALUES(13, 2014);
-- Orminston Bollingbroke
INSERT INTO n_school_year (school, year)
VALUES(8, 2014);
-- st Augustine of Cantebury
INSERT INTO n_school_year (school, year)
VALUES(9, 2014);
-- St Julies
INSERT INTO n_school_year (school, year)
VALUES(10, 2014);
-- St Margarets
INSERT INTO n_school_year (school, year)
VALUES(11, 2014);
-- broadgreen primary
INSERT INTO n_school_year (school, year)
VALUES(16, 2014);
-- Notes:
-- type = type of school; 1 = Primary; 2 = Secondary.
-- name = name of the school.
-- url_path = the website-friendly address for the school - lower-case, no spaces or
-- special chars.
-- statement = The statement to appear at the top the school's page on the site.
-- website = FULL address of the school's own website, including http://...
-- image = the name and folder of the image used as the school's logo,
-- e.g. 'alsop-high-school/alsop-logo.jpg'
-- Copy-and-paste the INSERT statement below as many times as you need. Please leave
-- a couple of blank lines between each school.
ALTER TABLE n_school_year AUTO_INCREMENT = 21;
ALTER TABLE n_school AUTO_INCREMENT = 21;
INSERT INTO n_school (type, name, url_path, statement, website, image)
VALUES (1,
'Auckland College Lower School',
'auckland-college-lower-school',
'Auckland College is an independent school providing education for children from 6 weeks to 18 years of age.',
'http://www.aucklandcollege.com',
'auckland-college-lower-school/auckland-college-logo.jpg');
INSERT INTO n_school_year (school, year)
VALUES(LAST_INSERT_ID(), 2014);
INSERT INTO n_school (type, name, url_path, statement, website, image)
VALUES (1,
'Barlows Primary School',
'barlows-primary-school',
'Barlows Primary School provides a happy and secure environment in which our children can acquire skills and develop their imagination and appreciation of the world, thus enabling them to fulfil their role as valuable members of the community.',
'http://www.barlowsprimary.co.uk/',
'barlows-primary-school/barlows-primary-logo.jpg');
INSERT INTO n_school_year (school, year)
VALUES(LAST_INSERT_ID(), 2014);
INSERT INTO n_school (type, name, url_path, statement, website, image)
VALUES (1,
'Christian Fellowship Middle School',
'christian-fellowship-middle-school',
'We began in 1981 on a small scale, prompted simply by the urgency to give an option to parents who wanted a non-denominational school to support a Christian upbringing for children, reflecting the ethos of a family who honour Christ.',
'http://www.cfschool.org.uk/index.shtml',
'christian-fellowship-middle-school/christian-fellowship-logo');
INSERT INTO n_school_year (school, year)
VALUES(LAST_INSERT_ID(), 2014);
INSERT INTO n_school (type, name, url_path, statement, website, image)
VALUES (1,
'Rainford CE Primary School',
'rainford-ce-primary-school',
'At Rainford C.E. Primary School we foster Christian beliefs whilst nurturing
our chosen values of love, peace, trust, friendship, forgiveness and thankfulness. Through this we aim to maintain and develop a Christian ethos and encourage an atmosphere of warmth and calm where all in our school community are equally valued and work together as part of the wider community',
'http://www.rainfordcofe-pri.st-helens.sch.uk/index.html',
'rainford-ce-primary-school/rainford-ce-logo');
INSERT INTO n_school_year (school, year)
VALUES(LAST_INSERT_ID(), 2014);
INSERT INTO n_school (type, name, url_path, statement, website, image)
VALUES (1,
'Saints Peter and Paul Catholic Primary School',
'saints-peter-and-paul-catholic-primary-school',
'Saints Peter and Paul is a school where we embrace and enhance our partnership with parents, the parish and the wider community. We seek to enable every child to reach their true potential through our teaching and learning experiences, closely matched to children?s needs. Central to our approach is the firm belief that our culture and ethos are based on gospel values of love, and mutual respect where individuality is encouraged and individuals thrive.',
'http://saintspeterandpaulcps.org.uk/',
'saints-peter-and-paul-catholic-primary-school/saints-peter-logo.jpg');
INSERT INTO n_school_year (school, year)
VALUES(LAST_INSERT_ID(), 2014);
INSERT INTO n_school (type, name, url_path, statement, website, image)
VALUES (1,
'St. Matthew''s Primary School',
'st-matthews-primary-school',
'Our pupils have really enjoyed this quilling project as it helped them to develop many skills, both artistic and social. The skill of paper curling is extremely intricate and requires a great deal of patience. The pupils were further challenged to consider different shapes that could be achieved whilst having an awareness of the space created within the layers of paper. Colour was another aspect, as they considered which colours both contrasted and complimented well. The project was a cross-curricular initiative linking to our study of Victorian Britain. The pupils learnt how this delicate craft was used to decorate many furnishings during this period.',
'http://www.stmatthewsprimaryschool.co.uk',
'st-matthews-primary/st-matthews-logo.jpg');
INSERT INTO n_school_year (school, year)
VALUES(LAST_INSERT_ID(), 2014);
INSERT INTO n_school (type, name, url_path, statement, website, image)
VALUES (1,
'St Michael and All Angels Primary School',
'st-michael-and-all-angels-primary-school',
'Our Year 6 pupils visited Crosby Beach, the Pier Head and Festival Gardens site earlier in February. They took photographs during the very chilly and windy day. Back at school the photographs were printed off so that pupils and parents could vote for their favourite. The pupils then used the photographs taken to produce their own piece of art work by using either pastels, photographs, or collage. The pupils worked totally independently and made their choice of media independently too. The children had lots of fun and took great delight in working on their own pieces of River Mersey art work.',
'http://www.smaaa.info',
'st-michael-and-all-angel/st-michael-logo.jpg');
INSERT INTO n_school_year (school, year)
VALUES(LAST_INSERT_ID(), 2014);
INSERT INTO n_school (type, name, url_path, statement, website, image)
VALUES (1,
'Weston Primary School',
'weston-primary-school',
'We are a small village primary school who provides rich, unique and varied creative experiences that go beyond the norm. Our children explore many artistic styles and encounter Artists and Designers who are not normally focused upon across the curriculum. All the children submitted have taken the lead, drawing upon artists and other influences from around the world, and we are proud to submit their work into this competition.',
'NULL',
'weston-primary-school/weston-primary-logo.png');
INSERT INTO n_school_year (school, year)
VALUES(LAST_INSERT_ID(), 2014);
INSERT INTO n_school (type, name, url_path, statement, website, image)
VALUES (1,
'Whitefield Primary School',
'whitefield-primary-school',
'The children were inspired by the works of the artist J.M.W.Turner to create their own interpretations of a shipwreck. The children are currently finding out about shipwrecks as it is a topic of study during their literacy and learning challenge lessons. The idea of drawing a shipwreck in the style of Turner enabled the children to extend their learning and allow others to visualise this creativity. The children used oil pastels in a variety of techniques, by blending and sketching they created different depths and textures. They also used solid colour to create different shades and highlights.',
'http://www.Whitefieldprimary.co.uk',
'whitefield-primary-school/whitefield-primary-logo.jpg');
INSERT INTO n_school_year (school, year)
VALUES(LAST_INSERT_ID(), 2014);
/*
INSERT INTO n_school (type, name, url_path, statement, website, image)
VALUES (1,
'Woolton Primary School',
'woolton-primary-school',
'Working together to provide every child with an inclusive, high quality, enjoyable learning experience where success is celebrated and children feel valued.',
'http://www.wooltonprimary.com/',
'woolton-primary-school/woolton-primary-logo.jpg');
INSERT INTO n_school_year (school, year)
VALUES(LAST_INSERT_ID(), 2014);
*/
INSERT INTO n_school (type, name, url_path, statement, website, image)
VALUES (1,
'Arnot St Mary C of E Primary School',
'arnot-st-mary-c-of-e-primary-school',
'Children of Arnot St Mary have used mono printing as a base for their pieces of artwork. They have been inspired by natural imagery. In some cases they have printed using real sardines and shells. Some pieces of artwork have been over worked with chalk pastels, acrylic paint and ink.',
'http://www.Arnotstmary.co.uk',
'arnot-st-mary-c-of-e-primary-school/arnot-st-logo.jpg');
INSERT INTO n_school_year (school, year)
VALUES(LAST_INSERT_ID(), 2014);
INSERT INTO n_school (type, name, url_path, statement, website, image)
VALUES (2,
'Auckland College Secondary School',
'auckland-college-secondary-school',
'Auckland College is an indepedent school providing education for children from 6 weeks to 18 years of age.',
'http://www.aucklandcollege.com',
'auckland-college-secondary-school/auckland-college.jpg');
INSERT INTO n_school_year (school, year)
VALUES(LAST_INSERT_ID(), 2014);
INSERT INTO n_school (type, name, url_path, statement, website, image)
VALUES (2,
'Bellerive FCJ Catholic College',
'bellerive-fcj-catholic-college',
'Bellerive FCJ has been educating girls in Liverpool for nearly 170 years ? and more recently boys in the Sixth Form ? preparing them for the lives they will lead once they leave the school for the final time. Currently in Year 7 we teach the basic elements of Art and study Botanical Art, Gargoyles and animation, and Still Life. In Year 8 we develop ideas based on Architecture, different viewpoints, and Environmental Art. In Year 9 we complete work based on different cultures, self-portraits and still life',
'http://www.bellerivefcj.org/',
'bellerive-fcj-catholic-college/bellerive-fcj-logo.jpg');
INSERT INTO n_school_year (school, year)
VALUES(LAST_INSERT_ID(), 2014);
INSERT INTO n_school (type, name, url_path, statement, website, image)
VALUES (2,
'Birkenhead High School Academy',
'birkenhead-high-school-academy',
'Birkenhead High School Academy offers girls from the age of 3 to 19 years the opportunity to develop into confident, articulate, aspiring and responsible young women equipped to tackle cheerfully whatever life throws at them and to forge an exciting and fulfilling future for themselves. BHSA is sponsored by the Girls'' Day School Trust and maintains the shared goal of excellence in girls'' education.? We ?expect the highest of standards in attendance, punctuality, appearance, conduct and achievement in it students, because we believe education is about the whole person and preparing them to enjoy all aspects of life',
'http://www.birkenheadhigh.gdst.net/',
'birkenhead-high-school-academy/birkenhead-high-logo.jpg');
INSERT INTO n_school_year (school, year)
VALUES(LAST_INSERT_ID(), 2014);
INSERT INTO n_school (type, name, url_path, statement, website, image)
VALUES (2,
'Calderstones School',
'calderstones-school',
'The aim of the school is to educate pupils of all abilities, each to a maximum of his/her potential, so that every boy and girl can enjoy a high quality of life and contribute responsibly and fully to the life of the community.',
'http://www.calderstones.co.uk/',
'calderstones-school/calderstones-school-logo.jpg');
INSERT INTO n_school_year (school, year)
VALUES(LAST_INSERT_ID(), 2014);
INSERT INTO n_school (type, name, url_path, statement, website, image)
VALUES (2,
'Cavendish High School',
'cavendish-high-school',
'Cavendish High School prides itself on delivering its curriculum through the arts. We are a school for students with learning difficulties and disabilities, and so the arts provide another way for our students to communicate, express themselves and connect with others, as well as a fantastic way to learn.',
'http://www.cavendishhighschool.com/',
'cavendish-high-school/cavendish-high-logo.jpg');
INSERT INTO n_school_year (school, year)
VALUES(LAST_INSERT_ID(), 2014);
INSERT INTO n_school (type, name, url_path, statement, website, image)
VALUES (2,
'Christian Fellowship Upper School',
'christian-fellowship-upper-school',
'We began in 1981 on a small scale, prompted simply by the urgency to give an
option to parents who wanted a non-denominational school to support a Christian
upbringing for children, reflecting the ethos of a family who honour Christ.',
'http://www.cfschool.org.uk',
'christian-fellowship-upper-school/christian-fellowship-logo.jpg');
INSERT INTO n_school_year (school, year)
VALUES(LAST_INSERT_ID(), 2014);
INSERT INTO n_school (type, name, url_path, statement, website, image)
VALUES (2,
'De La Salle School St Helens',
'de-la-salle-school-st-helens',
'De La Salle is a mixed Secondary comprehensive School for students aged 11-16. They have a busy and thriving Art department which sees a large cohort of students opt for Art at GCSE level and achieve excellent grades. In Year 9 the students learning experience in Art is on a rota which explores a variety of themes, processes and ways of thinking. The work you are viewing ranges from lino printmaking to ceramics to mixed media work all in response to artists, craftspeople and designers and cultural practices. The Art department is very proud of all of their students and here are a few to set the scene.',
'http://www.delasalle.st-helens.sch.uk/',
'de-la-salle-st-helens/de-la-logo.jpg');
INSERT INTO n_school_year (school, year)
VALUES(LAST_INSERT_ID(), 2014);
INSERT INTO n_school (type, name, url_path, statement, website, image)
VALUES (2,
'Greenbank High School',
'greenbank-high-school',
'Greenbank High School for Girls is an age 11 ? 16 academy on the outskirts of Southport. The School has fewer than 800 students and has Specialist status in Modern Foreign Languages.',
'http://www.greenbankhigh.co.uk',
'greenbank-high-school/greenbank-high-logo.jpg');
INSERT INTO n_school_year (school, year)
VALUES(LAST_INSERT_ID(), 2014);
INSERT INTO n_school (type, name, url_path, statement, website, image)
VALUES (2,
'Hillside High School',
'hillside-high-school',
'Year 9 pupils have been inspired by the artists Vincent Van Gogh, George Lund, and David Hockney. They have experimented with different materials, such as pastel, collage, pen and ink and paint. They have deepened their knowledge of the history of art. Pupils have also completed a series of observational drawings. This has developed their drawing skills further as well as enhancing their knowledge of the formal elements in art.',
'http://www.hillsidehigh.co.uk/',
'hillside-high-school/hillside-high-logo.jpg');
INSERT INTO n_school_year (school, year)
VALUES(LAST_INSERT_ID(), 2014);
INSERT INTO n_school (type, name, url_path, statement, website, image)
VALUES (2,
'Holy Family Catholic High School',
'holy-family-catholic-high-school',
'We are a high achieving, 11-18 school, where children feel safe and happy. We aim to create a very supportive and caring environment where each student has the self-confidence and belief to realise their ambitions. We are aspirational for all of our young people and strive to meet the needs of every child, irrespective of ability, to ensure they maximise their potential both in and out of the classroom. The general theme of these pieces was Close Ups though some students decided to expand on this however they wished.',
'www.holyfamilyhighschool.co.uk',
'holy-family-catholic-high-school/holy-family-logo.jpg');
INSERT INTO n_school_year (school, year)
VALUES(LAST_INSERT_ID(), 2014);
INSERT INTO n_school (type, name, url_path, statement, website, image)
VALUES (1,
'Hope School',
'hope-school',
'We are a busy but friendly school, with lots going on. At Hope School, we are committed to the principle that all children have a right to an education which meets their learning, emotional and social needs. Since September the following 8 boys from Hope school have been working really hard on their art work. They have been learning abstract art, surrealism, still life and looking at artists such as Kandinsky, Jackson Pollock and Cy Twombly. The boys are really proud of their work and this showcases the work produced by a key stage 2 class.',
'http://www.hopeschool-liverpool.co.uk/',
'hope-school/hope-school-logo.jpg');
INSERT INTO n_school_year (school, year)
VALUES(LAST_INSERT_ID(), 2014);
INSERT INTO n_school (type, name, url_path, statement, website, image)
VALUES (2,
'Merchant Taylors'' Boys'' School',
'merchant-taylors-boys-school',
'Year 9 boys have been studying Pop Art this term. The boys have begun by creating observational drawings of their facial features and then produced self-portraits. This has finally led to the development of a Pop Art Portrait.Other year 9 boys have been studying Cubism this term. They have produced a series of observational drawings and eventually created their own still life scene influenced by Cubism.',
'http://www.merchanttaylors.com',
'merchant-taylors-boys-school/merchant-taylors-logo.jpg');
INSERT INTO n_school_year (school, year)
VALUES(LAST_INSERT_ID(), 2014);
INSERT INTO n_school (type, name, url_path, statement, website, image)
VALUES (2,
'Range High School',
'range-high-school',
'Range High is an 11-18 co-educational comprehensive school situated on the edge of Formby in Merseyside. This simple description belies a wealth of special characteristics, which combine to make Range High School a unique place in which to educate your child.',
'http://www.range.sefton.sch.uk',
'range-high-school/range-high-logo.jpg');
INSERT INTO n_school_year (school, year)
VALUES(LAST_INSERT_ID(), 2014);
INSERT INTO n_school (type, name, url_path, statement, website, image)
VALUES (2,
'St Chad''s Catholic and Church of England High School',
'st-chads-catholic-and-church-of-england-high-school',
'St. Chad''s Catholic and Church of England School is a secure, friendly and Faith centred community where we seek to realise the full potential of all our members through the living love of Christ.',
'http://www.st-chads.co.uk/index.php/school-information/mainmenu-missionstatement',
'st-chads/st-chads-logo.jpg');
INSERT INTO n_school_year (school, year)
VALUES(LAST_INSERT_ID(), 2014);
INSERT INTO n_school (type, name, url_path, statement, website, image)
VALUES (2,
'St Hilda''s CE School',
'st-hildas-ce-school',
'The work submitted is in response to a campaign to save Sefton Meadows from being developed for luxury housing. There are personal responses as well as a collaborative piece. All the work was done during an extra-curricular club by year 9 pupils.',
'http://www.st-hildas.com/',
'st-hildas-c-e-school/st-hildas-logo.jpg');
INSERT INTO n_school_year (school, year)
VALUES(LAST_INSERT_ID(), 2014);
INSERT INTO n_school (type, name, url_path, statement, website, image)
VALUES (2,
'St John Bosco Arts College',
'st-john-bosco-arts-college',
'Students have worked in a variety of media to produce their own creative designs based on African images, patterns and colours. Their design work will be developed into a 3D ceramic piece. The project is current and on-going.',
'http://www.stjohnboscoartscollege.com/',
'st-john-bosco-art-college/st-john-logo.jpg');
INSERT INTO n_school_year (school, year)
VALUES(LAST_INSERT_ID(), 2014);
INSERT INTO n_school (type, name, url_path, statement, website, image)
VALUES (2,
'St. Mary''s Catholic College',
'st-marys-catholic-college',
'Year 9 students created this set of work with local artist David Setter to celebrate the achievements of people from Merseyside that have achieved status within The Arts. After completing a scheme of work based on his work which involved poly-print, continuous line drawings and string portraits, they set about researching their chosen celebrity. The portraits were drawn to reflect the personality of the subject.',
'http://www.stmaryscollege.wirral.sch.uk/',
'st-marys-catholic-college/st-marys-logo.jpg');
INSERT INTO n_school_year (school, year)
VALUES(LAST_INSERT_ID(), 2014);
INSERT INTO n_school (type, name, url_path, statement, website, image)
VALUES (2,
'The Heath School',
'the-heath-school',
'The Heath School year 9 art students have been having fun studying Mexican Folk art, the work of artist Frida Kahlo and the celebration Dias de Los Muertos. They have worked independently over the term, producing their own handmade sketchbooks by experimenting with images of sugar skulls, tattoos, La Catarina and animal skeletons using mixed media.',
'http://www.heathschool.org.uk/',
'the-heath-school/the-heath-logo.jpg');
INSERT INTO n_school_year (school, year)
VALUES(LAST_INSERT_ID(), 2014);
INSERT INTO n_school (type, name, url_path, statement, website, image)
VALUES (2,
'The Oldershaw Academy',
'the-oldershaw-academy',
'We are a large mixed 11-18 high school which has a proud history successfully working with the Wallasey community providing excellent education for over 90 years. The Academy has a strong partnership with over 20 primary schools and serves a wide geographical area including Wallasey, Moreton and Birkenhead. The Art department is an oversubscribed, popular subject which plays an important role in the school. KS3 have hour lessons covering Art, Graphics and Textiles. Pupils are taught skills that can be used at GCSE and pupils are actively engaged in visits, workshops and clubs in order to research Art first hand.',
'http://www.oldershaw.wirral.sch.uk/',
'the-oldershaw-academy/the-oldershaw-logo.jpg');
INSERT INTO n_school_year (school, year)
VALUES(LAST_INSERT_ID(), 2014);
INSERT INTO n_school (type, name, url_path, statement, website, image)
VALUES (2,
'Wade Deacon High School',
'wade-deacon-high-school',
'Combining the traditional with the latest cutting edge teaching and learning facilities, Wade Deacon High School offers the perfect environment within which all pupils can achieve. The school?s ethos of ''A Commitment to Excellence'' permeates through every aspect of school life. A disciplined, supportive and purposeful working environment enables pupils to excel across the whole curriculum, reflected in the success that pupils enjoy year on year at both Key Stages 3 & 4. Wade Deacon''s external examination results are consistently well above the national average.',
'http://www.wadedeacon.co.uk',
'wade-deacon-high-school/wade-deacon-logo.jpg');
INSERT INTO n_school_year (school, year)
VALUES(LAST_INSERT_ID(), 2014);
INSERT INTO n_school (type, name, url_path, statement, website, image)
VALUES (2,
'West Derby School',
'west-derby-school',
'West Derby School, a Specialist Academy in Maths and Computing, serving boys only in Key Stages 3 and 4, and welcoming girls into the Sixth Form. We are a popular and over subscribed school with a very special and warm ethos.We welcome the fact that our students are individuals with differing backgrounds, talents, aspirations and needs. We offer a full range of academic and enrichment opportunities to all and we are very proud of the boys'' achievements.',
'http://www.westderbyschool.co.uk/',
'west-derby-school/west-derby-logo.jpg');
INSERT INTO n_school_year (school, year)
VALUES(LAST_INSERT_ID(), 2014);
INSERT INTO n_school (type, name, url_path, statement, website, image)
VALUES (2,
'West Kirby Residential School',
'west-kirby-residential-school',
'As a Non Maintained Special School, West Kirby Residential School caters for boys and girls with a range of complex social, emotional and behavioural difficulties, often linked with medical conditions such as Asperger''s Syndrome, learning difficulties and communication problems. It is a priority to provide a structured, supportive and controlled learning environment for each pupil. By actively encouraging children to develop their inner control and social skills, staff can help them to overcome their own individual behavioural difficulties. Pupils are able to learn and grow in situations that will help them achieve their maximum potential. Staff are specially trained to assist pupils in developing an awareness both of themselves as individuals and within a group, increasing their respect for others, their self-esteem, emotional stability and acceptability.',
'http://www.wkrs.co.uk/',
'west-kirby-residential-school/west-kirby-logo.jpg');
INSERT INTO n_school_year (school, year)
VALUES(LAST_INSERT_ID(), 2014);
INSERT INTO n_school (type, name, url_path, statement, website, image)
VALUES (2,
'Rainhill High School',
'rainhill-high-school',
'Rainhill High is a highly popular and oversubscribed Media Arts Specialism school & sixth form. The Art department holds a highly innovative and diverse team of teachers who drive and enthuse pupils to consistently surpass expectations time and time again. With innovative SOL and highly dedicated teachers from a wide range of specialisms, we pride ourselves on allowing all our students to independently explore ideas and concepts in projects to arrive at unique and unexpected outcomes. We achieved 95.8% A*-C within Art & Design and all year 13 Art students secured places at their chosen universities across England for the third year running.',
'http://www.rainhillhighschool.org.uk',
'rainhill-high-school/rainhill-high-logo.jpg');
INSERT INTO n_school_year (school, year)
VALUES(LAST_INSERT_ID(), 2014);
|
PHP
|
UTF-8
| 835 | 3.09375 | 3 |
[] |
no_license
|
<?php
class Library_Qframe_View_Element_JS_File
{
private $type;
private $src;
public function __construct($type, $src)
{
$this->type = $type;
$this->src = $src;
}
/**
* Devuelve el valor del atributo type.
*
* @return string
*/
public function getType()
{
return $this->type;
}
/**
* Establece el valor del atributo type.
*
* @param string $type
*/
public function setType($type)
{
$this->type = $type;
}
/**
* Devuelve el valor del atributo src.
*
* @return string
*/
public function getSrc()
{
return $this->src;
}
/**
* Establece el valor del atributo src.
*
* @param string $src
*/
public function setSrc($src)
{
$this->src = $src;
}
public function __toString()
{
return Library_Qframe_View_Element_JS_Printer::printFile($this);
}
}
|
C#
|
UTF-8
| 3,091 | 3.015625 | 3 |
[] |
no_license
|
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Assignment3_crypto.Logic.Interfaces;
using System.Numerics;
namespace Assignment3_crypto.Logic.BackEndLogic
{
public class Hasher : IBlock
{
#region IBlock Members
public string AddendPadding(string rawText)
{
rawText = rawText.Insert(0, "1");
while (rawText.Length % 1024 != 896)
{
rawText = rawText.Insert(1, "0");
}
return rawText;
}
public string AppendLength(string rawText, string paddedText)
{
var formerSize = Convert.ToString(rawText.Length, 2);
while (formerSize.Length < 128)
formerSize = formerSize.Insert(0, "0");
paddedText += formerSize;
return paddedText;
}
public string[] GetHashBuffer()
{
var buffer = new string[8];
buffer[0] = "0110101000001001111001100110011111110011101111001100100000000000";
buffer[1] = "1011101101100111101011101000010110000100110010101010100000000000";
buffer[2] = "0011110001101110111100110111001011111110100101001111100000000000";
buffer[3] = "1010010101001111111101010011101001011111000111010011100000000000";
buffer[4] = "0101000100001110010100100111111110101101111001101000000000000000";
buffer[5] = "1001101100000101011010001000110000101011001111100111000000000000";
buffer[6] = "0001111110000011110110011010101111111011010000011011110100000000";
buffer[7] = "0101101111100000110011010001100100010011011111100010000000000000";
return buffer;
}
public string[] SplitIntoBlock(string rawText)
{
var blocks = new List<string>();
for (int i = 0; i < rawText.Length; i+=1024)
{
blocks.Add(rawText.Substring(i, 1024));
}
return blocks.ToArray();
}
public string CompressThreeFactors(string factor1, string factor2, string factor3)
{
var part1 = factor1 + factor2;
var part2 = FlipBinaries(factor1) + factor3;
return XOR(part1, part2);
}
public string XOR(string string1, string string2)
{
if(string1.Length != string2.Length)
throw new ArithmeticException("Cannot XOR. Input lengths are not equal");
var sb = new StringBuilder();
for (int i = 0; i < string1.Length; i++)
{
sb.Append(string1[i].Equals(string2[i]) ? "0" : "1");
}
return sb.ToString();
}
public string FlipBinaries(string rawBinary)
{
var sb = new StringBuilder();
for (int i = 0; i < rawBinary.Length; i++)
{
sb.Append(rawBinary[i].Equals('0') ? "1" : "0");
}
return sb.ToString();
}
#endregion
}
}
|
C++
|
UTF-8
| 387 | 2.703125 | 3 |
[] |
no_license
|
#include <utility>
template<typename T>
Pimpl<T>::Pimpl() : p_{ new T{} } {}
template<typename T>
template<typename ...Args>
Pimpl<T>::Pimpl(Args&& ...args) : p_{ new T{std::forward<Args>(args)...} } {}
template<typename T>
Pimpl<T>::~Pimpl() {}
template<typename T>
T* Pimpl<T>::operator->() { return p_.get(); }
template<typename T>
T& Pimpl<T>::operator*() { return *p_.get(); }
|
Markdown
|
UTF-8
| 7,774 | 3.65625 | 4 |
[] |
no_license
|
# 14503\(๋ก๋ด ์ฒญ์๊ธฐ\)
## ๋ฌธ์
๋ก๋ด ์ฒญ์๊ธฐ๊ฐ ์ฃผ์ด์ก์ ๋, ์ฒญ์ํ๋ ์์ญ์ ๊ฐ์๋ฅผ ๊ตฌํ๋ ํ๋ก๊ทธ๋จ์ ์์ฑํ์์ค.
๋ก๋ด ์ฒญ์๊ธฐ๊ฐ ์๋ ์ฅ์๋ NรM ํฌ๊ธฐ์ ์ง์ฌ๊ฐํ์ผ๋ก ๋ํ๋ผ ์ ์์ผ๋ฉฐ, 1ร1ํฌ๊ธฐ์ ์ ์ฌ๊ฐํ ์นธ์ผ๋ก ๋๋์ด์ ธ ์๋ค. ๊ฐ๊ฐ์ ์นธ์ ๋ฒฝ ๋๋ ๋น ์นธ์ด๋ค. ์ฒญ์๊ธฐ๋ ๋ฐ๋ผ๋ณด๋ ๋ฐฉํฅ์ด ์์ผ๋ฉฐ, ์ด ๋ฐฉํฅ์ ๋, ์, ๋จ, ๋ถ์ค ํ๋์ด๋ค. ์ง๋์ ๊ฐ ์นธ์ \(r, c\)๋ก ๋ํ๋ผ ์ ์๊ณ , r์ ๋ถ์ชฝ์ผ๋ก๋ถํฐ ๋จ์ด์ง ์นธ์ ๊ฐ์, c๋ ์์ชฝ์ผ๋ก ๋ถํฐ ๋จ์ด์ง ์นธ์ ๊ฐ์์ด๋ค.
๋ก๋ด ์ฒญ์๊ธฐ๋ ๋ค์๊ณผ ๊ฐ์ด ์๋ํ๋ค.
1. ํ์ฌ ์์น๋ฅผ ์ฒญ์ํ๋ค.
2. ํ์ฌ ์์น์์ ํ์ฌ ๋ฐฉํฅ์ ๊ธฐ์ค์ผ๋ก ์ผ์ชฝ๋ฐฉํฅ๋ถํฐ ์ฐจ๋ก๋๋ก ํ์์ ์งํํ๋ค.
1. ์ผ์ชฝ ๋ฐฉํฅ์ ์์ง ์ฒญ์ํ์ง ์์ ๊ณต๊ฐ์ด ์กด์ฌํ๋ค๋ฉด, ๊ทธ ๋ฐฉํฅ์ผ๋ก ํ์ ํ ๋ค์ ํ ์นธ์ ์ ์งํ๊ณ 1๋ฒ๋ถํฐ ์งํํ๋ค.
2. ์ผ์ชฝ ๋ฐฉํฅ์ ์ฒญ์ํ ๊ณต๊ฐ์ด ์๋ค๋ฉด, ๊ทธ ๋ฐฉํฅ์ผ๋ก ํ์ ํ๊ณ 2๋ฒ์ผ๋ก ๋์๊ฐ๋ค.
3. ๋ค ๋ฐฉํฅ ๋ชจ๋ ์ฒญ์๊ฐ ์ด๋ฏธ ๋์ด์๊ฑฐ๋ ๋ฒฝ์ธ ๊ฒฝ์ฐ์๋, ๋ฐ๋ผ๋ณด๋ ๋ฐฉํฅ์ ์ ์งํ ์ฑ๋ก ํ ์นธ ํ์ง์ ํ๊ณ 2๋ฒ์ผ๋ก ๋์๊ฐ๋ค.
4. ๋ค ๋ฐฉํฅ ๋ชจ๋ ์ฒญ์๊ฐ ์ด๋ฏธ ๋์ด์๊ฑฐ๋ ๋ฒฝ์ด๋ฉด์, ๋ค์ชฝ ๋ฐฉํฅ์ด ๋ฒฝ์ด๋ผ ํ์ง๋ ํ ์ ์๋ ๊ฒฝ์ฐ์๋ ์๋์ ๋ฉ์ถ๋ค.
๋ก๋ด ์ฒญ์๊ธฐ๋ ์ด๋ฏธ ์ฒญ์๋์ด์๋ ์นธ์ ๋ ์ฒญ์ํ์ง ์์ผ๋ฉฐ, ๋ฒฝ์ ํต๊ณผํ ์ ์๋ค.
### ์
๋ ฅ
์ฒซ์งธ ์ค์ ์ธ๋ก ํฌ๊ธฐ N๊ณผ ๊ฐ๋ก ํฌ๊ธฐ M์ด ์ฃผ์ด์ง๋ค. \(3 โค N, M โค 50\)
๋์งธ ์ค์ ๋ก๋ด ์ฒญ์๊ธฐ๊ฐ ์๋ ์นธ์ ์ขํ \(r, c\)์ ๋ฐ๋ผ๋ณด๋ ๋ฐฉํฅ d๊ฐ ์ฃผ์ด์ง๋ค. d๊ฐ 0์ธ ๊ฒฝ์ฐ์๋ ๋ถ์ชฝ์, 1์ธ ๊ฒฝ์ฐ์๋ ๋์ชฝ์, 2์ธ ๊ฒฝ์ฐ์๋ ๋จ์ชฝ์, 3์ธ ๊ฒฝ์ฐ์๋ ์์ชฝ์ ๋ฐ๋ผ๋ณด๊ณ ์๋ ๊ฒ์ด๋ค.
์
์งธ ์ค๋ถํฐ N๊ฐ์ ์ค์ ์ฅ์์ ์ํ๊ฐ ๋ถ์ชฝ๋ถํฐ ๋จ์ชฝ ์์๋๋ก, ๊ฐ ์ค์ ์์ชฝ๋ถํฐ ๋์ชฝ ์์๋๋ก ์ฃผ์ด์ง๋ค. ๋น ์นธ์ 0, ๋ฒฝ์ 1๋ก ์ฃผ์ด์ง๋ค. ์ฅ์์ ๋ชจ๋ ์ธ๊ณฝ์ ๋ฒฝ์ด๋ค.
๋ก๋ด ์ฒญ์๊ธฐ๊ฐ ์๋ ์นธ์ ์ํ๋ ํญ์ ๋น ์นธ์ด๋ค.
### ์ถ๋ ฅ
๋ก๋ด ์ฒญ์๊ธฐ๊ฐ ์ฒญ์ํ๋ ์นธ์ ๊ฐ์๋ฅผ ์ถ๋ ฅํ๋ค.
## CODE
```java
import java.util.Scanner;
public class Main {
static int dir[][] = {{-1,0},{0,1},{1,0},{0,-1}}; //0๋ถ, 1๋, 2๋จ, 3์
static int room[][];
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scan = new Scanner(System.in);
int n, m;
int r, c, d;
n = scan.nextInt();
m = scan.nextInt();
r = scan.nextInt();
c = scan.nextInt();
d = scan.nextInt();
room = new int[n][m];
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
room[i][j] = scan.nextInt();
}
}
Robot rb = new Robot(d, r ,c);
rb.clean(room, dir, n, m);
System.out.println(rb.cleanNum);
}
}
class Robot{
public int direction;
public int r; //ํ
public int c; //์ด
public int cleanNum;
public Robot(int direction, int r, int c) {
this.direction = direction;
this.r = r;
this.c = c;
cleanNum = 0;
}
public void turnLeft() {
if(direction == 0)
direction = 3;
else if(direction == 1)
direction = 0;
else if(direction == 2)
direction = 1;
else
direction = 2;
}
public int backDir() {
if(direction == 0)
return 2;
else if(direction == 1)
return 3;
else if(direction == 2)
return 0;
else
return 1;
}
public void clean(int room[][], int dir[][], int n, int m) {
while(true) {
int dirtySpace = 4;
if(room[r][c] == 0) {
room[r][c] = 2;
cleanNum++;
}
for(int i = 0; i < 4; i++) {
turnLeft();
int nextR = r + dir[direction][0];
int nextC = c + dir[direction][1];
if(nextR >= n || nextR < 0 || nextC >= m || nextC < 0 || room[nextR][nextC] != 0) {
dirtySpace--;
}
else {
r = nextR;
c = nextC;
break;
}
}
if(dirtySpace == 0) {
int backR = r + dir[backDir()][0];
int backC = c + dir[backDir()][1];
if(backR >= n || backR < 0 || backC >= m || backC < 0 || room[backR][backC] == 1)
break;
else {
r = backR;
c = backC;
}
}
}
}
}
```
## CODE 2 \_ 200320\(0:43 ์์\)
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static int dir[][] = { { -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, -1 } };
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int map[][] = new int[n][m];
st = new StringTokenizer(br.readLine());
int rRow = Integer.parseInt(st.nextToken());
int rCol = Integer.parseInt(st.nextToken());
int rDir = Integer.parseInt(st.nextToken());
for (int i = 0; i < n; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < m; j++) {
map[i][j] = Integer.parseInt(st.nextToken());
}
}
int answer = 0;
while (true) {
if (map[rRow][rCol] == 0) {
answer++;
map[rRow][rCol] = 2;
}
boolean allClear = true;
for (int d = 0; d < 4; d++) {
rDir--;
if (rDir < 0)
rDir = 3;
int nextRow = rRow + dir[rDir][0];
int nextCol = rCol + dir[rDir][1];
if (map[nextRow][nextCol] == 0) {
rRow = nextRow;
rCol = nextCol;
allClear = false;
break;
}
}
if (allClear) {
int backDir = (rDir + 2) % 4;
int backRow = rRow + dir[backDir][0];
int backCol = rCol + dir[backDir][1];
if (map[backRow][backCol] == 1)
break;
else {
rRow = backRow;
rCol = backCol;
}
}
}
System.out.println(answer);
}
}
```
## CODE 3 \_ 200520\(0:28 ์์\)
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
class Main {
static int dir[][] = { { -1, 0 }, { 0, 1 }, { 1, 0 }, { 0, -1 } };
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int map[][] = new int[n][m];
st = new StringTokenizer(br.readLine());
int row = Integer.parseInt(st.nextToken());
int col = Integer.parseInt(st.nextToken());
int d = Integer.parseInt(st.nextToken());
for (int i = 0; i < n; i++) {
st = new StringTokenizer(br.readLine());
for (int j = 0; j < m; j++) {
map[i][j] = Integer.parseInt(st.nextToken());
}
}
int answer = 0;
boolean visitCheck[][] = new boolean[n][m];
while (true) {
if (!visitCheck[row][col]) {
visitCheck[row][col] = true;
answer++;
}
boolean existDirty = false;
int nextD = d;
for (int i = 0; i < 4; i++) {
nextD--;
if (nextD == -1)
nextD = 3;
int nextRow = row + dir[nextD][0];
int nextCol = col + dir[nextD][1];
if (nextRow > -1 && nextRow < n && nextCol > -1 && nextCol < m && map[nextRow][nextCol] != 1
&& !visitCheck[nextRow][nextCol]) {
existDirty = true;
row = nextRow;
col = nextCol;
d = nextD;
break;
}
}
if (!existDirty) {
int nextRow = row + dir[(d + 2) % 4][0];
int nextCol = col + dir[(d + 2) % 4][1];
if (nextRow > -1 && nextRow < n && nextCol > -1 && nextCol < m && map[nextRow][nextCol] != 1) {
row = nextRow;
col = nextCol;
} else {
break;
}
}
}
System.out.println(answer);
}
}
```
|
Java
|
UTF-8
| 676 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
package in.sapk.grava.game;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
/**
* Created by george on 27/05/15.
*/
public class SideTest {
@Test
public void testGetValue_A() {
Side side = Side.A;
assertEquals(0, side.getValue());
}
@Test
public void testGetValue_B() {
Side side = Side.B;
assertEquals(1, side.getValue());
}
@Test
public void testGetOpposite_A() {
Side side = Side.A;
assertEquals(Side.B, side.getOpposite());
}
@Test
public void testGetOpposite_B() {
Side side = Side.B;
assertEquals(Side.A, side.getOpposite());
}
}
|
C++
|
UTF-8
| 598 | 3.0625 | 3 |
[] |
no_license
|
vector<int> topoSort(int V, vector<int> adj[])
{
// code here
vector<int> indegree(V,0);
for(int i = 0; i<V;i++){
for(int x : adj[i]){
indegree[x]++;
}
}
queue<int> q;
for(int i=0;i<V;i++){
if(indegree[i]==0){
q.push(i);
}
}
vector<int> ans;
while(!q.empty()){
int temp = q.front();
q.pop();
ans.push_back(temp);
for(int x : adj[temp]){
if(--indegree[x]==0){
q.push(x);
}
}
}
return ans;
}
|
Shell
|
UTF-8
| 951 | 3.015625 | 3 |
[
"MIT"
] |
permissive
|
#!/bin/bash
fsf_list=( /Users/boo/Documents/degree_PhD/data_fmri/analysis_MVPA/fsl_glm_wft4_w8s_lc_w8s*)
for i in "${fsf_list[@]}"; do
fsf_list2=($i/*.nii)
for dd in "${fsf_list2[@]}"; do
IN=$dd
arrIN=(${IN//analysis_MVPA\// })
file_name=${arrIN[1]}
IN=$file_name
arrIN=(${IN//\// })
folder_name2=${arrIN[0]}
IN=$file_name
arrIN=(${IN//sub/ })
sub=${arrIN[1]}
IN=$sub
arrIN=(${IN//_s/ })
sub=${arrIN[0]}
IN=$IN
arrIN=(${IN//_s/ })
sess=${arrIN[1]}
IN=$sess
arrIN=(${IN//.nii/ })
sess=${arrIN[0]}
p1="flirt -in $dd "
p2=" -ref /usr/local/fsl/data/standard/MNI152_T1_2mm_brain.nii.gz "
p22="-out /Users/boo/Documents/degree_PhD/data_fmri/analysis_MVPA/"$folder_name2"/mni_sub"$sub"_s"$sess".nii"
p3=" -init /Users/boo/Documents/degree_PhD/data_fmri/collection_fun2stand_reg/fun2stand_sub"$sub"_s"$sess".mat -applyxfm"
$p1$p2$p22$p3
done
done
|
PHP
|
UTF-8
| 787 | 2.765625 | 3 |
[] |
no_license
|
<?php
declare(strict_types=1);
namespace Mvannes\JwtParser\Validator\Constraint;
use Mvannes\JwtParser\Token\TokenInterface;
class ValidNotBeforeConstraint implements TokenSyntaxConstraintInterface
{
private const NOT_BEFORE_CLAIM_NAME = 'nbf';
private $validAt;
public function __construct(\DateTime $validAt = null)
{
$this->validAt = $validAt;
}
public function tokenIsValid(TokenInterface $token): bool
{
$tokenNotBeforeTime = $token->getClaim(self::NOT_BEFORE_CLAIM_NAME);
if (null === $tokenNotBeforeTime) {
return false;
}
$tokenNotBeforeDate = new \DateTime("@$tokenNotBeforeTime");
$validAt = $this->validAt ?? new \DateTime();
return $tokenNotBeforeDate <= $validAt;
}
}
|
JavaScript
|
UTF-8
| 4,733 | 3.421875 | 3 |
[] |
no_license
|
var inputCheck = document.getElementById("inputCheck");
var inputPrevious = document.getElementById("inputPrevious");
var inputNext = document.getElementById("inputNext");
var textResultCheck = document.getElementById("resultCheck");
var textResultPrevious = document.getElementById("resultPrevious");
var textResultNext = document.getElementById("resultNext");
var themeButton = document.getElementById("themeButton");
var khakiTheme = 'css/khakiTheme.css';
var greyTheme = 'css/greyTheme.css';
var activeTheme;
var n, resBool, resInt;
var arrDivs = ["check", "previous", "next"];
function setStorage(strInput){
var input = document.getElementById("input" + strInput);
var aux1, aux2;
/* Reordenar elementos en localStorage y en HTML para que aparezcan
con el mรกs reciente arriba del todo y el mรกs antiguo abajo */
for(i = 1; i <= 5; i++){
if(i % 2 != 0){
aux1 = localStorage.getItem(i.toString());
if(i == 1)
localStorage.setItem(i.toString(), input.value.toString());
else
localStorage.setItem(i.toString(), aux2.toString());
}
else{
aux2 = localStorage.getItem(i.toString());
localStorage.setItem(i.toString(), aux1.toString());
}
document.getElementById("hist" + i.toString()).innerHTML = localStorage.getItem(i.toString());
}
}
function loadStorage(){
for(i = 1; i <= 5; i++)
document.getElementById("hist" + i.toString()).innerHTML = localStorage.getItem(i.toString());
if (localStorage.getItem("theme") != null){
document.getElementById("theme").href = localStorage.getItem("theme");
activeTheme = localStorage.getItem("theme");
}
else{
document.getElementById("theme").href = greyTheme;
activeTheme = greyTheme;
}
}
function setTheme(theme) {
document.getElementById("theme").href = theme;
localStorage.setItem("theme", theme);
activeTheme = theme;
}
themeButton.addEventListener("click", function(e){
if(activeTheme == greyTheme)
setTheme(khakiTheme);
else
setTheme(greyTheme);
});
inputCheck.addEventListener("keydown", function (e) {
if (e.keyCode === 13){ //controla que la tecla presionada sea enter
n = inputCheck.value;
resBool = checkPrime(n);
assignTextResCheck(resBool);
colorResCheck(resBool);
setStorage("Check");
}
});
inputPrevious.addEventListener("keydown", function (e) {
if (e.keyCode === 13){
n = inputPrevious.value;
resInt = previousPrime(n);
assignTextResPrev(resInt);
setStorage("Previous");
}
});
inputNext.addEventListener("keydown", function (e) {
if (e.keyCode === 13){
n = inputNext.value;
resInt = nextPrime(n);
assignTextResNext(resInt);
setStorage("Next");
}
});
function checkPrime(n){
if (n <= 1) return false;
if (n <= 3) return true;
if (n % 2 == 0 || n % 3 == 0)
return false;
for (var i = 5; i * i <= n; i = i + 6)
if (n % i == 0 || n % (i + 2) == 0)
return false;
return true;
}
function previousPrime(n){
var i, j, winner;
var arr = [0, 0];
for(i = 2; i <= n; ++i)
arr[i] = 1;
for(i = 2; i < n; ++i) {
if(arr[i]) {
winner = i;
for(j = i+i; j < n; j += i)
arr[j] = 0;
}
}
return winner;
}
function nextPrime(n){
if (n <= 1)
return 2;
var aux = n;
var found = false;
// Loopea continuamente hasta que checkPrime devuelve
// true para un nรบmero mรกs grande que n
while (!found){
aux++;
if (checkPrime(aux))
found = true;
}
return aux;
}
function assignTextResCheck(res){
if(res == true)
textResultCheck.innerHTML = "es un nรบmero primo";
else
textResultCheck.innerHTML = "no es un nรบmero primo";
}
function assignTextResPrev(res){
textResultPrevious.innerHTML = res;
}
function assignTextResNext(res){
textResultNext.innerHTML = res;
}
function colorResCheck(bool){
if(bool == true)
textResultCheck.className = "result true";
else
textResultCheck.className = "result false";
}
function showDiv(str) {
var divMostrar = document.getElementById(str + "Prime");
var divOcultar;
divMostrar.style.display = "block";
for(i = 0; i < 3; i++){
if(arrDivs[i] != str){
divOcultar = document.getElementById(arrDivs[i] + "Prime");
divOcultar.style.display = "none";
}
}
}
|
Shell
|
UTF-8
| 143 | 2.921875 | 3 |
[] |
no_license
|
#!/bin/sh
if grep "abc" file
then
echo file contains abc
else
echo file doesn\'t contain abc
fi
grep abc file
echo return code is $?
exit 0
|
Python
|
UTF-8
| 1,782 | 3.875 | 4 |
[] |
no_license
|
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def pushdata(self, new_data):
new_node = Node(new_data)
new_node.next = self.head
self.head = new_node
def insertAfterData(self,new_data,key):
tmp = self.head
if tmp is not None:
if tmp.data == key:
temp = tmp.next
tmp.next = Node(new_data)
tmp.next.next = temp
return
tmp = tmp.next
while tmp is not None:
if tmp.data == key:
temp = tmp.next
tmp.next = Node(new_data)
tmp.next.next = temp
break
tmp = tmp.next
def insertBeforeData(self,new_data,key):
tmp = self.head
if tmp is not None:
if tmp.data == key:
temp = Node(new_data)
temp.next = tmp
self.head = temp
return
while tmp is not None:
if tmp.next.data == key:
temp = tmp.next
tmp.next = Node(new_data)
tmp.next.next = temp
break
tmp = tmp.next
def printList(self):
tmp = self.head
while(tmp):
print(tmp.data,end="")
if tmp.next:
print("->",end="")
tmp = tmp.next
print()
if __name__ == "__main__":
llist = LinkedList()
llist.pushdata(20)
llist.pushdata(10)
llist.pushdata(40)
llist.pushdata(50)
llist.printList()
llist.insertAfterData(30,10)
llist.printList()
llist.insertBeforeData(90,40)
llist.printList()
|
Java
|
UTF-8
| 5,554 | 2.140625 | 2 |
[
"BSD-2-Clause"
] |
permissive
|
/**
* Copyright (c) 2003-2010, Xith3D Project Group all rights reserved.
*
* Portions based on the Java3D interface, Copyright by Sun Microsystems.
* Many thanks to the developers of Java3D and Sun Microsystems for their
* innovation and design.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the 'Xith3D Project Group' nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) A
* RISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE
*/
package org.xith3d.render.preprocessing;
import org.openmali.spatial.bodies.Classifier;
import org.xith3d.render.preprocessing.sorting.RenderBinSorter;
import org.xith3d.scenegraph.Node;
import org.xith3d.scenegraph.Transform3D;
/**
* Contains and maintains all RenderBins, which on their part may contain all
* RenderAtoms of the whole scenegraph.
*
* @author David Yazel
* @author Marvin Froehlich (aka Qudus)
*/
public class RenderBinProvider
{
protected RenderBin opaqueBin;
protected RenderBin transparentBin;
protected RenderBin shadowsBin;
public RenderBinProvider( RenderBin opaqueBin, RenderBin transparentBin, RenderBin shadowsBin )
{
this.opaqueBin = opaqueBin;
this.transparentBin = transparentBin;
this.shadowsBin = shadowsBin;
}
public RenderBinProvider()
{
this( new RenderBin( RenderBinType.MAIN_OPAQUE, "Main Opaque RenderBin", 2048 ),
new RenderBin( RenderBinType.MAIN_TRANSPARENT, "Main Transparent RenderBin", 128 ),
new RenderBin( RenderBinType.MAIN_OPAQUE, "Shadows RenderBin", 2048 )
);
}
public final RenderBin getOpaqueBin()
{
return ( opaqueBin );
}
public final RenderBin getTransparentBin()
{
return ( transparentBin );
}
public final RenderBin getShadowsBin()
{
return ( shadowsBin );
}
public final int getAtomsCount()
{
return ( transparentBin.size() + opaqueBin.size() );
}
/**
* Adds an atom to be rendered. The atoms are sorted into multiple render
* bins to facilitate multiple passes where necessary.
*
* @param atom
*/
public final void addMainAtom( RenderAtom< ? extends Node > atom, Classifier.Classification classify, long frameId )
{
if ( !atom.isTranslucent() )
opaqueBin.addAtom( atom, classify, frameId );
else
transparentBin.addAtom( atom, classify, frameId );
}
public final void addShadowAtom( RenderAtom< ? extends Node > atom, Classifier.Classification classify, long frameId )
{
shadowsBin.addAtom( atom, classify, frameId );
}
private static final void sortRenderBin( RenderBin renderBin, RenderBinSorter opaqueSorter, RenderBinSorter transparentSorter, Transform3D viewTransform )
{
if ( renderBin.size() > 0 )
{
if ( renderBin.getType().isTransparent() )
{
if ( transparentSorter != null )
transparentSorter.sortRenderBin( renderBin, viewTransform );
}
else
{
if ( opaqueSorter != null )
opaqueSorter.sortRenderBin( renderBin, viewTransform );
}
}
}
/**
* Sorts the RenderAtoms in the diverse RenderBins by policies.
*
* @param opaqueSorter the sorting policy for opaque shapes
* @param transparentSorter the sorting policy for transparent shapes
* @param viewTransform the View's transform
*/
public final void sortAllAtoms( RenderBinSorter opaqueSorter, RenderBinSorter transparentSorter, Transform3D viewTransform )
{
sortRenderBin( opaqueBin, opaqueSorter, transparentSorter, viewTransform );
sortRenderBin( transparentBin, opaqueSorter, transparentSorter, viewTransform );
sortRenderBin( shadowsBin, opaqueSorter, transparentSorter, viewTransform );
}
public final void clearAllBins()
{
opaqueBin.clear();
transparentBin.clear();
shadowsBin.clear();
}
public final void shrinkAllBins()
{
opaqueBin.shrink();
transparentBin.shrink();
shadowsBin.shrink();
}
}
|
C#
|
UTF-8
| 2,200 | 3.09375 | 3 |
[] |
no_license
|
๏ปฟnamespace DirkSarodnick.TS3_Bot.Core.Entity
{
using System;
/// <summary>
/// Defines the TimeClientEntity struct.
/// </summary>
[Serializable]
public class TimeClientEntity
{
/// <summary>
/// Initializes a new instance of the <see cref="TimeClientEntity"/> struct.
/// </summary>
public TimeClientEntity()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="TimeClientEntity"/> struct.
/// </summary>
/// <param name="userDatabaseId">The user database id.</param>
/// <param name="joined">The joined.</param>
/// <param name="disconnected">The disconnected.</param>
public TimeClientEntity(uint userDatabaseId, DateTime joined, DateTime? disconnected = null)
{
User = userDatabaseId;
Joined = joined;
Disconnected = disconnected ?? DateTime.UtcNow;
}
/// <summary>
/// Gets or sets the user.
/// </summary>
/// <value>
/// The user.
/// </value>
public uint User;
/// <summary>
/// Gets or sets the joined.
/// </summary>
/// <value>
/// The joined.
/// </value>
public DateTime Joined;
/// <summary>
/// Gets or sets the disconnected.
/// </summary>
/// <value>
/// The disconnected.
/// </value>
public DateTime Disconnected;
/// <summary>
/// Gets or sets the total minutes.
/// </summary>
/// <value>
/// The total minutes.
/// </value>
public int TotalMinutes;
public double GetTime(DateTime? fromTime, DateTime? toTime)
{
if (Joined.Date == Disconnected.Date || (!fromTime.HasValue && !toTime.HasValue)) return TotalMinutes;
var from = fromTime ?? DateTime.MinValue;
var to = toTime ?? DateTime.MaxValue;
var joined = Joined < from ? from : Joined;
var disconnected = Disconnected > to ? to : Disconnected;
return (disconnected - joined).TotalMinutes;
}
}
}
|
Java
|
UTF-8
| 3,840 | 3.234375 | 3 |
[] |
no_license
|
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Rectangle2D;
public class FractalExplorer {
private JFrame jFrame = new JFrame();
private JImageDisplay jImageDisplay;
private FractalGenerator fractalGenerator;
private Rectangle2D.Double range;
private int displaySize;
public FractalExplorer(int displaySize) {
this.displaySize = displaySize;
this.range = new Rectangle2D.Double();
this.fractalGenerator = new Mandelbrot();
fractalGenerator.getInitialRange(range);
}
public void createAndShowGUI(){
JButton jButton = new JButton("Reset Display");
jFrame.setLayout(new BorderLayout());
jImageDisplay = new JImageDisplay(displaySize,displaySize);
jFrame.add(jImageDisplay,BorderLayout.CENTER);
jButton.addActionListener(new ResetHandler());
jFrame.add(jButton,BorderLayout.SOUTH);
jFrame.setTitle("ะะตะฝะตัะฐัะพั ััะฐะบัะฐะปะพะฒ");
jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jFrame.addMouseListener(new MouseHandler());
drawFractal();
jImageDisplay.repaint();
jFrame.pack();
jFrame.setVisible(true);
jFrame.setResizable(false);
}
public static void main(String[] args) {
FractalExplorer fractalExplorer = new FractalExplorer(800);
fractalExplorer.createAndShowGUI();
fractalExplorer.drawFractal();
}
private void drawFractal(){
for (int x = 0; x < jImageDisplay.getBufferedImage().getWidth(); x++){
double xCoord = fractalGenerator.getCoord(range.x, range.x + range.width, displaySize, x);
for (int y = 0; y < jImageDisplay.getBufferedImage().getHeight(); y++){
double yCoord = fractalGenerator.getCoord(range.y, range.y + range.height, displaySize, y);
if (fractalGenerator.numIterations(xCoord,yCoord)==-1) {
jImageDisplay.drawPixel(x,y,0);
} else {
float hue = 0.7f + (float) fractalGenerator.numIterations(xCoord,yCoord) / 200f;
int rgbColor = Color.HSBtoRGB(hue, 1f, 1f);
jImageDisplay.drawPixel(x,y,rgbColor);
}
}
}
jImageDisplay.repaint();
}
private class ResetHandler implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
range = new Rectangle2D.Double();
fractalGenerator.getInitialRange(range);
drawFractal();
}
}
/**
* ะัะธ ะฟะพะปััะตะฝะธะธ ัะพะฑััะธั ะพ ัะตะปัะบะต ะผัััั, ะบะปะฐัั
* ะพัะพะฑัะฐะถะฐะตั ะฟะธะบัะตะปัะฝัะต ะบะพะพัะธะฝะฐัั ัะตะปัะบะฐ ะฒ ะพะฑะปะฐััั ััะฐะบัะฐะปะฐ, ะฐ ะทะฐัะตะผ ะฒัะทัะฒะฐะตั
* ะผะตัะพะด ะณะตะฝะตัะฐัะพัะฐ recenterAndZoomRange() ั ะบะพะพัะดะธะฝะฐัะฐะผะธ, ะฟะพ ะบะพัะพััะผ
* ะฟัะพะธะทะพัะตะป ะบะปะธะบ, ะธ ะผะฐัััะฐะฑะพะผ 0.5. ะขะฐะบะธะผ ะพะฑัะฐะทะพะผ, ะฝะฐะถะธะผะฐั ะฝะฐ ะบะฐะบะพะต-ะปะธะฑะพ ะผะตััะพ ะฝะฐ
* ััะฐะบัะฐะปัะฝะพะผ ะพัะพะฑัะฐะถะตะฝะธะธ, ะธะทะพะฑัะฐะถะตะฝะธะต ัะฒะตะปะธัะธะฒะฐะตััั.
*/
private class MouseHandler extends MouseAdapter
{
public void mouseClicked(MouseEvent e)
{
double xCoord = FractalGenerator.getCoord(range.x, range.x + range.width,
displaySize, e.getX());
double yCoord = FractalGenerator.getCoord(range.y, range.y + range.height,
displaySize, e.getY());
fractalGenerator.recenterAndZoomRange(range,xCoord, yCoord, 0.5);
drawFractal();
}
}
}
|
C
|
UTF-8
| 3,403 | 2.90625 | 3 |
[] |
no_license
|
/* db_recrd.c */
/* */
/* The purpose of this program is to display data for a specified part */
/* number; this data can be amended if required. */
/*
DB_RECRD.C
The purpose of this program is to display data for a specified part number
from a parts database; this data can be amended if required.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//#include <alloc.h>
#include "../ck_utils/ck_types.h"
#include "../ck_utils/ck_utils.h"
void main(int argc,
char *argv[])
{
// FILE *fptr_in;
FILE *fptr_db;
char part_number[10];
char description[100];
struct part_info *base_ptr;
struct part_info *part_ptr;
// int i, j;
int field;
int number;
float f_number;
if ((fptr_db = fopen(argv[1],"rb")) == NULL)
{
printf("Cannot open file %s \n",argv[1]);
exit(0);
}
if ((base_ptr = read_tgt_dbase(fptr_db)) == NULL)
{
printf("Insufficient memory for target database\n");
exit(0);
}
else
{
for (;;)
{
printf("Enter part number : ");
gets(part_number);
_flushall();
if (part_number[0] == '\0')
break;
printf("\n");
if ((part_ptr = find_part(part_number,
base_ptr)) != NULL)
{
display_part_data(part_ptr);
do {
printf("Update field (0 for none or number) : ");
scanf("%d",&field);
_flushall();
switch (field)
{
case 1: /* Description */
printf("\nNew description : ");
gets(description);
strcpy(part_ptr->description,description);
display_part_data(part_ptr);
break;
case 2: /* Stock */
printf("\nEnter stock : ");
scanf("%d",&number);
if (number >= 0 &&
number < 1000)
{
part_ptr->stock = number;
display_part_data(part_ptr);
}
break;
case 3: /* Re-order level */
printf("\nEnter re-order level : ");
scanf("%d",&number);
if (number >= 0 &&
number < 1000)
{
part_ptr->order_level = number;
display_part_data(part_ptr);
}
break;
case 4: /* Trade cost */
printf("\nEnter trade cost : ");
scanf("%6.2f",&f_number);
if (f_number >= 0.0 &&
f_number < 1000.00)
{
part_ptr->trade_cost = f_number;
display_part_data(part_ptr);
}
break;
case 5: /* Retail price */
printf("\nEnter retail price : ");
scanf("%6.2f",&f_number);
if (f_number >= 0.0 &&
f_number < 1000.00)
{
part_ptr->retail_cost = f_number;
display_part_data(part_ptr);
}
break;
default :
;
break;
}
_flushall();
} while (field != 0);
}
else
printf("Part not found\n");
_flushall();
}
}
_fcloseall();
} /* main() */
|
Java
|
UTF-8
| 761 | 3.078125 | 3 |
[] |
no_license
|
package com.mrgn.app;
public class DemoClass implements MyInterface {
@Override
public void method1() {
System.out.println("method 1 Implementation");
}
@Override
public void method2() {
System.out.println("method 2 Implementation");
}
@Override
public void method3() {
// TODO Auto-generated method stub
System.out.println("method 3 Implementation");
}
@Override
public void method4() {
System.out.println("method 4 Implementation");
}
public static void main(String[] args) {
System.out.println("Demo CI Test");
MyInterface myInterface = new DemoClass();
myInterface.method1();
myInterface.method2();
myInterface.method3();
myInterface.method4();
}
}
|
Java
|
UTF-8
| 801 | 2.5625 | 3 |
[] |
no_license
|
import org.testng.annotations.DataProvider;
/**
* The DataProvider, which passes a list of list of Objects to the @Test with
* the corresponding dataprovider attribute to be used as parameters to that
* test method. Essentially a form of parameterization.
*/
public class DataProviderMemeExercise {
/**
* Meme exercise object [ ] [ ] -- the DataProvider that is used in the
* "Meme Exercise" test to perform the parameterization.
*
* @return the object [ ] [ ] The data (passed via TestNG to the test).
*/
@DataProvider
public static Object[][] memeExercise() {
return new Object[][]{
{"internetmemes_backup.json",
"internetmemes.json",
"internetmemes_output.json"}
};
}
}
|
Python
|
UTF-8
| 982 | 3.3125 | 3 |
[] |
no_license
|
import unittest
import requests
from populace import _change_in_latitude, _change_in_longitude
class TestMilesToLatLng(unittest.TestCase):
def test_change_in_latitude(self):
"""
Test method correct latitude adjustment
"""
result = _change_in_latitude(100)
self.assertEqual(result, 1.4468631190172303)
def test_change_in_longitude(self):
"""
Test method returns correct longitude adjustment
"""
result = _change_in_longitude(10,100)
self.assertEqual(result, 1.4691833148061078)
def test_throws_exception_if_invalid_argument(self):
"""
Test methods throw TypeErrors if non numeric arguments passed
"""
with self.assertRaises(TypeError):
_change_in_latitude("bob")
with self.assertRaises(TypeError):
_change_in_longitude("ted", 100)
with self.assertRaises(TypeError):
_change_in_longitude(10, "alice")
|
Markdown
|
UTF-8
| 5,568 | 3.28125 | 3 |
[] |
no_license
|
# Aquarius
- January 20 - February 18
- Music: alternative/ electronic
- As an aquarius, you are an air sign, independent, and free spirited. You are innovative, imaginative, and a little rebellious. Alternative music is a great fit for you because it doesn't follow anyone else's rules. Alternative music is filled with persoanlity and originality, making it one of a kind, like you. The artists of this genre have a rebellious side to their music, embracing and showing off their unique style.
---
# Pisces
- February 19 - March 20
- Music: indie
- As a Pisces, you are a water sign, having the deepest connection to music. You have many emotions and think deeply, leading you to be artistic, romantic, intuitive, and original. For you, music is an escape from reality, getting you in touch with your emotions. Indie music is a great fit for you because it is complex in beats and lyrics, feeding your need to get in touch with your emotions.
---
# Aries
- March 21 - April 19
- Music: rock
- As an Aries, you are a fire sign, filled with adrenaline, constantly on the move. You are passionate and true to yourself. You are energetic, dynamic, charismatic, honest, and a little bit crazy. Rock music is a great fit for you because it is upbeat music that will keep up with your pace. Rock music has a good beat behind it and meaningful lyrics.
---
# Taurus
- April 20 - May 20
- Music: the classics
- As a Tarus, you are an earth sign ruled by venus, the planet of beauty, music, and art. You are relaxed and find comfort in listening to songs that remind you of good times. You are most at home when listening to the classics, reminiscing on the history of music. The classics remind you of a better time, a time when musicians were really about the music.
---
# Gemini
- May 21 - June 20
- Music: dance, techno, edm
- As a Gemini, you are an air sign, gentle and affectonate. You are high energy and versitle, always moving, always on the go. You are free-spirited and highly expressive. You consider music an important learning experience and you love teaching people new things about music. Dance music is the best fit for you because it keeps you dancing/ on your feet. With all that energy pent up, you need a genre that you can really dance to.
---
# Cancer
- June 21 - July 22
- Music: Blues/ R&B
- As a Cancer, you are a water sign, ruled by feelings. You are loyal, emotional, immaginative, sentimental and compassionate. You think deeply and love to support/ care for others. Blues/ R&B is the best fit for you beause it can be dark, but it can also be loving and lively. Blues music is about getting swept up in the magic of the song. The beats and lyrics of this genre trigger emotions, touching the heart and soul of the listener.
---
# Leo
- Juy 23 - August 22
- Pop
- As a Leo, you are a fire sign, the kings and ueens of the zodiac. You are a leader, someone popular, outgoing, and friendly. Popular music resonates with you, as it is also the center of attention. You love songs you can sing and dance to, and you've alwyas got the newest singles playing. You are invested in the whole musical experience, following the musicians rather than just the music.
---
# Virgo
- August 23 - September 22
- Classical
- As a Virgo, you are an earth sign, peaceful and calm. You are warm, caring, intelligent, analytical, and kind. You appreciate the sounds of nature and soothing tunes that can help calm your nerves. Classical music is the best fit for you because it is the cleanest most intellectual type of music. As one of the most intelligent signs, this music allows you to search within, tapping into your intellectual side.
---
# Libra
- September 23 - October 22
- Country
- As a Libra, you are an air sign ruled by venus, making you the ultimate social sign. You are also loving and gracious. As a social creature, you relate best to mysic that gives you the opportunity to incorporate your favorite songs into whatever you do. Country music is the best fit for you because it is a catchy beat with meaningful lyrics. Country lyrics are about love and relating to others, two things that resonate with you.
---
# Scorpio
- Octover 23 - November 21
- rap/ hip-hop
- As a Scorpio, you are a water sign, passionate and emotional. You are resourceful, brave, intense, and passionate. Rap/ hip-hop is the best fit for you because it is intense music that sigs into the soul. There's a lot of passion in the lyrics as well as a strong beat. These songs read more like poems, and you like that this is a different outlet for emotions than simply talking about them.
---
# Sagittarius
- November 22 - December 21
- Music: world music
- As a saggitatrius, you are a fire sign, openminded and idealistic. You have a great sense of humor and a love for culture, spirituality, and religion. World music is the best fit for you because it embodies different cultures and allows you to embrace and celebrate other cultures. You hate limiting yourself to one kind of music. You also like this genre for the emotion and catchiness of the songs, enjoying music that makes you want to get on your feet and dance.
---
# Capricorn
- December 22 - January 19
- Jazz
- As a Capricorn, you are an earth sign, sophisticated and hard working. You are intelligent, making your own rules in life and working hard toward your goals. Jazz is the best fit for you because it is sophisticated music that takes work and dedication to craft. Just like you, this genre does not abide by any other rules. Jazz is more than just a music genre, it is like a representation of you.
|
Python
|
UTF-8
| 120 | 2.578125 | 3 |
[] |
no_license
|
class test:
s1 = ('this is class varible')
@classmethod
def show(cls):
print(cls.s1)
test.show()
|
Markdown
|
UTF-8
| 5,168 | 2.921875 | 3 |
[
"Apache-2.0"
] |
permissive
|
## Building from the Command Line
The command-line version of Turbo Studio is called <b>XStudio.exe</b> and can be found in the Turbo Studio installation directory. See below for a list of command-line arguments and options for the XStudio tool.
<table>
<tr>
<th>Command</th>
<th>Usage</th>
<th>Description</th>
</tr>
<tr>
<td><strong><span><path to XAPPL configuration file></span></strong></td>
<td><span>/l <path to license file> [/o <path to output>] [/component] [/d] [/compressed] [/uncompressed] [/deletesandbox] [/v <version>] [/startupfile <virtual path to file>]</span></td>
<td>
<p>Builds the virtual application based on the application configuration file.</p>
<p>/l - Path the the license file. <span>The license file needs to be stored in Unicode format.</span></p>
<p>/o - Path to the output file. This will override the setting in the XAPPL <span>configuration </span>file.</p>
<p>/component - Sets the <strong>Project Type</strong> to <em>Component</em> resulting in an SVM output rather than EXE output. </p>
<p>/d - Enables the <strong>Generate diagnostic-mode executable </strong>setting.</p>
<p>/compressed - Enables the <strong>Compress payload</strong> setting.</p>
<p>/uncompressed - Disables the <strong>Compress payload</strong> setting.</p>
<p>/deletesandbox - Enables the <strong>Delete sandbox on application shutdown</strong> setting.</p>
<p>/v - Sets the <strong>Version </strong>of the output exe.</p>
<p>/startupfile - Sets the <strong>Startup File</strong> of the virtual application.</p>
</td>
</tr>
<tr>
<td>
<p><strong>/before</strong></p>
</td>
<td>/beforepath <path to where snapshot file is saved></td>
<td>
<p>Performs a before snapshot and saves the snapshot to the specified folder.</p>
<p>/beforepath - Path to the where the snapshot file is saved.</p>
</td>
</tr>
<tr>
<td>
<p><strong>/after</strong></p>
</td>
<td>
<p>/beforepath <path to where snapshot is saved> /o <path to where XAPPL configuration file is saved></p>
</td>
<td>
<p>Performs an after snapshot using the specified before snapshot path.</p>
<p>/beforepath - Path to the before snapshot file.</p>
<p>/o - Path to where the XAPPL configuration file is saved.</p>
</td>
</tr>
<tr>
<td>
<p><strong>/import</strong></p>
</td>
<td>/i <path to the configuration file to be imported> /o <span><path to where XAPPL configuration file is saved></span></td>
<td>
<p>Import MSI, AXT, or ThinApp configurations.</p>
<p>/i - Path to the configuration file to import.</p>
<p>/o - Path to where the <span>XAPPL configuration file is saved.</span></p>
</td>
</tr>
<tr>
<td>
<p><strong>/sandboxmerge</strong></p>
</td>
<td>/i <input-config> /o <output-config> <sandbox-path></td>
<td>
<p>Merge configuration and sandbox.</p>
<p>/i - Path to source configuration file.</p>
<p>/o - Path to output merged configuration file.</p>
<p>sandbox-path - Path to sandbox.</p>
</td>
</tr>
<tr>
<td>
<p><strong>/vmsettings</strong></p>
</td>
<td>/i <input-file-xappl-exe-svm> [name]</td>
<td>
<p>Getting virtualization settings from the configurations file or application.</p>
<p>/i - Path to the configuration file (xappl, exe or svm).</p>
<p>name - Name of settings or empty for all settings.</p>
</td>
</tr>
<tr>
<td>
<p><strong>/pathreplace</strong></p>
</td>
<td>[/reg] [/revert] <path></td>
<td>
<p>Replace path from native to virtual format.</p>
<p>/reg - Path is a register path instead of filesystem path.</p>
<p>/revert - Revert path from virtual to native format.</p>
<p>path - Path to replace.</p>
</td>
</tr>
<td>
<p><strong>/nologo</strong></p>
</td>
<td></td>
<td>
<p>Switch for suppress printing copyrigth and logo information.</p>
</td>
</tr>
</table>
<br>
**Note:** Configuration files that are generated from the command-line after using the **/after** flag do not have an output file specified in the **XAPPL** configuration file. When using scripting for snapshots, it may be necessary to apply changes to the generated **XAPPL** file, either manually or programmatically.
**Note:** If running XStudio displays the error `<SandboxCollision> is missing from the string table` the XStudio application cannot be run while Turbo Studio is also running. Turbo Studio must be closed before running XStudio via the command line.
|
SQL
|
UTF-8
| 1,018 | 3.8125 | 4 |
[] |
no_license
|
drop schema IMS;
CREATE SCHEMA IF NOT EXISTS IMS;
use IMS;
CREATE TABLE Customer
(customer_id int NOT NULL AUTO_INCREMENT,
first_name varchar(20),
last_name varchar(20),
email varchar(20),
phone_num int,
CONSTRAINT PK_Customer PRIMARY KEY (customer_id));
CREATE TABLE IF NOT EXISTS Item
(item_id int NOT NULL AUTO_INCREMENT, item_name varchar(20),
size int, price int, stock int,
CONSTRAINT PK_ITEM PRIMARY KEY (item_id));
CREATE TABLE IF NOT EXISTS Order_
(order_id int NOT NULL AUTO_INCREMENT, order_date date, customer_id int NOT NULL,
CONSTRAINT PK_Order PRIMARY KEY (order_id),
CONSTRAINT FK_customer_id FOREIGN KEY (customer_id) REFERENCES Customer(customer_id));
CREATE TABLE IF NOT EXISTS Item_Order (order_id int NOT NULL ,
item_id int NOT NULL, quantity int,
CONSTRAINT PK_ItemOrder PRIMARY KEY (order_id, item_id),
CONSTRAINT FK_ItemOrder_Item FOREIGN KEY (item_id) REFERENCES Item(item_id),
CONSTRAINT FK_ItemOrder_order FOREIGN KEY (order_id) REFERENCES Order_(order_id));
|
Java
|
UTF-8
| 1,042 | 1.828125 | 2 |
[] |
no_license
|
package com.kitri.board.service;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.kitri.board.dao.AlbumDao;
import com.kitri.board.model.AlbumDto;
@Service
public class AlbumServiceImpl implements AlbumService {
@Autowired
private SqlSession sqlSession;
@Override
public int writeArticle(AlbumDto adto) {
return sqlSession.getMapper(AlbumDao.class).writeArticle(adto);
}
@Override
public AlbumDto getArticle(int seq) {
// TODO Auto-generated method stub
return null;
}
@Override
public List<AlbumDto> listArticle(int bcode, int pg, String key, String word) {
// TODO Auto-generated method stub
return null;
}
@Override
public int modifyArticle(AlbumDto adto) {
// TODO Auto-generated method stub
return 0;
}
@Override
public int deleteArticle(String seq) {
// TODO Auto-generated method stub
return 0;
}
}
|
Java
|
UTF-8
| 2,211 | 2.203125 | 2 |
[
"MIT"
] |
permissive
|
/**
*
*/
/**
*
* Copyright (c) 2012 <copyright Aruba spa>
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
*/
package whitelabel.cloud.adapter;
import java.text.ParseException;
import java.util.Date;
import java.util.Locale;
import org.springframework.format.datetime.DateFormatter;
/**
* @author Inspect.it
*
*/
public class DateFormatterExt extends DateFormatter {
public static String DATE_PATTERN = "dd/MM/yyyy";
public static String DATE_TIME_PATTERN = "dd/MM/yyyy HH:mm:ss";
public static Locale LOCALE = Locale.ITALIAN;
public DateFormatterExt() {
super();
}
public DateFormatterExt(String pattern) {
super(pattern);
}
public String print(Date data) {
return (data ==null ? "" : this.print(data, LOCALE));
}
@Override
public String print(Date data, Locale locale) {
return (data ==null ? "" : super.print(data, locale));
}
@Override
public Date parse(String text, Locale locale) throws ParseException {
if(text == null || text.trim().length() == 0){
return null;
}
else {
return super.parse(text, locale);
}
}
}
|
C#
|
UTF-8
| 2,645 | 2.53125 | 3 |
[] |
no_license
|
๏ปฟusing System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace fORMS
{
public partial class counter : Form
{
public counter()
{
InitializeComponent();
textBox7.Text = "50";
}
private void button2_Click(object sender, EventArgs e)
{
}
private void label5_Click(object sender, EventArgs e)
{
}
private void label8_Click(object sender, EventArgs e)
{
}
private void textBox4_TextChanged(object sender, EventArgs e)
{
}
private void label18_Click(object sender, EventArgs e)
{
}
private void timer1_Tick(object sender, EventArgs e)
{
TimeSpan delta = Program.start - DateTime.Now;
kakaxa.Text = delta.Days.ToString() + " ะะฝะตะน " + delta.Hours.ToString() + " ัะฐัะพะฒ " + delta.Minutes.ToString() + " ะะธะฝัั ะดะพ ััะฐััะฐ ะผะฐัะฐัะพะฝะฐ!";
}
private void button1_Click(object sender, EventArgs e)
{
int money = int.Parse(textBox7.Text);
if (money >= 20) money -= 10;
textBox7.Text = money.ToString();
}
private void button3_Click(object sender, EventArgs e)
{
int money = int.Parse(textBox7.Text);
money += 10;
textBox7.Text = money.ToString();
}
private void textBox7_TextChanged(object sender, EventArgs e)
{
label4.Text = "$" + textBox7.Text;
}
private void button4_Click(object sender, EventArgs e)
{
int money = int.Parse(textBox7.Text);
if (money > 0)
{
Sponsor reg = new Sponsor();
this.Hide();
reg.ShowDialog();
this.Close();
}
else MessageBox.Show("Error");
}
private void counter_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'g463_stukalo_denisenkoDataSet.DataTable1' table. You can move, or remove it, as needed.
this.dataTable1TableAdapter.Fill(this.g463_stukalo_denisenkoDataSet.DataTable1);
// TODO: This line of code loads data into the 'g463_stukalo_denisenkoDataSet.User' table. You can move, or remove it, as needed.
this.userTableAdapter.Fill(this.g463_stukalo_denisenkoDataSet.User);
}
}
}
|
SQL
|
UTF-8
| 5,197 | 3.765625 | 4 |
[] |
no_license
|
-- MySQL Script generated by MySQL Workbench
-- Thu Apr 27 11:15:23 2017
-- Model: New Model Version: 1.0
-- MySQL Workbench Forward Engineering
/*
* Sql script to create and populate tables
* You need to run this script with an authorized user.
* to run this file @ mysql client :mysql> source path-to\E-Commerce.sql
* data files for load on desktop
*/
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
SHOW DATABASES;
-- -----------------------------------------------------
-- Schema cs157b
-- -----------------------------------------------------
DROP SCHEMA IF EXISTS `cs157b` ;
SHOW DATABASES;
-- -----------------------------------------------------
-- Schema cs157b
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `cs157b` DEFAULT CHARACTER SET utf8 ;
SHOW WARNINGS;
USE `cs157b` ;
-- -----------------------------------------------------
-- Table `cs157b`.`User`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `cs157b`.`User` ;
SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `cs157b`.`User` (
`Name` VARCHAR(45) NOT NULL,
`Address` VARCHAR(45) NULL,
`Password` VARCHAR(45) NOT NULL,
`UserID` INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`UserID`))
ENGINE = InnoDB;
SHOW WARNINGS;
-- -----------------------------------------------------
-- Table `cs157b`.`Suppliers`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `cs157b`.`Suppliers` ;
SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `cs157b`.`Suppliers` (
`Product` VARCHAR(45) NULL,
`Price` REAL NULL,
`Location` VARCHAR(45),
`Quantity` REAL NULL,
`SupplierID` INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`SupplierID`))
ENGINE = InnoDB;
SHOW WARNINGS;
-- -----------------------------------------------------
-- Table `cs157b`.`Order`
-- -----------------------------------------------------
DROP TABLE IF EXISTS `cs157b`.`Orders` ;
SHOW WARNINGS;
CREATE TABLE IF NOT EXISTS `cs157b`.`Orders` (
`UserID` INT NULL,
`Product` VARCHAR(45) NULL,
`Quantity` REAL NULL,
`UnitPrice` REAL NULL,
`TotalPrice` REAL NULL,
`SupplierID` INT NULL,
`OrderID` INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`OrderID`),
INDEX `CustomerID_idx` (`UserID` ASC),
INDEX `SupplierID_idx` (`SupplierID` ASC),
CONSTRAINT `UserID`
FOREIGN KEY (`UserID`)
REFERENCES `cs157b`.`User` (`UserID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `SupplierID`
FOREIGN KEY (`SupplierID`)
REFERENCES `cs157b`.`Suppliers` (`SupplierID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SHOW WARNINGS;
show tables;
LOAD DATA LOCAL INFILE 'C:\\Users\\BikramSingh\\Desktop\\users_data.txt' INTO TABLE user FIELDS TERMINATED BY ',' LINES TERMINATED BY '\r\n' ;
SELECT * FROM User;
LOAD DATA LOCAL INFILE 'C:\\Users\\BikramSingh\\Desktop\\suppliers_data.txt' INTO TABLE Suppliers FIELDS TERMINATED BY ',' LINES TERMINATED BY '\r\n' ;
SELECT * FROM Suppliers;
LOAD DATA LOCAL INFILE 'C:\\Users\\BikramSingh\\Desktop\\orders_data.txt' INTO TABLE Orders FIELDS TERMINATED BY ',' LINES TERMINATED BY '\r\n' ;
SELECT * FROM ORDERS;
/* find all the suppliers in San Jose */
select 'Find all the suppliers in San Jose' AS '';
SELECT SupplierID FROM Suppliers WHERE Location Like 'San Jose%';
/* How many registered users the website has? */
select 'Find all registered users the website has' AS '';
SELECT COUNT(userID) FROM user;
/* How many orders has quanity more than 2? */
select 'Find all the orders with quanity more than 2' AS '';
SELECT COUNT(orderId) FROM orders where Quantity > 2;
/* Find all the orders shipped from San Jose */
select 'Find all the orders shipped from San Jose ' AS '';
SELECT * FROM orders, suppliers where orders.supplierID = suppliers.supplierID AND Suppliers.Location LIKE 'san jose%';
/* Find all the buyers and their suppliers */
select 'Find all the buyers and their suppliers' AS '';
select u.name, a.supplierID from (select distinct userID, supplierID from orders) a, user u Where a.userID=u.userid;
/* Which users had orders that cost more than 200 dollars? */
select 'Find all the buyers and their suppliers' AS '';
select u.name from (select distinct userID from orders where totalprice > 200) a, user u Where a.userID=u.userid;
/* What is the total dollar count for all the orders? */
select 'What is the total dollar count for all the orders' AS '';
select sum(totalprice) from orders;
/* What is the smallest order? (Min*/
select 'What is the smallest order?' AS '';
select * from orders where totalprice=(select min(totalprice) from orders);
/* What is the smallest order? (Min*/
select 'What is the smallest order?' AS '';
select * from orders where totalprice=(select min(totalprice) from orders);
/* What is the average price of the orders? */
select 'What is the average price of the orders' AS '';
select AVG(totalprice) from orders;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
|
C++
|
UTF-8
| 3,432 | 3.078125 | 3 |
[] |
no_license
|
#include <algorithm>
#include <cassert>
#include <iomanip>
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
Solution(const vector<int>& parent, const vector<bool>& has_worm)
: has_worm_(has_worm) {
n_ = parent.size();
assert(n_ == (int)has_worm.size());
children_.resize(n_);
root_ = -1;
for (int x = 0; x < n_; x++) {
if (parent[x] == -1) {
root_ = x;
} else {
children_[parent[x]].push_back(x);
}
}
num_leaves_.resize(n_, 0);
}
double Solve() {
ComputeNumLeaves(root_);
vector<double> m0(n_);
vector<double> m1(n_);
return ComputeExpectedTime(root_, m0, m1);
}
private:
int ComputeNumLeaves(const int x) {
int num = 0;
if (children_[x].empty()) {
num = 1;
} else {
num = 0;
for (int j = 0, e = children_[x].size(); j < e; j++) {
const int y = children_[x][j];
num += ComputeNumLeaves(y);
}
}
num_leaves_[x] = num;
return num;
}
class Comparator {
public:
Comparator(const vector<int>& num_leaves, const vector<double>& m0)
: num_leaves_(num_leaves), m0_(m0) {}
bool operator()(const int y0, const int y1) const {
return (m0_[y0] + 2) * num_leaves_[y1] < (m0_[y1] + 2) * num_leaves_[y0];
}
private:
const vector<int>& num_leaves_;
const vector<double>& m0_;
};
double ComputeExpectedTime(const int x, vector<double>& m0,
vector<double>& m1) {
if (children_[x].empty()) {
m0[x] = 0.0;
return m1[x] = 0.0;
}
for (int j = 0, e = children_[x].size(); j < e; j++) {
const int y = children_[x][j];
ComputeExpectedTime(y, m0, m1);
}
m0[x] = 0.0;
if (!has_worm_[x]) {
for (int j = 0, e = children_[x].size(); j < e; j++) {
const int y = children_[x][j];
m0[x] += 1 + m0[y] + 1;
}
}
vector<int> order = children_[x];
sort(order.begin(), order.end(), Comparator(num_leaves_, m0));
double wasted_time = 0.0;
double expected_time = 0.0;
for (int j = 0, e = order.size(); j < e; j++) {
const int y = order[j];
expected_time +=
(wasted_time + 1 + m1[y]) * num_leaves_[y] / num_leaves_[x];
wasted_time += 1 + m0[y] + 1;
}
return m1[x] = expected_time;
}
double Solve(const vector<int>& parent, const vector<bool>& has_worm) {
const int n = parent.size();
assert(n == (int)has_worm.size());
vector<vector<int> > children(n);
int root = -1;
for (int x = 0; x < n; x++) {
if (parent[x] == -1) {
root = x;
} else {
children[parent[x]].push_back(x);
}
}
vector<int> num_leaves(n);
ComputeNumLeaves(root);
vector<double> m0(n);
vector<double> m1(n);
return ComputeExpectedTime(root, m0, m1);
}
int n_;
int root_;
vector<vector<int> > children_;
vector<int> num_leaves_;
const vector<bool>& has_worm_;
};
int main() {
int n;
cin >> n;
cout << fixed << setprecision(4);
while (n > 0) {
vector<int> parent(n);
vector<bool> has_worm(n);
for (int x = 0; x < n; x++) {
cin >> parent[x];
if (parent[x] > 0) {
parent[x]--;
}
char c;
cin >> c;
has_worm[x] = (c == 'Y');
}
Solution s(parent, has_worm);
cout << s.Solve() << endl;
cin >> n;
}
return 0;
}
|
C++
|
UTF-8
| 3,558 | 2.765625 | 3 |
[] |
no_license
|
/*
MessageQueueRequestChannel.cpp
Created by Joshua Higginbotham on 6/16/16.
*/
/*--------------------------------------------------------------------------*/
/* INCLUDES */
/*--------------------------------------------------------------------------*/
#include "MessageQueueRequestChannel.h"
/*--------------------------------------------------------------------------*/
/* CONSTANTS */
/*--------------------------------------------------------------------------*/
const bool VERBOSE = false;
/*--------------------------------------------------------------------------*/
/* PRIVATE METHODS FOR CLASS MessageQueueRequestChannel */
/*--------------------------------------------------------------------------*/
/* --- none --- */
/*--------------------------------------------------------------------------*/
/* CONSTRUCTOR/DESTRUCTOR FOR CLASS MessageQueueRequestChannel */
/*--------------------------------------------------------------------------*/
MessageQueueRequestChannel::MessageQueueRequestChannel(const std::string _name, const Side _side) :
my_name(_name),
my_side(_side),
side_name((my_side == RequestChannel::SERVER_SIDE) ? "SERVER" : "CLIENT"),
write_buf((my_side == RequestChannel::SERVER_SIDE) ? (my_name + "a") : (my_name + "b"),
MQ_NUM_MESSAGES, MQ_MAX_REQUEST),
read_buf((my_side == RequestChannel::SERVER_SIDE) ? (my_name + "b") : (my_name + "a"),
MQ_NUM_MESSAGES, MQ_MAX_REQUEST)
{
}
MessageQueueRequestChannel::~MessageQueueRequestChannel() {
}
/*--------------------------------------------------------------------------*/
/* READ/WRITE FROM/TO REQUEST CHANNELS */
/*--------------------------------------------------------------------------*/
std::string MessageQueueRequestChannel::send_request(std::string _request) {
cwrite(_request);
std::string read_result = cread();
return read_result;
}
std::string MessageQueueRequestChannel::cread() {
if(VERBOSE) {
threadsafe_console_output.println("MESSAGE_QUEUE_REQUEST_CHANNEL:" + my_name + ":" + side_name + ": reading...");
}
std::string read_result = read_buf.retrieve_front();
if(read_result.substr(0, 5) == "ERROR") {
threadsafe_console_output.perror("MESSAGE_QUEUE_REQUEST_CHANNEL:" + my_name + ": " + side_name + ":cread: " + read_result);
return read_result;
}
if(VERBOSE) {
threadsafe_console_output.println("MESSAGE_QUEUE_REQUEST_CHANNEL:" + my_name + ":" + side_name + ": reads [" + read_result + "]");
}
return read_result;
}
int MessageQueueRequestChannel::cwrite(std::string _msg) {
if (_msg.length() + 1 > MQ_MAX_REQUEST) {
threadsafe_console_output.println("MESSAGE_QUEUE_REQUEST_CHANNEL:" + my_name + ":" + side_name + ":cwrite: message too long for channel");
return -1;
}
if(VERBOSE) {
threadsafe_console_output.println("MESSAGE_QUEUE_REQUEST_CHANNEL:" + my_name + ":" + side_name + ": writing [" + _msg + "]");
}
std::string write_result = write_buf.push_back(_msg);
if(write_result.substr(0, 5) == "ERROR") {
threadsafe_console_output.perror("MESSAGE_QUEUE_REQUEST_CHANNEL:" + my_name + ": " + side_name + ":cwrite: " + write_result);
return -1;
}
if(VERBOSE) {
threadsafe_console_output.println("MESSAGE_QUEUE_REQUEST_CHANNEL:" + my_name + ":" + side_name + ": done writing.");
}
return _msg.length() + 1;
}
/*--------------------------------------------------------------------------*/
/* ACCESS THE NAME OF REQUEST CHANNEL */
/*--------------------------------------------------------------------------*/
std::string MessageQueueRequestChannel::name() {
return my_name;
}
|
Java
|
UTF-8
| 2,512 | 2.65625 | 3 |
[] |
no_license
|
package com.secondhand.common.basemethod;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;
import org.springframework.util.Assert;
/**
* Api่ฟๅ็ปๆ
*
* @author Erica
* @since 2020/2/3
*/
@Data
@Getter
@Setter
@Accessors(chain = true)
public class ApiResult<T> {
private static final long serialVersionUID = -5963397321998888554L;
private int code;
// // ้่ฏฏไปฃ็
// private String errorCode;
// ้่ฏฏๆถๆฏ
private String message;
// ่ฟๅ็ๅฏน่ฑก
private T data;
private String path;
public static int FAIL_CODE = 1;
public static int SUCCESS_CODE = 0;
public ApiResult(int code, String message, T data) {
this.code = code;
// 2ไฝๅ่ฟๅถๆฐ
// this.errorCode = String.format("%02d", code);
this.message = message;
this.data = data;
}
public ApiResult(int code, String message) {
this.code = code;
// this.errorCode = String.format("%02d", code);
this.message = message;
}
public static <T> ApiResult fail(int code, String message) {
Assert.isTrue(code >= FAIL_CODE, "้่ฏฏ็ปๆ่ฏทไธ่ฆ่ฎพ็ฝฎcodeๅผไธบ0");
return new ApiResult(code, message);
}
/**
* ๆ้ ไธไธชๆ ๅ้่ฏฏ
*
* @param message
* @return
* @throws
*/
@SuppressWarnings("rawtypes")
public static <T> ApiResult<T> fail(String message) {
return new ApiResult<>(FAIL_CODE, message);
}
/**
* ๆ้ ไธไธชๆๅ็ปๆ
*
* @param data
* @return
*/
@SuppressWarnings("rawtypes")
public static <T> ApiResult<T> success(T data) {
ApiResult<T> re = new ApiResult<>(SUCCESS_CODE, "ๆๅ");
re.data = data;
return re;
}
public static <T> ApiResult<T> success(String msg) {
return new ApiResult<>(SUCCESS_CODE, msg);
}
public static <T> ApiResult<T> success(boolean flag){
return flag ? success("ๆไฝๆๅ") : fail("ๆไฝๅคฑ่ดฅ");
}
/**
* ๆ้ ไธไธชๆๅ็ปๆ
*
* @param data
* @return
*/
@SuppressWarnings("rawtypes")
public static <T> ApiResult success(String msg, T data) {
ApiResult<T> re = new ApiResult<>(SUCCESS_CODE, msg);
re.data = data;
return re;
}
public static <T> ApiResult<T> success(Integer code,String msg,T data) {
return new ApiResult<>(code,msg,data);
}
}
|
Java
|
UTF-8
| 975 | 2.21875 | 2 |
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package VRTSignature;
import java.io.File;
/**
*
* @author heckarim
*/
public class DoIt {
public static void main(String[] args){
new DoIt().action();
}
private void action() {
String basefolder = System.getProperty("user.dir") + File.separator + "rules.2.9" + File.separator;
String outdir = System.getProperty("user.dir") + File.separator + "rule.test" + File.separator;
RuleDatabase rd = new RuleDatabase(basefolder);
rd.setOutputFolder(outdir);
// Backup database
rd.buildDatabase();
rd.backupDatabase("allsig.xls");
// Restore database
//rd.restoreDatabase(outdir, "allsig.xls");
//rd.backupDatabase(outdir, "test2");
//rd.print4Test();
//Statistic0 st = new Statistic0(rd);
//st.DoScript();
}
}
|
Java
|
UTF-8
| 482 | 1.601563 | 2 |
[] |
no_license
|
/*
* @(#)Prajitura.java
*
* Generated by <a href="http://lci.cs.ubbcluj.ro/ocle/>OCLE 2.0</a>
* using <a href="http://jakarta.apache.org/velocity/">
* Velocity Template Engine 1.3rc1</a>
*/
/**
*
* @author unascribed
*/
public class Prajitura {
public int getPret() {
int nPret = Prajitura.this.pret;
return nPret;
}
public Prajitura() {
}
private String nume;
private int pret;
}
|
Java
|
UTF-8
| 803 | 2.359375 | 2 |
[] |
no_license
|
package com.chrismin13.vanillaadditions.items.prismarine;
import org.bukkit.Color;
import org.bukkit.Material;
import com.chrismin13.additionsapi.enums.ArmorType;
import com.chrismin13.additionsapi.utils.MaterialUtils;
import com.chrismin13.vanillaadditions.items.AverageLeatherArmor;
public class PrismarineArmor extends AverageLeatherArmor {
public PrismarineArmor(ArmorType armorType) {
super(armorType, armorType.getIronMaterial().getMaxDurability(),
"vanilla_additions:prismarine_" + armorType.toString().toLowerCase(),
"Prismarine " + armorType.toIngameString(), Color.fromRGB(116, 183, 179), Material.PRISMARINE_SHARD,
MaterialUtils.getBaseArmor(armorType.getDiamondMaterial()),
MaterialUtils.getBaseArmorToughness(armorType.getDiamondMaterial()));
}
}
|
Java
|
UTF-8
| 3,757 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
package home.app.services.service.repositories;
import home.app.services.service.model.AccommodationType;
import home.app.services.service.model.Service;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
@ExtendWith(SpringExtension.class)
@ActiveProfiles("test")
@DirtiesContext
public class ServiceRepositoryIntegrationTests {
@Autowired
private ServiceRepository serviceRepository;
@Test
public void search_noArguments_returnAll() {
List<Service> services = serviceRepository.search("", "", null, null, null);
assertEquals(4, services.size());
}
@Test
public void search_namePassed_returnServicesContainingName() {
String name = "ter";
List<Service> services = serviceRepository.search(name, "", null, null, null);
assertEquals(2, services.size());
services.forEach(s -> assertTrue(s.getName().toLowerCase().contains(name.toLowerCase())));
}
@Test
public void search_minPricePassed_returnServicesWithAtLeastOneAccommodationMoreExpensiveThanPricePassed() {
double minPrice = 1300.0;
List<Service> services = serviceRepository.search("", "", minPrice, null, null);
assertEquals(3, services.size());
services.forEach(s -> assertTrue(s.getAccommodations().stream().anyMatch(a -> a.getPrice() >= minPrice)));
}
@Test
public void search_priceRangePassed_returnServicesWithAtLeastOneAccommodationInPriceRange() {
double minPrice = 1300.0;
double maxPrice = 1600.0;
List<Service> services = serviceRepository.search("", "", minPrice, maxPrice, null);
assertEquals(2, services.size());
services.forEach(s -> assertTrue(s.getAccommodations().stream().anyMatch(a -> a.getPrice() >= minPrice && a.getPrice() <= maxPrice)));
}
@Test
public void search_accommodationTypePassed_returnServicesWithAtLeastOneAccommodationOfPassedType() {
AccommodationType accommodationType = AccommodationType.REPAIRS;
List<Service> services = serviceRepository.search("", "", null, null, accommodationType);
assertEquals(1, services.size());
services.forEach(s -> assertTrue(s.getAccommodations().stream().anyMatch(a -> a.getType().equals(accommodationType))));
}
@Test
public void search_allArgumentsPassed_returnServicesThatMeetAllCriteria() {
String name = "ter";
String city = "Singapore";
double minPrice = 300.0;
double maxPrice = 2000.0;
AccommodationType accommodationType = AccommodationType.CATERING;
List<Service> services = serviceRepository.search(name, city, minPrice, maxPrice, accommodationType);
assertEquals(1, services.size());
services.forEach(s -> {
assertTrue(s.getName().toLowerCase().contains(name.toLowerCase()));
assertTrue(s.getContact().getAddress().getCity().toLowerCase().contains(city.toLowerCase()));
assertTrue(s.getAccommodations().stream().anyMatch(a -> a.getPrice() >= minPrice && a.getPrice() <= maxPrice));
assertTrue(s.getAccommodations().stream().anyMatch(a -> a.getType().equals(accommodationType)));
});
}
}
|
Python
|
UTF-8
| 7,245 | 2.734375 | 3 |
[
"BSD-3-Clause"
] |
permissive
|
import pytest
from pandarallel import pandarallel
import pandas as pd
import numpy as np
import math
@pytest.fixture(params=(False, True))
def progress_bar(request):
return request.param
@pytest.fixture(params=(None, False))
def use_memory_fs(request):
return request.param
@pytest.fixture(params=("named", "anonymous"))
def func_dataframe_apply_axis_0(request):
def func(x):
return max(x) - min(x)
return dict(named=func, anonymous=lambda x: max(x) - min(x))[request.param]
@pytest.fixture(params=("named", "anonymous"))
def func_dataframe_apply_axis_1(request):
def func(x):
return math.sin(x.a ** 2) + math.sin(x.b ** 2)
return dict(
named=func, anonymous=lambda x: math.sin(x.a ** 2) + math.sin(x.b ** 2)
)[request.param]
@pytest.fixture(params=("named", "anonymous"))
def func_dataframe_applymap(request):
def func(x):
return math.sin(x ** 2) - math.cos(x ** 2)
return dict(named=func, anonymous=lambda x: math.sin(x ** 2) - math.cos(x ** 2))[
request.param
]
@pytest.fixture(params=("named", "anonymous"))
def func_series_map(request):
def func(x):
return math.log10(math.sqrt(math.exp(x ** 2)))
return dict(
named=func, anonymous=lambda x: math.log10(math.sqrt(math.exp(x ** 2)))
)[request.param]
@pytest.fixture(params=("named", "anonymous"))
def func_series_apply(request):
def func(x, power, bias=0):
return math.log10(math.sqrt(math.exp(x ** power))) + bias
return dict(
named=func,
anonymous=lambda x, power, bias=0: math.log10(math.sqrt(math.exp(x ** power)))
+ bias,
)[request.param]
@pytest.fixture(params=("named", "anonymous"))
def func_series_rolling_apply(request):
def func(x):
return x.iloc[0] + x.iloc[1] ** 2 + x.iloc[2] ** 3 + x.iloc[3] ** 4
return dict(
named=func,
anonymous=lambda x: x.iloc[0]
+ x.iloc[1] ** 2
+ x.iloc[2] ** 3
+ x.iloc[3] ** 4,
)[request.param]
@pytest.fixture()
def func_dataframe_groupby_apply():
def func(df):
dum = 0
for item in df.b:
dum += math.log10(math.sqrt(math.exp(item ** 2)))
return dum / len(df.b)
return func
@pytest.fixture(params=("named", "anonymous"))
def func_dataframe_groupby_rolling_apply(request):
def func(x):
return x.iloc[0] + x.iloc[1] ** 2 + x.iloc[2] ** 3 + x.iloc[3] ** 4
return dict(
named=func,
anonymous=lambda x: x.iloc[0]
+ x.iloc[1] ** 2
+ x.iloc[2] ** 3
+ x.iloc[3] ** 4,
)[request.param]
@pytest.fixture()
def pandarallel_init(progress_bar, use_memory_fs):
pandarallel.initialize(progress_bar=progress_bar, use_memory_fs=use_memory_fs, nb_workers=2)
def test_dataframe_apply_axis_0(pandarallel_init, func_dataframe_apply_axis_0):
df_size = int(1e1)
df = pd.DataFrame(
dict(
a=np.random.randint(1, 8, df_size),
b=np.random.rand(df_size),
c=np.random.randint(1, 8, df_size),
d=np.random.rand(df_size),
e=np.random.randint(1, 8, df_size),
f=np.random.rand(df_size),
g=np.random.randint(1, 8, df_size),
h=np.random.rand(df_size),
)
)
res = df.apply(func_dataframe_apply_axis_0)
res_parallel = df.parallel_apply(func_dataframe_apply_axis_0)
assert res.equals(res_parallel)
def test_dataframe_apply_axis_1(pandarallel_init, func_dataframe_apply_axis_1):
df_size = int(1e1)
df = pd.DataFrame(
dict(a=np.random.randint(1, 8, df_size), b=np.random.rand(df_size))
)
res = df.apply(func_dataframe_apply_axis_1, axis=1)
res_parallel = df.parallel_apply(func_dataframe_apply_axis_1, axis=1)
assert res.equals(res_parallel)
def test_dataframe_applymap(pandarallel_init, func_dataframe_applymap):
df_size = int(1e1)
df = pd.DataFrame(
dict(a=np.random.randint(1, 8, df_size), b=np.random.rand(df_size))
)
res = df.applymap(func_dataframe_applymap)
res_parallel = df.parallel_applymap(func_dataframe_applymap)
assert res.equals(res_parallel)
def test_series_map(pandarallel_init, func_series_map):
df_size = int(1e1)
df = pd.DataFrame(dict(a=np.random.rand(df_size) + 1))
res = df.a.map(func_series_map)
res_parallel = df.a.parallel_map(func_series_map)
assert res.equals(res_parallel)
def test_series_apply(pandarallel_init, func_series_apply):
df_size = int(1e1)
df = pd.DataFrame(dict(a=np.random.rand(df_size) + 1))
res = df.a.apply(func_series_apply, args=(2,), bias=3)
res_parallel = df.a.parallel_apply(func_series_apply, args=(2,), bias=3)
assert res.equals(res_parallel)
def test_series_rolling_apply(pandarallel_init, func_series_rolling_apply):
df_size = int(1e2)
df = pd.DataFrame(dict(a=np.random.randint(1, 8, df_size), b=list(range(df_size))))
res = df.b.rolling(4).apply(func_series_rolling_apply, raw=False)
res_parallel = df.b.rolling(4).parallel_apply(func_series_rolling_apply, raw=False)
assert res.equals(res_parallel)
def test_dataframe_groupby_apply(pandarallel_init, func_dataframe_groupby_apply):
df_size = int(1e1)
df = pd.DataFrame(
dict(
a=np.random.randint(1, 8, df_size),
b=np.random.rand(df_size),
c=np.random.rand(df_size),
)
)
res = df.groupby("a").apply(func_dataframe_groupby_apply)
res_parallel = df.groupby("a").parallel_apply(func_dataframe_groupby_apply)
res.equals(res_parallel)
res = df.groupby(["a"]).apply(func_dataframe_groupby_apply)
res_parallel = df.groupby(["a"]).parallel_apply(func_dataframe_groupby_apply)
res.equals(res_parallel)
res = df.groupby(["a", "b"]).apply(func_dataframe_groupby_apply)
res_parallel = df.groupby(["a", "b"]).parallel_apply(func_dataframe_groupby_apply)
res.equals(res_parallel)
def test_dataframe_groupby_rolling_apply(
pandarallel_init, func_dataframe_groupby_rolling_apply
):
df_size = int(1e2)
df = pd.DataFrame(
dict(a=np.random.randint(1, 10, df_size), b=np.random.rand(df_size))
)
res = (
df.groupby("a")
.b.rolling(4)
.apply(func_dataframe_groupby_rolling_apply, raw=False)
)
res_parallel = (
df.groupby("a")
.b.rolling(4)
.parallel_apply(func_dataframe_groupby_rolling_apply, raw=False)
)
res.equals(res_parallel)
def test_datetime_rolling(pandarallel_init):
from datetime import datetime
test_df = pd.DataFrame([{"datetime": datetime.now(), "A": 1, "B": 7},
{"datetime": datetime.now(), "A": 2, "B": 4}])
grouped_test_df = test_df.set_index('datetime').groupby('A')
interval = '1D'
res = (grouped_test_df.rolling(interval)
.B
.parallel_apply(np.sum))
res_parallel = (grouped_test_df.rolling(interval)
.B
.parallel_apply(np.sum))
res.equals(res_parallel)
:q
|
C
|
UTF-8
| 3,082 | 3.59375 | 4 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
/* Helper math functions */
int circleError(int x, int y, int r) {
int error = (r*r) - (x*x) - (y*y);
if (error > 0) {
return error;
} else {
return -error;
}
}
/* End helper functions */
void writeImage(char* filename, char*** image, int width, int height) {
FILE* fp = fopen(filename, "wb");
fprintf(fp, "P6\n%d\n%d\n255\n", width, height);
int i, j;
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
fwrite(image[i][j], sizeof(char), 3, fp);
}
}
fclose(fp);
}
char*** blankImage(int width, int height) {
int i, j, k;
char*** image = (char***) malloc(height * sizeof(char**));
for (i = 0; i < height; i++) {
image[i] = (char**) malloc(width * sizeof(char*));
for (j = 0; j < width; j++) {
image[i][j] = (char*) malloc(3 * sizeof(char));
for (k = 0; k < 3; k++) {
image[i][j][k] = 255;
}
}
}
return image;
}
void freeImage(char*** image, int width, int height) {
int i, j;
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
free(image[i][j]);
}
free(image[i]);
}
free(image);
}
void setColor(char*** image, int width, int height, int coordX, int coordY, unsigned char red, unsigned char green, unsigned char blue) {
if ((coordX < width) && (coordY < height)) {
image[coordY][coordX][0] = red;
image[coordY][coordX][1] = green;
image[coordY][coordX][2] = blue;
}
}
void drawSquare(char*** image, int width, int height, int coordX, int coordY, int radius, unsigned char red, unsigned char green, unsigned char blue) {
if ((coordX >= radius) && (coordX <= width - radius) && (coordY >= radius) && (coordY <= height - radius)) {
int i;
for (i = -radius; i <= radius; i++) {
setColor(image, width, height, coordX + i, coordY + radius, red, green, blue);
setColor(image, width, height, coordX + i, coordY - radius, red, green, blue);
setColor(image, width, height, coordX + radius, coordY + i, red, green, blue);
setColor(image, width, height, coordX - radius, coordY + i, red, green, blue);
}
}
}
void drawCircle(char*** image, int width, int height, int coordX, int coordY, int radius, unsigned char red, unsigned char green, unsigned char blue) {
if ((coordX >= radius) && (coordX <= width - radius) && (coordY >= radius) && (coordY <= height - radius)) {
int x = radius;
int y = 0;
while (x >= y) {
setColor(image, width, height, coordX + x, coordY + y, red, green, blue);
setColor(image, width, height, coordX + y, coordY + x, red, green, blue);
setColor(image, width, height, coordX - x, coordY + y, red, green, blue);
setColor(image, width, height, coordX - y, coordY + x, red, green, blue);
setColor(image, width, height, coordX + x, coordY - y, red, green, blue);
setColor(image, width, height, coordX + y, coordY - x, red, green, blue);
setColor(image, width, height, coordX - x, coordY - y, red, green, blue);
setColor(image, width, height, coordX - y, coordY - x, red, green, blue);
y += 1;
if (circleError(x - 1, y, radius) < circleError(x, y, radius)) {
x -= 1;
}
}
}
}
|
C++
|
UTF-8
| 1,409 | 3.0625 | 3 |
[] |
no_license
|
#include <Wire.h>
#include "Adafruit_PWMServoDriver.h"
// called this way, it uses the default address 0x40
Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver(0x40);
// our servo # counter
uint8_t servonum = 0;
void setup() {
Serial.begin(9600);
Serial.println("16 channel Servo test!");
pwm.begin();
pwm.setPWMFreq(50); // Analog servos run at ~60 Hz updates
}
// you can use this function if you'd like to set the pulse length in seconds
// e.g. setServoPulse(0, 0.001) is a ~1 millisecond pulse width. its not precise!
void setServoPulse(uint8_t n, double pulse) {
double pulselength;
pulselength = 1000000; // 1,000,000 us per second
pulselength /= 50; // 50 Hz
Serial.print(pulselength); Serial.println(" us per period");
pulselength /= 4096; // 12 bits of resolution
Serial.print(pulselength); Serial.println(" us per bit");
pulse *= 1000;
pulse /= pulselength;
Serial.println(pulse);
pwm.setPWM(n, 0, pulse);
}
void writeServo(uint8_t n,uint8_t angle){
double pulse;
pulse=0.5+angle/90.0;
setServoPulse(n,pulse);
}
String inString = "";
void loop() {
if (Serial.available() > 0) {
if (Serial.peek() != '\n') {
inString += (char)Serial.read();
} else {
Serial.read();
Serial.print("Instruction received: ");
Serial.println(inString);
writeServo(servonum,inString.toInt());
inString = "";
}
}
}
|
Java
|
UTF-8
| 242 | 1.921875 | 2 |
[] |
no_license
|
/*
* Copyright 2007-2009 Eric Holloway. All rights reserved.
*/
package actuators;
import common.*;
public abstract class Actuator extends Machine {
public Actuator() {super();}
public Actuator(Thing t) {
super(t);
}
}
|
Python
|
UTF-8
| 1,055 | 3.734375 | 4 |
[] |
no_license
|
"""
Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.
Example 1:
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6
Explanation: The above elevation map (black section) is represented by array [0,1,0,2,1,0,1,3,2,1,2,1]. In this case, 6 units of rain water (blue section) are being trapped.
Input: height = [4,2,0,3,2,5]
Output: 9
Constraints:
n == height.length
0 <= n <= 3 * 104
0 <= height[i] <= 105
"""
class Solution:
def trap(self, height: List[int]) -> int:
left = 0
right = len(height) - 1
left_max = 0
right_max = 0
ans = 0
while left < right:
if height[left] < height[right]:
left_max = max(left_max, height[left])
ans += left_max - height[left]
left += 1
else:
right_max = max(right_max, height[right])
ans += right_max - height[right]
right -= 1
return ans
|
Java
|
UTF-8
| 148 | 1.6875 | 2 |
[
"MIT"
] |
permissive
|
package com.caimi.service.beans;
public interface Lifecycle {
public void init(BeansContainer beansContainer);
public void destroy();
}
|
C#
|
UTF-8
| 3,117 | 2.578125 | 3 |
[] |
no_license
|
๏ปฟusing System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace UsefulBits.Web.Mvc.Areas
{
/// <summary>
/// Allow service location and dependency resolution per ASP MVC Area.
/// </summary>
public sealed class AreaDependencyResolver : IDependencyResolver
{
private ConcurrentDictionary<string, IDependencyResolver> _areaDependencyResolvers = new ConcurrentDictionary<string, IDependencyResolver>();
private ConcurrentDictionary<string, IDependencyResolver> _namespaceCache = new ConcurrentDictionary<string, IDependencyResolver>();
private IDependencyResolver _baseDependencyResolver;
private AreaDependencyResolver()
{ }
private static AreaDependencyResolver _instance = new AreaDependencyResolver();
internal static AreaDependencyResolver Instance { get { return _instance; } }
/// <summary>
/// Provides a registration point for dependency resolvers, using the specified dependency resolver interface as resolver for objects outside a defined area.
/// </summary>
/// <param name="rootDependencyResolver">The root dependency resolver.</param>
public static void SetResolver(IDependencyResolver rootDependencyResolver = null)
{
Instance._baseDependencyResolver = rootDependencyResolver;
DependencyResolver.SetResolver(Instance);
}
internal void Register(string areaNamespace, IDependencyResolver dependencyResolver)
{
if (!_areaDependencyResolvers.TryAdd(areaNamespace, dependencyResolver))
throw new ArgumentException("A DependencyResolver is already registered for namespace " + areaNamespace, "areaNamespace");
}
/// <summary>
/// Resolves singly registered services that support arbitrary object creation.
/// </summary>
/// <param name="serviceType">The type of the requested service or object.</param>
/// <returns>
/// The requested service or object.
/// </returns>
public object GetService(Type serviceType)
{
var resolver = GetInnerDependencyResolver(serviceType);
if (resolver != null)
return resolver.GetService(serviceType);
else
return null;
}
/// <summary>
/// Resolves multiply registered services.
/// </summary>
/// <param name="serviceType">The type of the requested services.</param>
/// <returns>
/// The requested services.
/// </returns>
public IEnumerable<object> GetServices(Type serviceType)
{
var resolver = GetInnerDependencyResolver(serviceType);
if (resolver != null)
return resolver.GetServices(serviceType);
else
return Enumerable.Empty<object>();
}
private IDependencyResolver GetInnerDependencyResolver(Type serviceType)
{
return _namespaceCache.GetOrAdd(serviceType.Namespace,
serviceNameSpace =>
_areaDependencyResolvers.FirstOrDefault(kv => AreaNamespace.IsNamespaceMatch(kv.Key, serviceType.Namespace)).Value ?? _baseDependencyResolver
);
}
}
}
|
Java
|
UTF-8
| 1,205 | 2.96875 | 3 |
[] |
no_license
|
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
// System.setIn(new FileInputStream("src/test.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String l ;
while((l=br.readLine())!=null) {
int tc = Integer.parseInt(l);
if(tc ==0)break;
char[][] d = new char [tc][tc];
int cols [] = new int[tc];
int rows[] = new int[tc];
int ur =0;
int uc=0;
int cr=0;
int cc=0;
for(int i = 0;i<tc;i++) {
String [] lines = br.readLine().split(" ");
for(int j = 0;j<tc;j++) {
char aux =lines[j].charAt(0);
d[i][j]=aux;
if(aux=='1') {
rows[i]++;
cols[j]++;
}
}
}
for(int i = 0;i<tc;i++) {
if(rows[i]%2!=0) {
cr=i;
ur++;
}
}
for(int i = 0;i<tc;i++) {
if(cols[i]%2!=0) {
cc=i;
uc++;
}
}
if (uc==0 && ur ==0) {
System.out.println("OK");
}else if (uc==1 && ur==1) {
System.out.println("Change bit ("+(cr+1)+","+(cc+1)+")");
}else {
System.out.println("Corrupt");
}
}
}
}
|
Java
|
UTF-8
| 2,816 | 1.867188 | 2 |
[] |
no_license
|
package com.junyou.bus.jinfeng.service;
import java.sql.Timestamp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.junyou.bus.jinfeng.dao.FengIpDao;
import com.junyou.bus.jinfeng.entity.FengIp;
import com.junyou.bus.jinfeng.utils.FengHaoUtil;
import com.junyou.bus.role.export.RoleWrapper;
import com.junyou.bus.role.service.UserRoleService;
import com.junyou.constants.GameConstants;
import com.junyou.err.HttpErrorCode;
import com.junyou.io.export.SessionManagerExportService;
import com.junyou.public_.share.export.PublicRoleStateExportService;
import com.junyou.utils.datetime.GameSystemTime;
@Component
public class FengIpService{
@Autowired
private UserRoleService roleExportService;
@Autowired
private FengIpDao fengIpDao;
@Autowired
private PublicRoleStateExportService publicRoleStateExportService;
@Autowired
private SessionManagerExportService sessionManagerExportService;
public boolean isFengIp(String ip){
FengIp fengIp = fengIpDao.getFengIpByIp(ip);
if(fengIp == null){
return false;
}
if(fengIp.getExpireTime() > 0 && fengIp.getExpireTime() < GameSystemTime.getSystemMillTime()){
fengIpDao.delete(ip);
return false;
}
return true;
}
public String fengIp(Long userRoleId,int keepTime,String reasons) {
if( userRoleId == null ){
return HttpErrorCode.USER_NOT_EXIST;
}
RoleWrapper roleWrapper = null;
if(publicRoleStateExportService.isPublicOnline(userRoleId)){
roleWrapper = roleExportService.getLoginRole(userRoleId);
}else{
roleWrapper = roleExportService.getUserRoleFromDb(userRoleId);
}
//่ง่ฒไธๅญๅจ
if(roleWrapper == null){
return HttpErrorCode.ROLE_NOT_EXIST;
}
//ๆๅIPๅ
็ๅจ็บฟ็ฉๅฎถ่ธขไธ็บฟ
String lastLoginIp = roleWrapper.getLastLoginIp();
Object[] roleIds = sessionManagerExportService.getRoleIdsByIp(lastLoginIp);
if(roleIds != null){
for( Object obj : roleIds ){
Long roleId = (Long)obj;
Object result = new Object[]{GameConstants.GM_OFFLINE,lastLoginIp};
sessionManagerExportService.tiChuOfflineSingle(roleId,result);
}
}
FengIp fengIp = fengIpDao.getFengIpByIp(lastLoginIp);
long expireTime = FengHaoUtil.getExpireTime(keepTime);
if(fengIp == null){
fengIp = new FengIp();
fengIp.setIp(lastLoginIp);
fengIp.setReasons(reasons);
fengIp.setServerId(roleWrapper.getServerId());
fengIp.setExpireTime(expireTime);
fengIp.setUpdateTime(new Timestamp(GameSystemTime.getSystemMillTime()));
fengIpDao.cacheInsert(fengIp, userRoleId);
}else{
fengIp.setReasons(reasons);
fengIp.setExpireTime(expireTime);
fengIpDao.cacheUpdate(fengIp, userRoleId);
}
return lastLoginIp;
}
public void removeFengIpByIp(String ip) {
fengIpDao.delete(ip);
}
}
|
Java
|
UTF-8
| 1,110 | 2.125 | 2 |
[] |
no_license
|
package com.allei.service;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* @author alleiming 2017/8/6 ไธๅ9:45
*/
@RestController
public class ConsumerController {
private final Logger logger = LoggerFactory.getLogger(getClass());
@Resource
private HelloServiceHystrix helloServiceHystrix;
@RequestMapping(value = "/hello", method = RequestMethod.GET)
public String hello() {
RestTemplate restTemplate = new RestTemplate();
return restTemplate.getForEntity("http://localhost:8081/hello", String.class).getBody();
}
@RequestMapping(value = "/helloRobbin", method = RequestMethod.GET)
public String helloRobbin() {
//return restTemplate.getForEntity("http://hello-service/hello", String.class).getBody();
return helloServiceHystrix.hello();
}
}
|
Markdown
|
UTF-8
| 366 | 3.1875 | 3 |
[] |
no_license
|
# Linked List
> [Add Two Numbers](../problems/Add Two Numbers .md)
> [Delete Node in a Linked List](../problems/Delete Node in a Linked List .md)
> [Partition List](../problems/Partition List .md)
> [Remove Linked List Elements](../problems/Remove Linked List Elements .md)
> [Remove Nth Node From End of List](../problems/Remove Nth Node From End of List .md)
|
Java
|
UTF-8
| 1,025 | 3.703125 | 4 |
[] |
no_license
|
package model.players;
import java.awt.*;
/**
* Player factory which creates different kinds of players.
*
* @author Roberto Shino
* @author Arian Mohamad Hosaini
* @author Wenjing Qu
*/
public class PlayerFactory {
/**
* Creates either a Striker or a Goalkeeper based on the given type, and returns it.
* Returns nothing if the type given does not match one of the types allowed.
*
* @param type the desired type of player to be created
* @return <code>Striker</code> if the given type is striker (not case sensitive)
* <code>Goalkeeper</code> if the given type is goalkeeper (not case sensitive)
* <code>null</code> if the given type does not match one of the allowed types
*/
public GamePlayer getPlayer(String type) {
if ("striker".equalsIgnoreCase(type)) {
return new Striker("Striker", Color.BLUE);
} else if ("goalkeeper".equalsIgnoreCase(type)) {
return new Goalkeeper("Goalkeeper", Color.ORANGE);
} else {
return null;
}
}
}
|
Python
|
UTF-8
| 9,048 | 2.734375 | 3 |
[] |
no_license
|
###############################################################################
#Author : Yingyu
#Date : 24th August 2020
#Description : Tool to filter out images based on different classes and stores
# images into the respective files
###############################################################################
from imutils import build_montages
from imutils import paths
import argparse
import random
import cv2
import os
# construct the argument parse and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--images", required=True,
help="path to input directory of images")
args = vars(ap.parse_args())
maskClick = []
faceClick = []
discardClick = []
naClick = []
rectClick = []
imageClick = []
eachImageWidth = 0
eachImageHeight = 0
namedWindow = "Image"
def click_and_crop(event, x, y, flags, param):
# grab references to the global variables
global rectClick
if event == cv2.EVENT_LBUTTONDOWN:
rectClick.append((x, y))
def mask():
global rectClick, maskClick
maskClick.extend(rectClick)
print ("maskClick: ", maskClick)
def face():
global rectClick, faceClick
faceClick.extend(rectClick)
print ("faceClick: ", faceClick)
def discard():
global rectClick, discardClick
discardClick.extend(rectClick)
print ("discardClick: ", discardClick)
def na():
global rectClick, naClick
naClick.extend(rectClick)
print ("naClick: ", naClick)
def switcherRectToType(argument):
switcher = {
"mask":mask,
"face":face,
"discard":discard,
"na":na
}
func = switcher.get(argument, lambda: "Invalid classification")
func()
def createList(startIndex, endIndex):
return [item for item in range(startIndex, endIndex)]
def clearAll(originalImage):
global maskClick, faceClick, discardClick, naClick, rectClick, imageClick
maskClick = []
faceClick = []
discardClick = []
naClick = []
rectClick = []
imageClick = []
cv2.imshow("image", originalImage)
def writeToFile(fileName, allImages, imageCounter, imageHop, eachImageWidth, eachImageHeight, displayColumn, displayRow, flag):
if flag == 0:
file = open(fileName, "a+")
for eachMask in maskClick:
x = eachMask[0]//eachImageWidth
y = eachMask[1]//eachImageHeight
#Computes the position in the grid
position = y * displayColumn + x
print ("grid position: ", position)
position += imageCounter * imageHop
print ("total grid position: ", position)
#Finds the right image
storeImage = allImages[position]
print("image to be stored: ", storeImage)
file.write("%s\n" % storeImage)
file.close()
elif flag == 1:
file = open(fileName, "a+")
for eachFace in faceClick:
x = eachFace[0]//eachImageWidth
y = eachFace[1]//eachImageHeight
#Computes the position in the grid
position = y * displayColumn + x
print ("grid position: ", position)
position += imageCounter * imageHop
print ("total grid position: ", position)
#Finds the right image
storeImage = allImages[position]
print("image to be stored: ", storeImage)
file.write("%s\n" % storeImage)
file.close()
elif flag == 2:
file = open(fileName, "a+")
for eachNa in naClick:
x = eachNa[0]//eachImageWidth
y = eachNa[1]//eachImageHeight
#Computes the position in the grid
position = y * displayColumn + x
print ("grid position: ", position)
position += imageCounter * imageHop
print ("total grid position: ", position)
#Finds the right image
storeImage = allImages[position]
print("image to be stored: ", storeImage)
file.write("%s\n" % storeImage)
file.close()
elif flag == 3:
file = open(fileName, "a+")
for eachDiscard in discardClick:
x = eachDiscard[0]//eachImageWidth
y = eachDiscard[1]//eachImageHeight
#Computes the position in the grid
position = y * displayColumn + x
print ("grid position: ", position)
position += imageCounter * imageHop
print ("total grid position: ", position)
#Finds the right image
storeImage = allImages[position]
print("image to be stored: ", storeImage)
file.write("%s\n" % storeImage)
file.close()
elif flag == 4:
file = open(fileName, "a+")
#Finds out all the index that should be stored in this photo
startSave = imageCounter * imageHop
endSave = (imageCounter+1)*imageHop
if (endSave > len(allImages)):
endSave = len(allImages)
print ("imageHop: ", imageHop)
allIndexForImage = createList(startSave, endSave)
print ("allIndexForImage: ", allIndexForImage)
for noSave in imageClick:
x = noSave[0]//eachImageWidth
y = noSave[1]//eachImageHeight
#Computes the position in the grid
position = y * displayColumn + x
print ("grid position: ", position)
position += imageCounter * imageHop
print ("total grid position: ", position)
allIndexForImage.remove(position)
for eachSave in allIndexForImage:
#Finds the right image
storeImage = allImages[eachSave]
print("image to be stored for the default: ", storeImage)
file.write("%s\n" % storeImage)
file.close()
def saveFiles(allImages, imageCounter, imageHop, eachImageWidth, eachImageHeight, displayColumn, displayRow):
global maskClick, faceClick, discardClick, naClick
writeToFile("maskFile.txt", allImages, imageCounter, imageHop, eachImageWidth, eachImageHeight, displayColumn, displayRow, 0)
writeToFile("faceFile.txt", allImages, imageCounter, imageHop, eachImageWidth, eachImageHeight, displayColumn, displayRow, 1)
writeToFile("naFile.txt", allImages, imageCounter, imageHop, eachImageWidth, eachImageHeight, displayColumn, displayRow, 2)
writeToFile("discardFile.txt", allImages, imageCounter, imageHop, eachImageWidth, eachImageHeight, displayColumn, displayRow, 3)
#300820 Assuming that maskFile.txt is the default file to save images in
writeToFile("maskFile.txt", allImages, imageCounter, imageHop, eachImageWidth, eachImageHeight, displayColumn, displayRow, 4)
def drawOut(typeObject):
global rectClick, imageClick
switcherRectToType(typeObject)
imageClick.extend(rectClick)
for eachPair in rectClick:
x = eachPair[0]
y = eachPair[1]
startingPointX = x//eachImageWidth * eachImageWidth + int(eachImageWidth/2)
startingPointY = y//eachImageHeight * eachImageHeight + int(eachImageHeight/2)
cv2.putText(montage,typeObject, (startingPointX, startingPointY), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0))
cv2.circle(montage, (startingPointX, startingPointY), 10, (0,0,255), -1)
cv2.imshow("image", montage)
rectClick = []
imagePaths = list(paths.list_images(args["images"]))
#check the number of images in the directory
print ("# of files: ", len(imagePaths))
displayColumn = input("number of pictures to be display per row?")
displayRow = input ("number of rows of pictures?")
namedWindow = "Click f for face, click m for mask, click d for discard, click e for exception, click n for next"
images = []
# loop over the list of image paths
cv2.namedWindow(namedWindow)
cv2.setMouseCallback(namedWindow, click_and_crop)
for imagePath in imagePaths:
# load the image and update the list of images
image = cv2.imread(imagePath)
images.append(image)
# construct the montages for the images
montages = build_montages(images, (128, 196), (displayColumn, displayRow))
eachImageWidth = 128
eachImageHeight = 196
imageCounter = -1
imageHop = displayColumn * displayRow
for montage in montages:
rectClick = []
maskClick = []
faceClick = []
naClick = []
discardClick = []
imageClick = []
cv2.imshow(namedWindow, montage)
originalImage = montage.copy()
imageCounter += 1
while True:
key = cv2.waitKey(0)
if key == ord("f"):
drawOut("face")
elif key == ord("m"):
drawOut("mask")
elif key == ord("n"):
drawOut("na")
elif key == ord("d"):
drawOut("discard")
elif key == ord("r"):
clearAll(originalImage)
montage = originalImage
elif key == 32:
saveFiles(imagePaths, imageCounter, imageHop, eachImageWidth, eachImageHeight, displayColumn, displayRow);
break
|
C++
|
UTF-8
| 1,003 | 3.9375 | 4 |
[] |
no_license
|
#include <iostream>
//๋งค๊ฒ๋ณ์์ ์์ํ.(๋ชจ๋ ํจ์๊ฐ ์ฌ์ฉํ ์ ์์) //๋ฉ์๋์ ๋ค์ด์ค๋ ํ๋ผ๋ฏธํฐ์ ์์ํ๋ฅผ ํด์ฃผ๋ ๋ฐฉ์
//๋ฉ์๋์ ์์ํ. (๋ฉค๋ฒ ๋ฉ์๋-ํ์ ๋ ๋๋) //const
using namespace std;
class Account{
private:
int money;
public:
//์์ฑ์ ์์ฑ
Account() :money(0){};
Account(int money): money(money){};
void Deposit(const int d){ //<<๋ฉ๊ฒ๋ณ์์ ์์ํ
money+=d;
cout << d<< "์์ ์
๊ธํ๋ค"<< endl;
}
void Draw(const int d){ //๋ฉ๊ฒ๋ณ์์ ์์ํ
if(money>d){
money-=d;
cout << d <<"์์ ์ธ์ถ ํ๋ค"<< endl;
}
}
int ViewMoney() const { //const ๋ ๋ฉ์ค๋๋ฅผ ์์ํ ํด์ฃผ๋ ๋ช
๋ น์ด (๊ฐ์ด ๋ณํ ์๊ฐ ์๋ค)
return money;
}
};
int main() {
Account test (100);//์ด๊ธฐ์๋ณธ ์ ์ฅ
test.Deposit(20); //์๊ธ
test.Draw(10); //์ถ๊ธ
cout<< test.ViewMoney() << endl;
}
|
Python
|
UTF-8
| 1,965 | 3.078125 | 3 |
[
"MIT"
] |
permissive
|
# Imports from 3rd party libraries
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
# Imports from this application
from app import app
# 1 column layout
# https://dash-bootstrap-components.opensource.faculty.ai/l/components/layout
column1 = dbc.Col(
[
dcc.Markdown(
"""
## Insights
After Creating Essentially two models there are many things that did not go as I had
expected. One example would be the fact my app model only lost roughly 3 percent
validation accuracy compared to the full model. This seems like a rather small drop
in accuracy rating for the amount of Data that was lost.
#### The Different Models
Three models had been tested for both features including a Logistic Regression,
Random Forest and XGBoost model. The Random Forest Model and the XGBoost model stayed
relatively close to each other in accuracy.
"""
),
html.Img(src='assets/ROC.jpg', className='img-fluid'),
html.Img(src='assets/Accuracy.jpg', className='img-fluid'),
dcc.Markdown(
"""
Even the ROC score had the models relatively the same. Though the XGBoost model
always managed to perform slightly better with a .93 ROC score compared to a .92
validation score the Random Forest model had. Even the validation score for the XGBoost
model was typically a percent higher than the Random forest model. However after XGBoost
model was chosen and the app had been created I ran the Random Forest model against
the test data set. It managed to perform a percent or two higher than the XGBoost model.
"""
),
],
)
layout = dbc.Row([column1])
|
C++
|
UTF-8
| 475 | 2.625 | 3 |
[] |
no_license
|
//
// Created by Kenneth-Matthew Velarde on 2019-03-12.
//
#include "floatingarray.h"
#include "iostream"
using namespace std;
float arr[5];
floatingarray::floatingarray(int asize) {
size = asize;
arr[5] = arr[size];
}
int floatingarray::storeNum(int numstore, int spot) {
return arr[spot] = numstore;
}
int floatingarray::getNum(int numb) {
return arr[numb];
}
int floatingarray::getHigh() {
return arr[size];
}
int floatingarray::getLow() {
return arr[0];
}
|
Java
|
UTF-8
| 421 | 2.765625 | 3 |
[] |
no_license
|
package exercicio3;
public class Ingresso {
public double valor = 245;
public double getValor() {
return valor;
}
public void setValor(double valor) {
this.valor = valor;
}
public void imprimirNota(){
System.out.println("*NOTA DO INGRESSO*:"
+ "\n" + "VALOR DO INGRESSO: R$"+this.valor);
}
}
|
Java
|
UTF-8
| 3,739 | 2.90625 | 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.
*/
import carpanel.CarPanel;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
import org.junit.Rule;
import org.junit.rules.ExpectedException;
/**
*
* @author Michaล
*/
public class JunitTest {
CarPanel cp;
public JunitTest() {
cp = new CarPanel();
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test
public void test1() {
System.out.print("Speed:" + cp.display_Speed(0, 0) + " Distance:" + cp.getS() + " Time:" + cp.getT());
System.out.println(", WARN: " + cp.isWARN());
}
@Test
public void test2() {
System.out.print("Speed:" + cp.display_Speed(120, 1) + " Distance:" + cp.getS() + " Time:" + cp.getT());
System.out.println(", WARN: " + cp.isWARN());
}
@Test
public void test3() {
System.out.print("Speed:" + cp.display_Speed(Double.MAX_VALUE, 1) + " Distance:" + cp.getS() + " Time:" + cp.getT());
System.out.println(", WARN: " + cp.isWARN());
}
@Test
public void test4() {
System.out.print("Speed:" + cp.display_Speed(1, 0.01) + " Distance:" + cp.getS() + " Time:" + cp.getT());
System.out.println(", WARN: " + cp.isWARN());
}
@Test
public void test5() {
System.out.print("Speed:" + cp.display_Speed(120.1,1) + " Distance:" + cp.getS() + " Time:" + cp.getT());
System.out.println(", WARN: " + cp.isWARN());
}
@Test
public void test6() {
System.out.print("Speed:" + cp.display_Speed(Double.MIN_VALUE,2) + " Distance:" + cp.getS() + " Time:" + cp.getT());
System.out.println(", WARN: " + cp.isWARN());
}
@Test
public void test7() {
System.out.print("Speed:" + cp.display_Speed(-0.1d,0.02) + " Distance:" + cp.getS() + " Time:" + cp.getT());
System.out.println(", WARN: " + cp.isWARN());
}
@Test
public void test8() {
System.out.print("Speed:" + cp.display_Speed(2d, Double.MIN_VALUE) + " Distance:" + cp.getS() + " Time:" + cp.getT());
System.out.println(", WARN: " + cp.isWARN());
}
@Test
public void test9() {
System.out.print("Speed:" + cp.display_Speed(-10d, -0.1) + " Distance:" + cp.getS() + " Time:" + cp.getT());
System.out.println(", WARN: " + cp.isWARN());
}
@Test
public void test10() {
System.out.print("Speed:" + cp.display_Speed(120, 1.01) + " Distance:" + cp.getS() + " Time:" + cp.getT());
System.out.println(", WARN: " + cp.isWARN());
}
@Test
public void test11() {
System.out.print("Speed:" + cp.display_Speed(2, Double.MAX_VALUE) + " Distance:" + cp.getS() + " Time:" + cp.getT());
System.out.println(", WARN: " + cp.isWARN());
}
@Test
public void test12() {
System.out.print("Speed:" + cp.display_Speed(2 * Double.MIN_VALUE, 2) + " Distance:" + cp.getS() + " Time:" + cp.getT());
System.out.println(", WARN: " + cp.isWARN());
}
@Test
public void test13() {
System.out.print("Speed:" + cp.display_Speed(-0.02, 2) + " Distance:" + cp.getS() + " Time:" + cp.getT());
System.out.println(", WARN: " + cp.isWARN());
}
}
|
C
|
UTF-8
| 17,708 | 2.921875 | 3 |
[] |
no_license
|
/**********************************************************************************************************/
/* 2016A - 20407 : Final Project ***********************************************************************/
/* @author: Chanan Welt *******************************************************************************/
/* @date 20/02/2016 ***********************************************************************************/
/**********************************************************************************************************/
/* This project implements the most efficient data structure for managing a dynamic set of bank customers.*/
/* The managing include supporting all dictionary basic queries - insert, delete, search, and some more */
/* complex ones: all clients with a negative balance, updating balance (increase/decrease), max and more. */
/* The efficiency of the various variations is valuated as a function of N - the number of accounts in the*/
/* bank, or in other words - the number of records in the dynamic set. */
/* The most efficient data structure known to me by this time for implementing such a task is a balanced */
/* binary-search-tree. In this project the balanced type of tree which is used is a basic red-black tree */
/* and an augmented red-black tree, which is a order-statistic tree. basic operations on this data struct'*/
/* operate in time of O(lgn) on the worst case scenario ***************************************************/
/**********************************************************************************************************/
#include "io_utils.h"
#include "rb_tree.h"
#include "os_tree.h"
int main (int argc, char *argv[])
{
FILE *input_fp; /* input file pointer */
FILE *output_fp; /* output file pointer */
time_t current_time;
char *timestamp;
unsigned int file_counter = 0;
char *argument_name; /* name of current command line argument */
char file_name[FILE_MAX_NAME];
char output_file_name[FILE_OUT_MAX_NAME];
unsigned int arg_name_length;
unsigned int line_counter = 0;
char current_input_line[MAX_LINE_LENGTH];
char current_token[MAX_LINE_LENGTH];
char *line_parser;
int operation;
customer customer_record;
customer *customer_ptr = &customer_record;
int success_indicator;
os_tree_header *T_data_structure_ptr;
os_tree_node *sentinel;
os_tree_node *min_sentinel;
os_tree_node *max_sentinel;
os_tree_node *temp_util_node;
rb_tree_node *rb_sentinel;
rb_tree_node *rb_temp_util_node;
float temp_sum = 0;
int i, j, k = 0;
/* get current time stamp for log documentation and output file name */
current_time = time(NULL);
timestamp = ctime(¤t_time);
/* create data structure: header data and sentinels */
T_data_structure_ptr = (os_tree_header*)calloc(1, sizeof(os_tree_header));
sentinel = (os_tree_node*)calloc(1, sizeof(os_tree_node));
min_sentinel = (os_tree_node*)calloc(1, sizeof(os_tree_node));
max_sentinel = (os_tree_node*)calloc(1, sizeof(os_tree_node));
rb_sentinel = (rb_tree_node*)calloc(1, sizeof(rb_tree_node));
if((T_data_structure_ptr == NULL) || (sentinel == NULL) || (min_sentinel == NULL) || (max_sentinel == NULL) || (rb_sentinel == NULL))
{
fprintf(output_fp, "%s %s", argv[0], msg_main_memory);
return EXIT_FAILURE;
}
/* first initialization of data structure */
T_data_structure_ptr->nil_sentinel = sentinel;
T_data_structure_ptr->rb_nil_sentinel = rb_sentinel;
T_data_structure_ptr->root = sentinel;
T_data_structure_ptr->rb_root = rb_sentinel;
T_data_structure_ptr->max_sentinel = min_sentinel;
T_data_structure_ptr->max_sentinel = max_sentinel;
T_data_structure_ptr->min = min_sentinel;
T_data_structure_ptr->max = max_sentinel;
min_sentinel->balance = LONG_MAX;
max_sentinel->balance = LONG_MIN;
temp_util_node = T_data_structure_ptr->root; /* set temp to point on os-tree root */
temp_util_node->parent = sentinel; /* set os-tree root's parent to nil sentinel */
sentinel->customer_num = NIL_SENTINEL;
sentinel->parent = sentinel;
sentinel->left = sentinel;
sentinel->right = sentinel;
sentinel->color = BLACK;
sentinel->size = 0;
sentinel->parallel_node = rb_sentinel;
rb_temp_util_node = T_data_structure_ptr->rb_root; /* set temp to point on os-tree root */
rb_temp_util_node->parent = rb_sentinel; /* set os-tree root's parent to nil sentinel */
rb_sentinel->customer_num = NIL_SENTINEL;
rb_sentinel->parent = sentinel;
rb_sentinel->left = sentinel;
rb_sentinel->right = sentinel;
rb_sentinel->color = BLACK;
rb_sentinel->parallel_node = sentinel;
fprintf(stderr, "\n%s\n", timestamp);
/* check source of input: file or manually */
if (argc > 1) /* at least one file */
{/* validate there are not too many files (security & memory concerns) */
if (argc > (MAX_FILES+1))
fprintf(stderr, msg_max_files, argv[0], MAX_FILES);
while (--argc > 0 && file_counter < MAX_FILES)
{
file_counter++;
argument_name = *++argv;
arg_name_length = strlen(argument_name);
if (arg_name_length > FILE_MAX_NAME)
{
fprintf(stderr, msg_file_name_length, argv[0], argument_name, FILE_MAX_NAME);
continue;
}
/* try to open input file for reading */
strcpy(file_name, argument_name);
if ((input_fp = fopen(file_name, "r")) == NULL)
{ /* if error */
fprintf(stderr, "File %d: %s \'%s\'.\n", file_counter, msg_file_open_failure, file_name);
continue;
}
/* set output file name */
strcpy(output_file_name, file_name);
strcat(output_file_name, "_");
strncat(output_file_name, timestamp, TIMESTAMP_LENGTH);
strcat(output_file_name, output_file_name_suffix);
/* try to open output file for writing */
if ((output_fp = fopen(output_file_name, "w")) == NULL)
{ /* if error */
fprintf(stderr, msg_file_creation_err, output_file_name);
continue;
}
fprintf(output_fp, header_line);
fprintf(output_fp, report_title, file_name);
fprintf(output_fp, header_line);
line_counter = 0;
/* loop at all input lines, one at a time */
while(fgets(current_input_line, (MAX_LINE_LENGTH+1), input_fp))
{
if(file_counter > 0)
fprintf(output_fp, "\n\nline %-2d ", ++line_counter); /* update line counter */
if (strlen(current_input_line) == MAX_LINE_LENGTH)
{
fprintf(output_fp, msg_line_length, MAX_LINE_LENGTH);
continue;
}
READ_INPUT: /*set label for enabling manual input as well */
fprintf(output_fp, "input: %s\toutput:\t", current_input_line);
/* in case the input is manually via command line interpreter, check if the user wants to quit */
if(*current_input_line == 'q')
{
fprintf(output_fp, "\n%s", long_header_line);
fprintf(output_fp, "Rank|| First name || Last name\t || Id num || Customer\t || Balance \t|| Color|\n");
fprintf(output_fp, "%s", long_header_line);
OS_INORDER_TREE_WALK(T_data_structure_ptr, T_data_structure_ptr->root, output_fp); /* if so, print result */
return EXIT_SUCCESS;
}
line_parser = strcpy(current_token, current_input_line);
operation = determine_operation(line_parser); /* check what is the wished operation */
if((operation == EMPTY_LINE) || (operation == NOT_FOUND))
{
if(operation == NOT_FOUND)
fprintf(output_fp, msg_illegal_op, line_parser);
else fprintf(output_fp, "\n");
continue;
}
/* map user's input to programs params for integrating between the different modules */
success_indicator = map_data(operation, line_parser, &customer_record);
if (success_indicator == EXIT_SUCCESS)
{
switch (operation) /* proceed according to the matching operation requested */
{
case DEPOSIT_WITHDRAW:
{
/* search for the customer node in rb-tree */
rb_temp_util_node = RB_ITERATIVE_TREE_SEARCH(T_data_structure_ptr, T_data_structure_ptr->rb_root, customer_ptr->customer_number);
if(rb_temp_util_node == T_data_structure_ptr->rb_nil_sentinel) /* error if not found */
{
fprintf(output_fp, msg_customer_not_found, customer_ptr->customer_number);
continue;
}
temp_util_node = rb_temp_util_node->parallel_node; /* get parallel node in os-tree */
temp_sum = customer_ptr->balance; /* save requested amount for deposit\ withdraw */
/* map satellite data from current node to structure for a node with new balance */
strcpy(customer_ptr->first_name, temp_util_node->first_name);
strcpy(customer_ptr->last_name, temp_util_node->last_name);
strcpy(customer_ptr->id_number, temp_util_node->id_number);
customer_ptr->balance = (customer_ptr->balance) + (temp_util_node->balance);
temp_util_node = OS_INSERT(T_data_structure_ptr, customer_ptr);
if(temp_util_node == NULL)
{
fprintf(output_fp, "%s", msg_node_memory);
continue;
}
T_data_structure_ptr->root = temp_util_node; /*update root after insertion of new node*/
temp_util_node = rb_temp_util_node->parallel_node;
temp_util_node = OS_DELETE(T_data_structure_ptr, temp_util_node);
free(temp_util_node);
rb_temp_util_node = RB_DELETE(T_data_structure_ptr, rb_temp_util_node);
free(rb_temp_util_node);
fprintf(output_fp, feedback_balance_upd, (customer_ptr->balance - temp_sum), customer_ptr->balance);
continue;
}
case NEW_CUSTOMER:
{
rb_temp_util_node = RB_ITERATIVE_TREE_SEARCH(T_data_structure_ptr, T_data_structure_ptr->rb_root, customer_ptr->customer_number);
if(rb_temp_util_node != T_data_structure_ptr->rb_nil_sentinel)
{
fprintf(output_fp, "%s", msg_customer_already_exsits);
continue;
}
temp_util_node = OS_INSERT(T_data_structure_ptr, customer_ptr);
if(temp_util_node != NULL)
{
T_data_structure_ptr->root = temp_util_node; /* return updated root after insertion */
fprintf(output_fp, feedback_new_cust, customer_ptr->first_name, customer_ptr->last_name, customer_ptr->customer_number, customer_ptr->id_number, customer_ptr->balance);
continue;
}
else
{
fprintf(output_fp, "%s", msg_node_memory);
continue;
}
}
case CUSTOMER_LEAVE:
{
rb_temp_util_node = RB_ITERATIVE_TREE_SEARCH(T_data_structure_ptr, T_data_structure_ptr->rb_root, customer_ptr->customer_number);
if(rb_temp_util_node == T_data_structure_ptr->rb_nil_sentinel)
{
fprintf(output_fp, msg_customer_not_found, customer_ptr->customer_number);
continue;
}
temp_util_node = rb_temp_util_node->parallel_node; /* get parallel node from os-tree */
/* assure account is balanced to zero before deletion */
if(temp_util_node->balance!= 0)
{
fprintf(output_fp, msg_balance_not_zero, temp_util_node->balance);
continue;
}
/* delete parallel node from os-tree */
temp_util_node = OS_DELETE(T_data_structure_ptr, temp_util_node); /* delete os-tree node */
free(temp_util_node); /*free memory of deleted os-tree node */
/* delete node of rb-tree */
rb_temp_util_node = RB_DELETE(T_data_structure_ptr, rb_temp_util_node); /*delete rb-node */
free(rb_temp_util_node); /*free memory of rb node */
/* print feedback */
fprintf(output_fp, feedback_delete_cust, customer_ptr->customer_number);
continue;
}
case QUERY_BALANCE:
{
rb_temp_util_node = RB_ITERATIVE_TREE_SEARCH(T_data_structure_ptr, T_data_structure_ptr->rb_root, customer_ptr->customer_number);
if(rb_temp_util_node == T_data_structure_ptr->rb_nil_sentinel)
{
fprintf(output_fp, msg_customer_not_found, customer_ptr->customer_number);
continue;
}
temp_util_node = rb_temp_util_node->parallel_node;
fprintf(output_fp, feedback_balance_query, temp_util_node->balance);
continue;
}
case QUERY_MAX:
{
if(T_data_structure_ptr->max == T_data_structure_ptr->max_sentinel)
{ /* if no nodes are found */
fprintf(output_fp, "%s", feedback_max_query_none);
continue;
}
fprintf(output_fp, "%s", feedback_max_query);
print_customer_data(T_data_structure_ptr->max, output_fp);
continue;
}
case QUERY_NEGETIVE_BALANCE:
{
temp_util_node = T_data_structure_ptr->min;
if(temp_util_node->balance >= 0)
fprintf(output_fp, "%s", feedback_negative_not_found);
else
{
fprintf(output_fp, "%s", negative_query_title);
OS_ENUMERATE(T_data_structure_ptr, T_data_structure_ptr->root, LONG_MIN, 0, output_fp);
continue;
}
}
default: break;
}
continue;
}
else
{
fprintf(output_fp, "%s :\"%s\"", msg_map_data, current_input_line);
continue;
}
}
if(file_counter > 0)
fprintf(stderr, "File %d: \'%s\' processed, output report successfully generated.\n", file_counter, file_name);
fprintf(output_fp, "\n%s", long_header_line);
fprintf(output_fp, "Rank|| First name || Last name\t || Id num || Customer\t || Balance \t|| Color|\n");
fprintf(output_fp, "%s", long_header_line);
OS_INORDER_TREE_WALK(T_data_structure_ptr, T_data_structure_ptr->root, output_fp);
}
}
else /* (argc == 1) no arguments (no files) */
{
fprintf(stderr, msg_no_files, argv[0]);
fgets(current_input_line, MAX_LINE_LENGTH+1, stdin);
input_fp = stdin;
output_fp = stderr;
goto READ_INPUT;
exit (EXIT_SUCCESS);
}
exit (EXIT_SUCCESS);
}
|
C++
|
UTF-8
| 974 | 2.546875 | 3 |
[] |
no_license
|
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
vector<int> g[2020];
vector<int> rg[2020];
bool vis[2020];
stack<int>st;
int scc;
int id[2020];
// get topological ordering of nodes and
// goes through it on the reverse graph
void dfs(int x){
vis[x] = true;
for(int i = 0 ; i < g[x].size() ; i ++)
if(!vis[g[x][i]]) dfs(g[x][i]);
st.push(x);
}
void dfs2(int x){
id[x] = scc;
for(int i = 0 ; i < rg[x].size() ; i ++)
if(id[rg[x][i]] == -1) dfs2(rg[x][i]);
}
int main(){
ios::sync_with_stdio(false); cin.tie(0);
memset(id, -1 ,sizeof id);
int n, m;
cin>>n>>m;
for(int a, b, i = 0 ; i < m ; i ++){
cin>>a>>b;
g[a].pb(b);
rg[b].pb(a);
}
for(int i = 1 ; i <= n ; i ++)
if(!vis[i]) dfs(i);
while(!st.empty()){
int u = st.top();
st.pop();
if(id[u] != -1) continue;
id[u] = scc;
dfs2(u);
scc++;
}
for(int i = 1 ; i <= n ; i ++)
cout<<"id["<<i<<"] = "<<id[i]<<"\n";
return 0;
}
|
C
|
UTF-8
| 1,509 | 2.59375 | 3 |
[] |
no_license
|
#include <stdarg.h>
#include <stdbool.h>
#include <stdint.h>
#include "inc/hw_i2c.h"
#include "inc/hw_memmap.h"
#include "inc/hw_types.h"
#include "inc/hw_gpio.h"
#include "driverlib/i2c.h"
#include "driverlib/sysctl.h"
#include "driverlib/gpio.h"
#include "driverlib/pin_map.h"
#include "driverlib/uart.h"
#include "utils/uartstdio.h"
#define DELAY(x) SysCtlDelay(SysCtlClockGet() / (1000 * 3) * x)
void InitConsole(void); //Init UART
// Function prototype to read the Accelerometer
int main(void) {
SysCtlClockSet(SYSCTL_SYSDIV_1 | SYSCTL_USE_OSC | SYSCTL_OSC_MAIN | SYSCTL_XTAL_16MHZ);
InitConsole();
while (1) {
DELAY(500);
UARTprintf("Hallo Welt!\n");
}
return 0;
}
void InitConsole(void)
{
//
// Enable GPIO port A which is used for UART0 pins.
//
SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);
//SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOB);
//
// Configure the pin muxing for UART0 functions on port A0 and A1.
// This step is not necessary if your part does not support pin muxing.
//
GPIOPinConfigure(GPIO_PA0_U0RX);GPIOPinConfigure(GPIO_PA1_U0TX);
//GPIOPinConfigure(GPIO_PB0_U1RX);GPIOPinConfigure(GPIO_PB1_U1TX);
//
// Select the alternate (UART) function for these pins.
//
GPIOPinTypeUART(GPIO_PORTA_BASE, GPIO_PIN_0 | GPIO_PIN_1);
//GPIOPinTypeUART(GPIO_PORTB_BASE, GPIO_PIN_0 | GPIO_PIN_1);
//
// Initialize the UART for console I/O.
//
UARTStdioConfig(0, 115200, 16000000);
}
|
Java
|
UTF-8
| 1,173 | 2.484375 | 2 |
[
"MIT"
] |
permissive
|
package ee.ria.riha.service.util;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import org.springframework.util.Assert;
import java.util.ArrayList;
import java.util.List;
/**
* Response model for paged list.
*
* @author Valentin Suhnjov
*/
@Getter
@Setter
public class PagedResponse<T> {
@Getter(value = AccessLevel.PRIVATE)
@Setter(value = AccessLevel.PRIVATE)
private Pageable pageable;
private long totalElements;
private List<T> content = new ArrayList<>(0);
public PagedResponse(Pageable pageable, long totalElements, List<T> content) {
this(pageable);
this.totalElements = totalElements;
this.content = content;
}
public PagedResponse(Pageable pageable) {
Assert.notNull(pageable, "pageable must not be null");
this.pageable = pageable;
}
public PagedResponse() {
}
public int getSize() {
return pageable.getPageSize();
}
public int getPage() {
return pageable.getPageNumber();
}
public int getTotalPages() {
return getSize() == 0 ? 1 : (int) Math.ceil((double) totalElements / (double) getSize());
}
}
|
Markdown
|
UTF-8
| 6,687 | 2.921875 | 3 |
[] |
no_license
|
---
layout: post
title: "What is Self-Sovereign Identity?"
summary: A beginner's introduction to Self-Sovereign Identity (SSI)
date: 2020-12-07 11:07:00 +0100
author: sam_jones
image: /assets/images/luis-alberto-certs.jpg
published: true
---

###### Title photo: [Luis Alberto Cardenas Otaya](https://www.pexels.com/@luis-alberto-cardenas-otaya-2321018)
|Time: | 5 minute read |
# Introduction
In late November the Mimoto team had a virtual 'stand' at [Identity week 2020](https://www.terrapinn.com/exhibition/identity-week/index.stm).
Originally planned as a physical conference, it eventually migrated online due
to the COVID-19 pandemic. As our first conference as exhibitors the virtual
format made for a very different experience from meeting people in person.
The event featured a wide range of interactive talks from international experts
in digital identity. One of the main themes of the event was Self-Sovereign
Identity (SSI). Whilst watching some of the talks about SSI, I reflected that
often when people ask me what I do, I end up having to explain the concept of
federated identity as a kind of pre-requisite piece of knowledge. With this in
mind, I thought it would be useful to write a beginner's introduction to SSI
and briefly cover how it differs from centrally managed identity and federated
identity.
# What is Self-Soverign Identity
The concept is still young and there is still a bit of discussion of what
exactly is and isn't SSI but broadly speaking it's a authentication system
where by a user can authenticate themselves to a service without having to rely
on a central authority to enable that process. In this scenario the service
doesn't need prior knowledge of the user, it can establish a trust based on the
information the user supplies. The user has control over their identity and
isn't reliant on a central authority to provide it on their behalf.
# Identity architectures
It is helpful to look at Self-Soverign Identity in the context of other identity infrastructures.

## Centralized
(Unfortunately) most login experiences we have are based on a centralized
identity infrastructure. As an example, think of the experience you've had when
you want to buy something from an online shop. You want to use this service,
first you have to register your details and create a set of credentials that
you'll use to access the service. It's easy for the service provider to setup
but it has a lot of negative affects for everyone involved: the user has _so_
many credentials, the service provider has a data security headache, and the
whole approach fosters an environment where it is easy for a malicious attacker
to win.
## Open-trust
This is the Google and Facebook login model. A handful of large Identity
Providers (IdPs) grant access to a vast range of services. The users identity
information is hosted and controlled by these giant IdPs. Differences in
protocol flavours mean that service providers (SPs) can end up creating multiple
login handlers to allow access to their site from two or more of these huge
IdPs. The IdPs have control over which SPs can use the authentication
framework, and what happens to the users data. The user does have fewer
credentials to remember however.
## Federated Trust
With a federated login system, a user's identity is hosted by an Identity
Provider (IdP) at a logical home institution for the user. They use the IdP to
authenticate to one or more service providers (SPs). The IdP also discloses an
amount of data about the user to the SP, the level of disclosure is ultimately
at the IdP owners discretion. To the point where access can be trusted to be
both anonymous and authenticated at the same time. An interesting concept when
you think about it.
With federated login systems the user doesn't interact with the federation
directly; they're most likely not even aware of it. The federation is
essentially a register of participating IdPs and SPs and trust data they need
to be able to interact with each other. The IdPs and SPs download a copy of
this register and use it to establish technical trusts between themselves
whilst authenticating users. Within the federated identity sphere users
typically have one identity they use across a range of services, they have
control of their own data if their IdP delegates that to them. Here at Mimoto
one of our products is [Indiid](https://indiid.net), an IdP in the federated
model where users have control of their identity.
## Self Sovereign identity
Returning to self sovereign identity; in this model there is no IdP. The user
has a digital identity, perhaps stored on a phone, which authenticates them to
service providers. This can only work if the service provider has something
they can put their trust in. With self sovereign identity the trust framework is
provided by a de-centralized trust technology. Many are proposing blockchain as
a way of providing this.
You may be aware of a old technology called Pretty Good Privacy (PGP) as a
means of establishing the true identity of a email sender. In some ways it
helps to think of PGP as something that is pretty close to a SSI. Users control
a set of cryptographic keys they use to sign and/or encrypt data, and they also
control which keys they trust. It's a peer to peer model with no immediately
apparent central authority that controls access to the technology. However,
its strong link to email, and therefore the domain name system, means it can
be seen as dependant on the ICANN authority which precludes it from being an
SSI to many.
## Conclusion
There is obviously a lot more to this topic than I can do justice to in a short
introduction, so I thought I would end with some questions to ponder:
* How can we give the users control over their identity, whilst also making the technology simple enough for them to use in a secure way? Lots of users fall foul social engineering attacks even when the authentication model is simple.
* Who is responsible for the persistence and/or re-provisioning of the users identity? If it's the user, how can this be made simple? If it's an organisation how can we address the central authority issue?
* How will the decentralised trust fabric work? There is a lot of discussion about using blockchain but what are the costs of that and who bares them?
* How will a user's access to their own identity be protected?
I would be interested to hear your thoughts. If you fancy a chat about digital identity, or if the Mimoto team can help you with your needs, please do get in [touch.](/contact/)
|
Python
|
UTF-8
| 7,298 | 3.203125 | 3 |
[
"MIT"
] |
permissive
|
"""
Purpose of this is to handle MultiIndexes and ObjectIndexes in a more convenient
manner. Much like how DatetimeIndex has convenience tools like df.index.hour == 3.
I want the equivalent for objects and multiindexes
"""
import itertools
import operator
import numpy as np
import pandas as pd
from pandas import compat
from trtools.monkey import patch_prop
def _sub_method(op, name):
def _wrapper(self, other):
if isinstance(other, LevelWrapper):
other = other.values
return op(self.values, other)
return _wrapper
class LevelWrapper(object):
def __init__(self, name, getter):
self.name = name
self.getter = getter
def __getitem__(self, key):
# get level value by .levels which are the distinct monotonic values
if isinstance(key, int):
return self.labels[key]
raise KeyError(key)
@property
def labels(self):
"""
Return the acutal labels. Equivalent of MultiIndex.levels[x]
"""
return self.getter.level_name(self.name)
@property
def values(self):
""" Returns the actual values """
vals = self.getter.sub_column(self.name)
return vals
def __array__(self):
# TODO
# Reset dtypes to proper dtype. Other than the numerics, things like bools
# come out of here as dtype == object.
vals = self.values
# vals is pd.Index
# pd.Index promotes flaots to objects, we demote to float if it's numeric
if vals.is_numeric() and not isinstance(vals, pd.Int64Index):
vals = vals.values.astype(float)
else:
# always return an np.ndarray and not index
vals = vals.values
return vals
#----------------------------------------------------------------------
# Arithmetic operators
__add__ = _sub_method(operator.add, '__add__')
__sub__ = _sub_method(operator.sub, '__sub__')
__mul__ = _sub_method(operator.mul, '__mul__')
__truediv__ = _sub_method(operator.truediv, '__truediv__')
__floordiv__ = _sub_method(operator.floordiv, '__floordiv__')
__pow__ = _sub_method(operator.pow, '__pow__')
#__radd__ = _sub_method(_radd_compat, '__add__')
__rmul__ = _sub_method(operator.mul, '__mul__')
__rsub__ = _sub_method(lambda x, y: y - x, '__sub__')
__rtruediv__ = _sub_method(lambda x, y: y / x, '__truediv__')
__rfloordiv__ = _sub_method(lambda x, y: y // x, '__floordiv__')
__rpow__ = _sub_method(lambda x, y: y ** x, '__pow__')
# comparisons
__gt__ = _sub_method(operator.gt, '__gt__')
__ge__ = _sub_method(operator.ge, '__ge__')
__lt__ = _sub_method(operator.lt, '__lt__')
__le__ = _sub_method(operator.le, '__le__')
def __eq__(self, other):
vals = np.array(self)
try:
return np.isclose(vals, other)
except TypeError:
# likely here because vals/other is not numeric
return operator.eq(vals, other)
__ne__ = _sub_method(operator.ne, '__ne__')
# Python 2 division operators
if not compat.PY3:
__div__ = _sub_method(operator.div, '__div__')
__rdiv__ = _sub_method(lambda x, y: y / x, '__div__')
__idiv__ = __div__
class IndexGetter(object):
def __init__(self, obj, attr=None):
self._obj = obj
if isinstance(obj, pd.Index) and attr is None:
self._index = obj
else:
self._index = getattr(obj, attr)
def __getattr__(self, name):
if name in self.names:
return LevelWrapper(name, self)
raise AttributeError(name)
def sub_column(self, name):
"""
Return the value of name for every item in obj.columns
"""
raise NotImplementedError('Implement this in subclass')
@property
def names(self):
raise NotImplementedError('Implement this in subclass')
def level_name(self, name):
raise NotImplementedError('Implement this in subclass')
class MultiIndexGetter(IndexGetter):
"""
Handles MultiIndex.
Requires that that the levels be named.
"""
def sub_column(self, name):
return self._index.get_level_values(name)
def level_name(self, name):
"""
Get the .levels value by name
"""
ind = self._index.names.index(name)
return self._index.levels[ind]
@property
def names(self):
"""
Complete based off of MultiIndex.names
"""
return [c for c in self._index.names]
def _get_val(obj, name):
if isinstance(obj, dict):
return obj[name]
return getattr(obj, name)
class ObjectIndexGetter(IndexGetter):
"""
Handles an Index of objects and treats the attributes like un-ordered levels.
"""
def sub_column(self, name):
return pd.Index([_get_val(col, name) for col in self._index])
def level_name(self, name):
"""
Note that the only way to get the equivalent of MultiIndex.levels is to get all
values and then run unique. There should be caching done somewhere here
"""
vals = self.sub_column(name)
ind = vals.unique()
ind.sort()
ind = pd.Index(ind)
return ind
@property
def names(self):
"""
Try to grab the proper attrs for the Columns
Best case is that the object has a keys method.
"""
test = self._index[0]
try:
names = list(test.keys())
return names
except:
names = list(test.__dict__.keys())
return names
def _getter(obj, attr='columns'):
"""
This function returns IndexGetter based on obj and attr.
In retrospect, this is a bit cludgy. It was done to support passing in
an object and not just its index.
"""
index = getattr(obj, attr)
getter_class = _getter_class(index)
return getter_class(obj, attr=attr)
def _getter_class(index):
"""
Parameters:
----------
index : pd.Index
Return:
-------
Proper IndexGetter class
"""
if isinstance(index, pd.MultiIndex):
return MultiIndexGetter
test = index[0]
if isinstance(index, pd.Index) and not np.isscalar(test):
return ObjectIndexGetter
@patch_prop([pd.DataFrame], 'col')
def col(self):
return _getter(self)
@patch_prop([pd.Index], 'lev')
def lev(self):
return _getter_class(self)(self)
# IPYTYHON
def install_ipython_completers(): # pragma: no cover
"""Register the DataFrame type with IPython's tab completion machinery, so
that it knows about accessing column names as attributes."""
from IPython.utils.generics import complete_object
@complete_object.when_type(MultiIndexGetter)
def complete_column_panel_items(obj, prev_completions):
return prev_completions + [c for c in obj.names \
if isinstance(c, str) and compat.isidentifier(c)]
# Importing IPython brings in about 200 modules, so we want to avoid it unless
# we're in IPython (when those modules are loaded anyway).
import sys
if "IPython" in sys.modules: # pragma: no cover
try:
install_ipython_completers()
except Exception:
pass
|
C++
|
UTF-8
| 5,358 | 3.15625 | 3 |
[] |
no_license
|
/*
GridMap.cpp
Created by Chengtao Wang on 12/20/2016
*/
#include "GridMap.h"
GridMap::GridMap(int row, int col)
{
this->row = row;
this->col = col;
this->startStatus = 0;
this->goalStatus = 0;
//generate image
this->image = Mat3b(30 * row + 60, 30 * col, Vec3b(255, 255, 255));
this->button = Rect(0, 0, this->image.cols, 30);
this->button_clean = Rect(0, 30 + 30 * row, this->image.cols, 30);
this->image(this->button) = Vec3b(200, 200, 200);
this->image(this->button_clean) = Vec3b(200, 200, 200);
const string buttonText = "Start!";
const string cleanText = "Clean!";
putText(this->image(this->button), buttonText, Point(this->button.width*0.45, this->button.height*0.7), FONT_HERSHEY_PLAIN, 1, Scalar(0, 0, 0));
putText(this->image(this->button_clean), cleanText, Point(this->button_clean.width*0.45, this->button_clean.height*0.7), FONT_HERSHEY_PLAIN, 1, Scalar(0, 0, 0));
//generate grids,square
this->grids = new Status*[row];
this->square = new Rect*[row];
for (int i = 0; i < row; i++) {
this->grids[i] = new Status[col];
this->square[i] = new Rect[col];
for (int j = 0; j < col; j++) {
this->grids[i][j] = Free;
this->square[i][j] = Rect(30 * j, 30 + 30 * i, 30, 30);
rectangle(this->image, this->square[i][j], Scalar(255, 0, 0), 1);
//cout << i << " ," << j << " is: " << grids[i][j] << "\n";
}
}
}
void GridMap::ShowGrid()
{
this->winName = "The Map";
namedWindow(this->winName);
setMouseCallback(this->winName, callBackFunc, this);
imshow(this->winName, this->image);
waitKey();
}
void GridMap::cleanGrid()
{
Rect cleanSquare(0, 30, this->image.cols, 30 * this->row);
this->image(cleanSquare) = Vec3b(255, 255, 255);
this->startStatus = 0;
this->goalStatus = 0;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
this->grids[i][j] = Free;
rectangle(this->image, this->square[i][j], Scalar(255, 0, 0), 1);
}
}
}
void GridMap::generatePath() {
cout << "Path can not be generated in GridMap program!\n";
//just do nothing
}
void GridMap::callBackFunc(int event, int x, int y)
{
if (event == EVENT_LBUTTONDOWN) //set obstacle, set free
{
if (this->button.contains(Point(x, y)))
{
cout << "Started!" << endl;
generatePath();
rectangle(this->image, this->button, Scalar(0, 0, 255), 2);
}
if (this->button_clean.contains(Point(x, y)))
{
cleanGrid();
cout << "Cleaned!" << endl;
rectangle(this->image, this->button_clean, Scalar(0, 0, 255), 2);
}
for (int i = 0; i < this->row; i++) {
for (int j = 0; j < this->col; j++) {
if (this->square[i][j].contains(Point(x, y)))
{
if (this->grids[i][j] == Free) {
this->image(this->square[i][j]) = Vec3b(100, 100, 100);
this->grids[i][j] = Obstacle;
cout << "The grid " << i + 1 << "," << j + 1 << " is Obstacle!\n";
}
else if (this->grids[i][j] == Obstacle) {
this->image(this->square[i][j]) = Vec3b(255, 255, 255);
rectangle(this->image, this->square[i][j], Scalar(255, 0, 0), 1);
this->grids[i][j] = Free;
cout << "Free the grid " << i + 1 << "," << j + 1 << " !\n";
}
else if (this->grids[i][j] == Start) {
this->image(this->square[i][j]) = Vec3b(100, 100, 100);
this->grids[i][j] = Obstacle;
this->startStatus = 0;
cout << "The start " << i + 1 << "," << j + 1 << " changed to Obstacle!\n";
}
else if (this->grids[i][j] == Goal) {
this->image(this->square[i][j]) = Vec3b(100, 100, 100);
this->grids[i][j] = Obstacle;
this->goalStatus = 0;
cout << "The goal " << i + 1 << "," << j + 1 << " changed to Obstacle!\n";
}
}
}
}
}
if (event == EVENT_LBUTTONDBLCLK) //set start and goal
{
if (this->startStatus == 0 || this->goalStatus == 0) {
for (int i = 0; i < this->row; i++) {
for (int j = 0; j < this->col; j++) {
if (this->square[i][j].contains(Point(x, y))) {
if (this->startStatus == 0) {
this->image(this->square[i][j]) = Vec3b(0, 255, 255);
this->grids[i][j] = Start;
cout << "The grid " << i + 1 << "," << j + 1 << " is the Start point!\n";
this->startNode = i * this->col + j;
//cout << "startNode:" << this->startNode << "\n";
this->startStatus = 1;
}
else if (this->goalStatus == 0) {
this->image(this->square[i][j]) = Vec3b(255, 255, 0);
this->grids[i][j] = Goal;
cout << "The grid " << i + 1 << "," << j + 1 << " is the Goal point!\n";
this->goalNode = i * this->col + j;
//cout << "goalNode:" << this->goalNode << "\n";
this->goalStatus = 1;
}
}
}
}
}
}
if (event == EVENT_LBUTTONUP) //make the button nicer
{
rectangle(this->image, this->button, Scalar(200, 200, 200), 2);
rectangle(this->image, this->button_clean, Scalar(200, 200, 200), 2);
}
imshow(this->winName, this->image);
waitKey(1);
}
void GridMap::callBackFunc(int event, int x, int y, int flags, void* userdata)
{
static_cast<GridMap*>(userdata)->callBackFunc(event, x, y);
}
GridMap::~GridMap()
{
for (int i = 0; i < this->row; i++) {
delete[] grids[i];
delete[] square[i];
}
delete[] grids;
delete[] square;
grids = nullptr;
square = nullptr;
}
|
Markdown
|
UTF-8
| 3,490 | 2.984375 | 3 |
[
"MIT"
] |
permissive
|
---
title: Fees
---
# {{$frontmatter.title}}
<TocHeader />
<TOC class="table-of-contents" :include-level="[2,3]" />
A requester will have three types of fees to consider.
1. Setup fees: transaction gas costs to maintain a requester record, its endorsements, etc.
2. Airnode execution fees: transaction gas costs when calling an Airnode.
3. API provider fees: subscriptions with an API provider.

## Setup Fees
Setup fees are encountered when setting up or changing a requester's record and endorsements. These are per call transaction gas costs and are relatively small. The funds will come from the wallet mnemonic that the requester supplied when [creating a requester record](become-a-requester.md#part-1-create-a-requester-record).
- [Creating or updating](become-a-requester.md#part-1-create-a-requester-record) a requester record.
- Adding or removing [endorsements](become-a-requester.md#part-2-endorse-client-contracts) of client contracts.
- Adding or removing [endorsements](become-a-requester.md#part-3-endorse-airnodes) of Airnodes.
## Airnode Execution Fees
When a client contract calls an Airnode there will be transaction gas costs that the requester usually covers. These funds will come from the designated wallet that was created for the requester when it endorsed the Airnode being called. There is a separate designated wallet for each Airnode that the requester has [endorsed](become-a-requester.md#part-3-endorse-airnodes).
The requester should keep in mind that a designated wallet is custodial, i.e., the Airnode keeps the private key, and the funds are trusted with the Airnode. Therefore, a requester should not fund a designated wallet with more then they can trust the Airnode with. This risk becomes negligible when:
- The Airnode is a first-party oracle, because first-party oracles are trustworthy.
- The Airnode is being used for a high value use-case, which already implies a high level of trust.
If the requester does not trust the Airnode at all, they can fund the designated just enough to cover a single fulfillment for each request. Therefore, this scheme both supports the traditional per-call payments, but also allows the protocol to leverage the trustworthiness of Airnodes to reduce unnecessary gas costs caused by microtransactions.
Although the designated wallet scheme allows the requester to cover the fulfillment gas costs, it is just as easy to have the API provider cover the gas costs. The only thing that needs to be done in this case is for the API provider to top up the designated wallet, instead of the requester. Furthermore, this scheme allows hybrid use-cases where the API provider covers the fulfillment gas costs for one requester (e.g., because they have made a special service agreement with them, while requires others to cover their own fulfillment gas costs.
## API Provider Fees
Some API providers charge a subscription fee to access their data. This is a typical practice and usually requires the requester to create an account on a website and then subscribe to a level of service offered. These types of services are usually billed monthly and can be based on an annual rate to save costs. The subscription (even if free) will most likely involve the use of a security scheme such as an api-key that must be used to access the data. See [Calling an Airnode](call-an-airnode.md) to learn more on how to pass the security credentials to an Airnode.
|
Java
|
UTF-8
| 13,234 | 2.078125 | 2 |
[] |
no_license
|
package com.jtl.arruler.old;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.opengl.GLES20;
import android.opengl.GLUtils;
import android.opengl.Matrix;
import com.google.ar.sceneform.math.Vector3;
import com.jtl.arruler.render.ShaderUtil;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import static android.opengl.Matrix.orthoM;
public class PictureRender {
private static final int FLOAT_SIZE = 4;//ๆฏไธชfloat 4ไธชๅญ่
private static final String TAG = PointRender.class.getSimpleName();
// Shader names.
private static final String VERTEX_SHADER_NAME = "shaders/picture.vert";
private static final String FRAGMENT_SHADER_NAME = "shaders/picture.frag";
private int program;
private int positionParam;
private int Color;
private float[] vpMatrix = new float[16];
private float[] mvpMatrix = new float[16];
private float[] projectionMatrix2D = new float[16];
private FloatBuffer quadVertices;
// private int vertexBufferId;
private int mMvpMatrixHandle;
private float[] originalPosition = new float[18];//18
private float[] texturePosition = {
0.0f,1.0f,
1.0f,1.0f,
1.0f,0.0f,
0.0f,1.0f,
1.0f,0.0f,
0.0f,0.0f,
};
final float[] colorCorrectionRgba = {1.0f, 0, 0, 1.0f};
private float T = 0.01f;
//็ปๅถๅพ็็ธๅ
ณ
private final int[] textures = new int[1];
private static final String A_TEXTURE_COORDINATES = "v_TexCoord";//็บน็
private static final String U_TEXTURE_UNIT = "u_TextureUnit";//็บน็
private int mMTextureUnit;
private int mTexCoordParam;
private FloatBuffer quadTextureVertices;
private int mColor;
private float mAspectRatio;
public void createOnGlThread(Context context){
int vertexShader = ShaderUtil.loadGLShader(TAG, context, GLES20.GL_VERTEX_SHADER, VERTEX_SHADER_NAME);
int fragmentShader = ShaderUtil.loadGLShader(TAG, context, GLES20.GL_FRAGMENT_SHADER, FRAGMENT_SHADER_NAME);
program = GLES20.glCreateProgram();
GLES20.glAttachShader(program, vertexShader);
GLES20.glAttachShader(program, fragmentShader);
GLES20.glLinkProgram(program);
GLES20.glUseProgram(program);
ShaderUtil.checkGLError(TAG, "Program creation");
//่ทๅ้กถ็น็่ฒๅจ็ไธคไธชๅๆฐ๏ผ็จไบๅพ็่ฒๅจ้ไผ ๅผ๏ผ็ฑปไผผๆ้๏ผ
positionParam = GLES20.glGetAttribLocation(program, "a_Position");
mMvpMatrixHandle = GLES20.glGetUniformLocation(program, "mvpMatrix");
mTexCoordParam = GLES20.glGetAttribLocation(program, "a_TexCoord");
mMTextureUnit = GLES20.glGetAttribLocation(program, "u_TextureUnit");
// Color = GLES20.glGetUniformLocation(program, "u_Color");
// //ๅๅปบ็บน็ๅฏน่ฑก
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glGenTextures(textures.length, textures, 0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures[0]);
GLES20.glUniform1i(mMTextureUnit, 0);
//่ฎพ็ฝฎ็ฏ็ปๆนๅS๏ผๆชๅ็บน็ๅๆ ๅฐ[1/2n,1-1/2n]ใๅฐๅฏผ่ดๆฐธ่ฟไธไผไธborder่ๅ
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_S, GLES20.GL_CLAMP_TO_EDGE);
//่ฎพ็ฝฎ็ฏ็ปๆนๅT๏ผๆชๅ็บน็ๅๆ ๅฐ[1/2n,1-1/2n]ใๅฐๅฏผ่ดๆฐธ่ฟไธไผไธborder่ๅ
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_WRAP_T, GLES20.GL_CLAMP_TO_EDGE);
//่ฎพ็ฝฎ็ผฉๅฐๆถไธบไธ็บฟๆง่ฟๆปค
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR_MIPMAP_LINEAR);
//่ฎพ็ฝฎๆพๅคงๆถไธบๅ็บฟๆง่ฟๆปค
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR);
//ๅๅงๅๅไฝๅๆข็ฉ้ต
Matrix.setIdentityM(mvpMatrix,0);
int width = Resources.getSystem().getDisplayMetrics().widthPixels;
int height = Resources.getSystem().getDisplayMetrics().heightPixels;
mAspectRatio = width > height ? (float)width / (float)height : (float)height / (float)width;
if (width > height) {
orthoM(projectionMatrix2D,0,-mAspectRatio, mAspectRatio,-1f,1f,-1f,1f);
}
else{
orthoM(projectionMatrix2D,0,-1f,1f,-mAspectRatio, mAspectRatio,-1f,1f);
}
}
public void onDraw() {
//draw
// Log.e("yyy");
GLES20.glUseProgram(program);
GLES20.glUniformMatrix4fv(mMvpMatrixHandle, 1, false, mvpMatrix, 0);
GLES20.glVertexAttribPointer(positionParam, 3, GLES20.GL_FLOAT, false, 0, quadVertices);
// GLES20.glUniform4fv(Color, 1, colorCorrectionRgba, 0);
GLES20.glVertexAttribPointer(mTexCoordParam, 2,
GLES20.GL_FLOAT, false, 0, quadTextureVertices);
GLES20.glEnableVertexAttribArray(mTexCoordParam);
GLES20.glEnableVertexAttribArray(positionParam);
// GLES20.glLineWidth(4);
GLES20.glDrawArrays(GLES20.GL_TRIANGLES,0,6); //(GLES20.GL_TRIANGLES, 0, 6);
}
public void upData(float[] p1, float[] p2,float[] viewMatrix,float[] projectionMatrix,String lineLength,@Config.DrawState int state) {
//่ฎก็ฎP็น็ๅๆ ๆไธค็งๆนๅผ๏ผ1.ๅ้็ๅๆณใ2.ๅ้็ๅ ๆณใ
if(state == Config.DrawState.DOING){
mColor = 0xFFFFA500;
}else{
mColor = 0xFEFEFEFE;
}
// Log.e("yyy","viewMatrix:\n"+
// viewMatrix[0]+" "+ viewMatrix[1] +" "+ viewMatrix[2]+" "+viewMatrix[3]+"\n"+
// viewMatrix[4]+" "+ viewMatrix[5] +" "+ viewMatrix[6]+" "+viewMatrix[7]+"\n"+
// viewMatrix[8]+" "+ viewMatrix[9] +" "+ viewMatrix[10]+" "+viewMatrix[11]+"\n"+
// viewMatrix[12]+" "+ viewMatrix[13] +" "+ viewMatrix[14]+" "+viewMatrix[15]+"\n"+
// "projectionMatrix:\n"+
// projectionMatrix[0]+" "+ projectionMatrix[1] +" "+ projectionMatrix[2]+" "+projectionMatrix[3]+"\n"+
// projectionMatrix[4]+" "+ projectionMatrix[5] +" "+ projectionMatrix[6]+" "+projectionMatrix[7]+"\n"+
// projectionMatrix[8]+" "+ projectionMatrix[9] +" "+ projectionMatrix[10]+" "+projectionMatrix[11]+"\n"+
// projectionMatrix[12]+" "+ projectionMatrix[13] +" "+ projectionMatrix[14]+" "+projectionMatrix[15]+"\n"
// );
//่ฝฌๆ็ธๆบ็ฉ้ต
// Matrix.invertM(viewMatrix,0,viewMatrix,0);
//ไธ็ๅๆ ็ณปไธ็็น
float[] point1 = new float[4];
point1[0] = p1[0];
point1[1] = p1[1];
point1[2] = p1[2];
point1[3] = 1;
float[] point2 = new float[4];
point2[0] = p2[0];
point2[1] = p2[1];
point2[2] = p2[2];
point2[3] = 1;
//1.ๅฐไธ็ๅๆ ็ณปไธ็็น่ฝฌๆขๅฐ็ธๆบๅๆ ็ณป๏ผview็ฉ้ตไนไปฅ็น
Matrix.multiplyMV(point1,0,viewMatrix,0,point1,0);
Matrix.multiplyMV(point2,0,viewMatrix,0,point2,0);
//2.ๆฑ่ฟๅชๅ้ข็ๅนณ้ขๆน็จ Z=0.1,ๆญคๆถ่ฎก็ฎ็ด็บฟๆน็จไธญ็tๅผ
float t1 = (float) (-0.1/point1[2]);
float t2 = (float) (-0.1/point2[2]);
//3.ๅจ่ฎก็ฎๅนณ้ขไธ็ไบค็นๅๆ
point1[0] = point1[0]*t1;
point1[1] = point1[1]*t1;
point1[2] = (float) -0.1;
point1[3] = 1;
point2[0] = point2[0]*t2;
point2[1] = point2[1]*t2;
point2[2] = (float) -0.1;
point2[3] = 1;
//ๆฑไธญๅฟ็น
float[] center = new float[3];
center[0] = (point2[0] + point1[0])/2;
center[1] = (point2[1] + point1[1])/2;
center[2] = (point2[2] + point1[2])/2;
//็ด็บฟๆนๅๅ้ๆฐ็ป่กจ็คบ
float[] vectorX = new float[2];
vectorX[0] = (point2[0] - point1[0]);
vectorX[1] = (point2[1] - point1[1]);
float[] vector2X = new float[2];
vector2X[0] = vectorX[0];
vector2X[1] = vectorX[1];
//่ทๅๅ็ดๅ้
float[] vector2Y = new float[4];
vector2Y = MathUtil.rotate90(vector2X);
// Log.e("yyy","็ด็บฟๅ็ดๅ้(ๆฒกๅฝไธๅ)"+vector2Y[0]+" "+vector2Y[1]+" "+"\n"+
// "ๆฃๆตไธคไธชๅ้ๆฏๅฆๅ็ด๏ผ"+(vector2X[0]*vector2Y[0] + vector2X[1]*vector2Y[1])+"\n");
// Log.e("yyy","===================");
vector2Y = MathUtil.normal2(vector2Y);
vector2X = MathUtil.normal2(vector2X);
// Log.e("yyy","็ด็บฟๅ็ดๅ้(ๅฝไธๅ)"+vector2Y[0]+" "+vector2Y[1]+" "+"\n"+
// "ๆฃๆตไธคไธชๅ้ๆฏๅฆๅ็ด๏ผ"+(vector2X[0]*vector2Y[0] + vector2X[1]*vector2Y[1])+"\n");
//yๅฝไธๅ
vector2Y[0] = (float) (vector2Y[0]/Math.sqrt(vector2Y[0]*vector2Y[0]+vector2Y[1]*vector2Y[1]));
vector2Y[1] = (float) (vector2Y[1]/Math.sqrt(vector2Y[0]*vector2Y[0]+vector2Y[1]*vector2Y[1]));
//่ฎก็ฎdx ,dy
final float DX = 0.01f;
final float DY = 0.005f;
float dxx = DX/2*vector2X[0];
float dxy = DX/2*vector2X[1];
float dyx = DY/2*vector2Y[0];
float dyy = DY/2*vector2Y[1];
originalPosition[0] = center[0]-dxx-dyx; originalPosition[1] = center[1]-dxy-dyy; originalPosition[2] = center[2];//p1
originalPosition[3] = center[0]+dxx-dyx;originalPosition[4] = center[1]+dxy-dyy;originalPosition[5] = center[2];//p2
originalPosition[6] = center[0]+dxx+dyx;originalPosition[7] = center[1]+dxy+dyy;originalPosition[8] = center[2];//p3
originalPosition[9] = center[0]-dxx-dyx;originalPosition[10] = center[1]-dxy-dyy;originalPosition[11] = center[2];
originalPosition[12] = center[0]+dxx+dyx;originalPosition[13] = center[1]+dxy+dyy;originalPosition[14] = center[2];
originalPosition[15] = center[0]-dxx+dyx;originalPosition[16] = center[1]-dxy+dyy;originalPosition[17] = center[2];//p4
//่ฎก็ฎ่ดดๅพๅๆ
if(originalPosition[6]>originalPosition[15]){
texturePosition[0] = 0.0f;texturePosition[1] = 1.0f;//p1
texturePosition[2] = 1.0f;texturePosition[3] = 1.0f;//p2
texturePosition[4] = 1.0f;texturePosition[5] = 0.0f;//p3
texturePosition[6] = 0.0f;texturePosition[7] = 1.0f;//p1
texturePosition[8] = 1.0f;texturePosition[9] = 0.0f;//p3
texturePosition[10] = 0.0f;texturePosition[11] = 0.0f;//p4
}else{
texturePosition[0] = 1.0f;texturePosition[1] = 0.0f;//p3
texturePosition[2] = 0.0f;texturePosition[3] = 0.0f;//p4
texturePosition[4] = 0.0f;texturePosition[5] = 1.0f;//p1
texturePosition[6] = 1.0f;texturePosition[7] = 0.0f;//p3
texturePosition[8] = 0.0f;texturePosition[9] = 1.0f;//p1
texturePosition[10] = 1.0f;texturePosition[11] = 1.0f;//p2
}
// texturePosition = {
// 0.0f,1.0f,
// 1.0f,1.0f,
// 1.0f,0.0f,
// 0.0f,1.0f,
// 1.0f,0.0f,
// 0.0f,0.0f,
// };
mvpMatrix = projectionMatrix;
float[] danwei = new float[3];
danwei[0] = originalPosition[6]-originalPosition[15];
danwei[1] = originalPosition[7]-originalPosition[16];
danwei[2] = originalPosition[8]-originalPosition[17];
danwei[0] = (float) (danwei[0]/Math.sqrt(danwei[0]*danwei[0]+danwei[1]*danwei[1]));
danwei[1] = (float) (danwei[1]/Math.sqrt(danwei[0]*danwei[0]+danwei[1]*danwei[1]));
//ๅๆ ็น็็ผๅฒๆต
ByteBuffer bbVertices = ByteBuffer.allocateDirect(originalPosition.length * FLOAT_SIZE);
bbVertices.order(ByteOrder.nativeOrder());
quadVertices = bbVertices.asFloatBuffer();
quadVertices.put(originalPosition);
quadVertices.position(0);
//็ปๅถๅพ็
Bitmap bitmap = Utils.getNewBitMap(mColor,Utils.dip2px(20),lineLength);
GLES20.glActiveTexture(GLES20.GL_TEXTURE0);
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textures[0]);
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);
GLES20.glGenerateMipmap(GLES20.GL_TEXTURE_2D);
bitmap.recycle();
//่ดดๅพๅๆ ็็ผๅฒๆต
ByteBuffer vertexBuffer = ByteBuffer.allocateDirect(texturePosition.length * FLOAT_SIZE);
vertexBuffer.order(ByteOrder.nativeOrder());
quadTextureVertices = vertexBuffer.asFloatBuffer();
quadTextureVertices.put(texturePosition);
quadTextureVertices.position(0);
}
/**
* ๆๆๅพๅ็ฐๅฎ็่ดดๅพไผไธ็ดๆไธใ
* ่ฎก็ฎ่ดดๅพ็ๆ่ฝฌ็ฉ้ตไธญ็Vxๅๆ
* @param vz
* @return
*/
private float[] calculateVx(float[] vz) {
float [] vx = new float[3];
float [] vy1 = new float[3];
vy1[0] = 0;
vy1[1] = 1;
vy1[2] = 0;
Vector3 vectorVY1 = new Vector3(vy1[0],vy1[1],vy1[2]);
Vector3 vectorVZ = new Vector3(vz[0],vz[1],vz[2]);
Vector3 vectorx = Vector3.cross(vectorVY1,vectorVZ).normalized();
vx[0] = vectorx.x;
vx[1] = vectorx.y;
vx[2] = vectorx.z;
return vx;
}
}
|
C#
|
UTF-8
| 8,006 | 2.84375 | 3 |
[] |
no_license
|
๏ปฟusing System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace EXER
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private int _D;
private double _OffSet = 0;
private double n = 0;
private double r = 0;
private bool rot = true;
private double speed = 51;
private int ghost = 15;
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text.Equals("") || textBox2.Text.Equals("") ||
Int32.Parse(textBox1.Text) < 3 ||
Int32.Parse(textBox1.Text) > 180 ||
Int32.Parse(textBox2.Text) <= 0 ||
( (2 * Double.Parse(textBox2.Text) * Math.Sin(Math.PI / Double.Parse(textBox1.Text)))
* Double.Parse(textBox1.Text)) > 170)
{
MessageBox.Show("ะั ะฒะฒะตะปะธ ััะพ-ัะพ ะฝะตะฟัะฒะธะปัะฝะพ, ะปะธะฑะพ ะฟะฐัะฐะผะตััั ัะปะธัะบะพะผ ะฑะพะปััะธะต");
textBox1.Clear();
textBox2.Clear();
label4.Text = "";
}
else
{
timer1.Enabled = false;
n = Double.Parse(textBox1.Text);
r = Double.Parse(textBox2.Text);
double side = 2 * r * Math.Sin(Math.PI / n);
double P = side * n;
_D = (int)side*10;
Graphics g = pictureBox1.CreateGraphics();
g.Clear(Color.Black);
label4.Text = P.ToString();
List<Point> p = new List<Point>();
_D = (int)(r * 10);
for (int i = 0; i < 360; i += 180 / (int)n * 2) //i ะณัะฐะดััั ะผะตะถะดั ััะพัะพะฝะฐะผะธ
{
var kr = _D / 2;
double rad = (double)i / 180.0 * Math.PI;
int x = (int)(kr * Math.Cos(rad + _OffSet));
int y = (int)(kr * Math.Sin(rad + _OffSet));
p.Add(new Point(x + kr, y + kr));
}
g.DrawEllipse(Pens.Red, new Rectangle(new Point(), new Size(_D, _D)));
g.DrawPolygon(new Pen(Color.FromArgb(255,
255,
255,
255)),
p.ToArray());
if (move == true)
{
rotate(r, n, _OffSet);
timer1.Enabled = true;
}
else
{
timer1.Enabled = false;
}
}
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if(!char.IsControl(e.KeyChar) &&
!char.IsDigit(e.KeyChar) &&
e.KeyChar!='.')
{
e.Handled = true;
}
if((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.')>-1))
{
e.Handled = true;
}
}
private void textBox2_KeyPress(object sender, KeyPressEventArgs e)
{
if (!char.IsControl(e.KeyChar) &&
!char.IsDigit(e.KeyChar) &&
e.KeyChar != '.')
{
e.Handled = true;
}
if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))
{
e.Handled = true;
}
}
private void rotate(double r, double n, double _OffSet)
{
Graphics g = pictureBox1.CreateGraphics();
g.Clear(Color.Black);
Random rand = new Random();
if (rot)
{
for (int j = 1; j < ghost; j++)
{
_OffSet -= 0.05 / speed * 40;
List<Point> p = new List<Point>();
_D = (int)(r * 10);
for (int i = 0; i < 360; i += 180 / (int)n * 2) //i ะณัะฐะดััั ะผะตะถะดั ััะพัะพะฝะฐะผะธ
{
var kr = _D / 2;
double rad = (double)i / 180.0 * Math.PI;
int x = (int)(kr * Math.Cos(rad + _OffSet));
int y = (int)(kr * Math.Sin(rad + _OffSet));
p.Add(new Point(x + kr, y + kr));
}
g.DrawEllipse(Pens.Red, new Rectangle(new Point(), new Size(_D, _D)));
g.DrawPolygon(new Pen(Color.FromArgb(255 / ((j/2)+1),
255,
255,
255)),
p.ToArray());
}
}
else
{
for (int j = 1; j < ghost; j++)
{
_OffSet += 0.05 / speed * 40;
List<Point> p = new List<Point>();
_D = (int)(r * 10);
for (int i = 0; i < 360; i += 180 / (int)n * 2) //i ะณัะฐะดััั ะผะตะถะดั ััะพัะพะฝะฐะผะธ
{
var kr = _D / 2;
double rad = (double)i / 180.0 * Math.PI;
int x = (int)(kr * Math.Cos(rad + _OffSet));
int y = (int)(kr * Math.Sin(rad + _OffSet));
p.Add(new Point(x + kr, y + kr));
}
g.DrawEllipse(Pens.Red, new Rectangle(new Point(), new Size(_D, _D)));
g.DrawPolygon(new Pen(Color.FromArgb(255 / ((j/2)+1),
255,
255,
255)),
p.ToArray());
}
}
}
private void timer1_Tick(object sender, EventArgs e)
{
if (move == true)
{
if (rot == true)
{
_OffSet += Math.PI / speed;
rotate(r, n, _OffSet);
}
else
{
_OffSet -= Math.PI / speed;
rotate(r, n, _OffSet);
}
}
}
private void button2_Click(object sender, EventArgs e)
{
rot = !rot;
}
private void button3_Click(object sender, EventArgs e)
{
if (speed == 1)
{
MessageBox.Show("ะญัะพ ะผะฐะบัะธะผะฐะปัะฝะฐั ัะบะพัะพััั, ะตั ััะพะธะปะพ ะฑั ะฟะพะฝะธะทะธัั");
}
else
{
if (speed == 51)
ghost = 15;
ghost--;
speed -= 10;
}
}
private void button4_Click(object sender, EventArgs e)
{
if (speed > 100)
{
MessageBox.Show("ะกะบะพัะพััั ะฟัะฐะบัะธัะตัะบะธ = 0, ะฟะพะฒััััะต ะตั");
}
else
{
if (ghost < 20)
ghost++;
speed += 10;
}
}
private bool move = false;
private void button5_Click(object sender, EventArgs e)
{
if (move == false)
button5.Text = "Stop";
else
button5.Text = "Start";
move = !move;
}
}
}
|
C
|
UTF-8
| 321 | 3.265625 | 3 |
[
"MIT"
] |
permissive
|
#include <stdio.h>
int main()
{
int a=5;
int *p;
p=&a;
printf("value of p = Address of a = %p\n",p);
printf("value of p = %p\n",++p);
printf("value of p = %p\n",p++);
printf("value of p = %p\n",p);
printf("value of p = %p\n",--p);
printf("value of p = %p\n",p--);
printf("value of p = %p\n",p);
return 0;
}
|
Python
|
UTF-8
| 1,142 | 4.46875 | 4 |
[] |
no_license
|
# A Better (than Naive) Solution to find all divisiors
import math
# method to print the divisors
def printDivisors(n):
# Note that this loop runs till square root
i = 1
calc = 0
while i <= math.sqrt(n):
if (n % i == 0):
# If divisors are equal, print only one
if (n / i == i) or (n / i == n):
calc = calc + i
else:
calc = calc + i + (n / i)
i = i + 1
return n == calc
# Driver method
print "The divisors of 100 are: "
print printDivisors(100)
import math
class Solution(object):
def checkPerfectNumber(self, num):
# Note that this loop runs till square root
if num <= 1:
return False
i = 1
calc = 0
while i <= math.sqrt(num):
if (num % i == 0):
# If divisors are equal, print only one
if (num / i == i) or (num / i == num):
calc = calc + i
else:
calc = calc + i + (num / i)
i = i + 1
return num == calc
a = Solution()
print a.checkPerfectNumber(-6)
|
Markdown
|
UTF-8
| 14,163 | 2.640625 | 3 |
[
"MIT",
"Apache-2.0"
] |
permissive
|
# Training, Classifying (Haar Cascades), and Tracking
Training our own Haar Cascade in OpenCV with Python. A cascade classifier has multiple stages of filtration. Using a sliding window approach, the image region within the window goes through the cascade. Can easily test accuracy of cascade with `classifier.py` script, which takes single images, directory of images, videos, and camera inputs. However, we want to also track our ROI (region of interest). This is because detection (through cascades, etc) is in general, more consuming and computationally taxing. Tracking algorithms are generally considered less taxing, because you know a lot about the apperance of the object in the ROI already. Thus, in the next frame, you use the information from the previous frame to predict and localize where the object is in the frames after.
There are many different types of tracking algorithms that are available through `opencv_contrib/tracking`, such as KCF, MOSSE, TLD, CSRT, etc. Here's a [good video](https://www.youtube.com/watch?v=61QjSz-oLr8) that demonstrates some of these tracking algorithms. Depending on your use case, the one you choose will differ.
## Jump to Section
* [Environment Setup](#environment-setup)
* [Image Scraping](#image-scraping)
* [Postive & Negative Image Sets](#positive-&-negative-image-sets)
* [Positive Samples Image Augmentation](#positive-samples-image-augmentation)
* [CSV Bounding Box Coordinates](#csv-bounding-box-coordinates)
* [Training](#training)
* [Testing Cascade](#testing-cascade)
* [Video Conversions](#video-conversions)
* [Contributing](#contributing)
* [Acknowledgements](#acknowledgements)
* [References](#references)
## Environment Setup
* Ubuntu 18.04; 20.04
* OpenCV 3.x.x (for running cascade training functions; built from source)
* OpenCV 4.4.0 (for running tracking algorithms)
* OpenCV Contrib (branch parallel with OpenCV 4.4.0)
As a clarification, the listed Ubuntu variants are for quick easy installs, depending on whether you're using `apt` or `pip`. To specifically get the OpenCV version you want, you will need to build from source (especially when you want to downgrade packages). I mainly used a Python virtual environment `venv` for package management. You can build and install OpenCV from source in the virtual environment (especially if you want a specific development branch or full control of compile options), or you can use `pip` locally in the `venv`. Packages included are shown in the `requirements.txt` file for reproducing the specific environment.
The project directory tree will look similar to the following below, and might change depending on the arguments passed to the scripts.
<blockquote>
```
.
โโโ classifier.py
โโโ bin
โย ย โโโ createsamples.pl
โโโ negative_images
โย ย โโโ *.jpg / *.png
โโโ positive_images
โย ย โโโ *.jpg / *.png
โโโ negatives.txt
โโโ positives.txt
โโโ requirements.txt
โโโ samples
โย ย โโโ *.vec
โโโ stage_outputs
โย ย โโโ cascade.xml
โย ย โโโ params.xml
โย ย โโโ stage*.xml
โโโ tools
โย ย โโโ bbox_from_vid.py
โย ย โโโ mergevec.py
โโโ venv
```
</blockquote>
## Image Scraping
Go ahead and web scrape relevant negative images for training. Once you have a good amount, filter extensions that aren't `*.jpg` or `*.png` such as `*.gif`. Afterwards, we'll convert all the `*.png` images to `*jpg` using the following command:
```
mogrify -format jpg *.png
```
Then we can delete these `*.png` images. Let's also rename all the images within the directoy to be `img.jpg`
```
ls | cat -n | while read n f; do mv "$f" "img$n.jpg"; done
```
To check if all files within our directory are valid `*.jpg` files:
```
find -name '*.jpg' -exec identify -format "%f" {} \; 1>pass.txt 2>errors.txt
```
## Positive & Negative Image Sets
Positive images correspond to images with detected objects. Images were cropped to 150 x 150 px training set. Negative images are images that are visually close to positive images, but *must not have* any positive image sets within.
<blockquote>
```
/images
img1.png
img2.png
positives.txt
```
</blockquote>
To generate your `*.txt` file, run the following command, make sure to change image extension to whatever file type you're using.
```
find ./positive_images -iname "*.png" > positives.txt
```
As a quote from OpenCV docs:
<blockquote>
Negative samples are taken from arbitrary images. These images must not contain detected objects. [...] Described images may be of different sizes. But each image should be (but not nessesarily) larger then a training window size, because these images are used to subsample negative image to the training size.
</blockquote>
## Positive Samples Image Augmentation
We need to create a whole bunch of image samples, and we'll be using `OpenCV 3.x.x` to augment these images. [These tools / functionalities were disabled during legacy C API](https://github.com/opencv/opencv/issues/13231#issuecomment-440577461), so we'll need to first be on a downgraded version of OpenCV, and once we have our trained cascade model, we can upgrade back to `4.x.x`. As mentioned in the link earlier, most modern approaches use deep learning approaches. However having used Cascades, they still their applications! Anyways, to create a training set as a collection of PNG images:
```
opencv_createsamples -img ~/opencv-cascade-tracker/positive_images/img1.png\
-bg ~/opencv-cascade-tracker/negatives.txt -info ~/opencv-cascade-tracker/annotations/annotations.lst\
-pngoutput -maxxangle 0.1 -maxyangle 0.1 -maxzangle 0.1
```
But we need a whole bunch of these. To augment a set of positive samples with negative samples, let's run the perl script that Naotoshi Seo wrote:
```
perl bin/createsamples.pl positives.txt negatives.txt samples 1500\
"opencv_createsamples -bgcolor 0 -bgthresh 0 -maxxangle 1.1\
-maxyangle 1.1 maxzangle 0.5 -maxidev 40 -w 50 -h 50"
```
Merge all `*.vec` files into a single `samples.vec` file:
```
python ./tools/mergevec.py -v samples/ -o samples.vec
```
**Errors**: If you run into the following error when running `mergevec.py`:
```
Traceback (most recent call last):
File "./tools/mergevec.py", line 170, in <module>
merge_vec_files(vec_directory, output_filename)
File "./tools/mergevec.py", line 133, in merge_vec_files
val = struct.unpack('<iihh', content[:12])
struct.error: unpack requires a string argument of length 12
```
You need to remove all `*.vec` files with size 0 in your `samples` directory. Simply `cd samples` into the directory and double check with `ls -l -S` for file sizes, and run:
```
find . -type f -empty -delete
```
Note: others have said that using artifical data vectors is not the best way to train a classifier. Personally, I have used this method and it worked fine for my use cases. However, you may approach this idea with a grain of salt and skip this step. If you want to hand select your ROI, you may use OpenCV's `opencv_annotation` function to select your regions of interest in a directory of images.
If you don't want to use artifical data, you will need to have your images and the coordinates of your region of interest. You can then use `opencv_createsamples` to merge all these images into a single vector `.vec` file and use this for training instead. You will need to supply an `info.dat` file that contains the image instance and the object coordinates in `(x, y, width, height)`. Your `info.dat` should look something like below, and can also be created using `opencv_annotation` or other customized data piplining methodologies you will need to implement.
<blockquote>
```
img/img1.jpg 1 140 100 45 45
img/img2.jpg 2 100 200 50 50 50 30 25 25
```
</blockquote>
## CSV Bounding Box Coordinates
In `tools`, there is a script called `bbox_from_vid.py` which can be used to generate the `(x_min, y_min, x_max, y_max)` coordinates, where `min` is from top left point of the bounding box and `max` is the bottom right point. It uses OpenCV's tracking algorithms to track the object selected.
```
usage: bbox_from_vid.py [-h] [-v] [-o] [-c] [-z]
Get bbox / ROI coords and training images from videos
optional arguments:
-h, --help show this help message and exit
-v, --vid specify video to be loaded
-o, --center select bounding box / ROI from center point
-c, --csv export CSV file with bbox coords
-z, --scale decrease video scale by scale factor
```
For example, if you wanted to save the bounding box coordinates of a tracked object:
```
./bbox_from_vid.py -v video_input.avi -c vid_bbox_coords.csv
```
## Training
There are two ways in OpenCV to train cascade classifier.
* `opencv_haartraining`
* `opencv_traincascade` - Newer version. Supports both Haar and LBP (Local Binary Patterns)
These were the parameters I used for my initial cascade training. Later, we can introduce a larger dataset. To begin training using `opencv_traincascade`:
```
opencv_traincascade -data stage_outputs -vec samples.vec -bg negatives.txt\
-numStages 20 -minHitRate 0.999 -maxFalseAlarmRate 0.5 -numPos 390\
-numNeg 600 -w 50 -h 50 -mode ALL -precalcValBufSize 8192\
-precalcIdxBufSize 8192
```
The first cascade worked relatively well. However, performance suffered in different lighting conditions. As a result, I trained a second cascade with a larger dataset that included different lighting conditions..
```
opencv_traincascade -data stage_outputs -vec samples.vec -bg negatives.txt\
-numStages 22 -minHitRate 0.993 -maxFalseAlarmRate 0.5 -numPos 1960\
-numNeg 1000 -w 50 -h 50 -mode ALL -precalcValBufSize 16384\
-precalcIdxBufSize 16384
```
Parameters for tuning `opencv_traincascade` are available in the [documentation](https://docs.opencv.org/4.4.0/dc/d88/tutorial_traincascade.html). `precalcValBufSize` and `precalcIdxBufSize` are buffer sizes. Currently set to 8192 Mb. If you have available memory, tune this parameter as training will be faster.
Something important to note is that
> vec-file has to contain `>= [numPos + (numStages - 1) * (1 - minHitRate) * numPos] + S`, where `S` is a count of samples from vec-file that can be recognized as background right away
`numPos` and `numNeg` are the number of positive and negative samples we use in training for every classifier stage. Therefore, `numPos` should be relatively less than our total number of positive samples, taking into consideration the number of stages we'll be running.
```
===== TRAINING 0-stage =====
<BEGIN
POS count : consumed 1960 : 1960
NEG count : acceptanceRatio 1000 : 1
Precalculation time: 106
+----+---------+---------+
| N | HR | FA |
+----+---------+---------+
| 1| 1| 1|
+----+---------+---------+
| 2| 1| 1|
+----+---------+---------+
| 3| 1| 1|
+----+---------+---------+
| 4| 1| 0.568|
+----+---------+---------+
| 5| 0.99949| 0.211|
+----+---------+---------+
END>
Training until now has taken 0 days 1 hours 3 minutes 47 seconds.
```
Each row of the training output for each stage represents a feature that's being trained. HR stands for Hit Ratio and FA stands for False Alarm. Note that if a training stage only has a few features (e.g. N = 1 ~ 3), that can suggest that the training data you used was not optimized.
**Note**: You can always pause / stop your cascade training and just build your final `cascade.xml` with the training stages that you've completed thus far. Just run your `opencv_traincascade` script and change the `-numStages` argument up to whichever completed stage you want, while *keeping every other parameter the same*. Your `cascade.xml` will be created.
```
opencv_traincascade -data stage_outputs -vec samples.vec -bg negatives.txt -numStages 22 -minHitRate 0.9993 -maxFalseAlarmRate 0.5 -numPos 1960 -numNeg 1000 -w 50 -h 50 -mode ALL -precalcValBufSize 16384 -precalcIdxBufSize 16384
```
## Testing Cascade
To test how well our cascade performs, run the `classifier.py` script.
```
usage: classifier.py [-h] [-s] [-c] [-i] [-d] [-v] [-w] [-f] [-o] [-z] [-t]
Cascade Classifier
optional arguments:
-h, --help show this help message and exit
-s, --save specify output name
-c, --cas specify specific trained cascade
-i, --img specify image to be classified
-d, --dir specify directory of images to be classified
-v, --vid specify video to be classified
-w, --cam enable camera access for classification
-f, --fps enable frames text (TODO)
-o, --circle enable circle detection
-z, --scale decrease video scale by scale factor
-t, --track select tracking algorithm [KCF, CSRT, MEDIANFLOW]
```
When testing a tracking algorithm, **pass the scale parameter**. For example, to run a video through the classifier and save the output:
```
./classifier.py -v ~/video_input.MOV -s ~/video_output -z 2 -t KCF
```
## Video Conversions
The `classifier.py` automatically saves output videos as `*.avi` (fourcc: XVID). If you need other video types, this can be done very easily with `ffmpeg`. There are way more command arguments, especially if you want to consider encoding and compression types. The following command below converts the `*.avi` to `*.mp4` and compresses it.
```
ffmpeg -i video_input.avi -vcodec libx264 -crf 30 video_output.mp4
```
## Contributing
Pull requests are welcomed.
## Acknowledgements
For releasing their tools and notes under MIT license.
* [Naotoshi Seo](https://github.com/sonots) - `createsamples.pl`
* [Blake Wulfe](https://github.com/wulfebw) - `mergevec.py`
* [Thorsten Ball](https://github.com/mrnugget)
## References
* [OpenCV - Cascade Classifier Training](https://docs.opencv.org/master/dc/d88/tutorial_traincascade.html)
* [OpenCV - Face Detection using Haar Cascades](https://docs.opencv.org/master/d2/d99/tutorial_js_face_detection.html)
* [Naotoshi Seo - Tutorial: OpenCV haartraining](http://note.sonots.com/SciSoftware/haartraining.html)
* [Thorsten Ball - Train your own OpenCV Haar Classifier](https://coding-robin.de/2013/07/22/train-your-own-opencv-haar-classifier.html)
|
Python
|
UTF-8
| 2,148 | 2.71875 | 3 |
[
"LicenseRef-scancode-public-domain"
] |
permissive
|
import unittest
import time
from testSetup import TestSetup
class TestCadastroMarca(TestSetup):
"""docstring for TestCadastroMarca"""
def setUp(self):
super(TestCadastroMarca,self).setUp()
compras_url_base = 'http://localhost:8000/toc_erp_web2py/estoque/'
controller_inserir = 'inserir_marca'
self.url_inserir_marca = compras_url_base + controller_inserir
self.nome = 'mais uma marca fajuta'
self.limpa_dados_tabela('marca')
self.limpa_dados_tabela('fabricante')
def test_inserir_campos_obrigatorios_vazios(self):
self.driver.get(self.url_inserir_marca)
self.submit_form()
time.sleep(0.5)
mensagem_de_erro = 'enter a value'
#so estou testanto o nome , pois a imagem eh opcional
#e a situacao sempre vem um valor padrao e a lista de fabricantes
#fica inativa quando n tem nenhum.
assert (self.driver.find_element_by_id('nome__error').text == mensagem_de_erro) == True
def test_inserir_campos_obrigatorios_preenchidos(self):
self.driver.get(self.url_inserir_marca)
self.driver.find_element_by_id('marca_nome').send_keys(self.nome)
self.submit_form()
time.sleep(0.5)
rows = self.db_test(self.db_test.marca.nome == self.nome.upper()).select()
assert (len(rows) > 0) == True
def test_validar_nome_marca_repetido(self):
fabricante_id = self.db_test.fabricante.insert(nome='fabricante para ' + self.nome,cpf_cnpj='02441251554')
self.db_test.commit()
self.db_test.marca.insert(nome=self.nome.upper(),fabricante_id=[fabricante_id],situacao='INATIVO')
self.db_test.commit()
time.sleep(0.5)
self.driver.get(self.url_inserir_marca)
self.driver.find_element_by_id('marca_nome').send_keys(self.nome)
mensagem_de_erro = 'value already in database or empty'
self.submit_form()
time.sleep(0.5)
assert (self.driver.find_element_by_id('nome__error').text == mensagem_de_erro)
@classmethod
def suite(cls):
suite = unittest.TestSuite()
suite.addTest(TestCadastroMarca('test_inserir_campos_obrigatorios_vazios'))
suite.addTest(TestCadastroMarca('test_inserir_campos_obrigatorios_preenchidos'))
suite.addTest(TestCadastroMarca('test_validar_nome_marca_repetido'))
return suite
|
Java
|
UTF-8
| 4,389 | 2.03125 | 2 |
[] |
no_license
|
package com.kedu.arias.product.service;
import java.util.List;
import javax.inject.Inject;
import org.springframework.stereotype.Service;
import com.kedu.arias.member.dto.MemberDto;
import com.kedu.arias.product.dao.ProductDao;
import com.kedu.arias.product.dto.Convin_code;
import com.kedu.arias.product.dto.NotsalesDto;
import com.kedu.arias.product.dto.ProductDto;
import com.kedu.arias.product.dto.ProductImgDto;
import com.kedu.arias.product.dto.Regulation_code;
import com.kedu.arias.product.dto.Safety_code;
import com.kedu.arias.product.dto.Space_code;
@Service
public class ProductServiceImpl implements ProductService {
@Inject
ProductDao pDao;
@Override
public boolean step1_insert(ProductDto pDto) throws Exception {
return pDao.step1_insert(pDto);
}
@Override
public int create_next_product_seq(String member_id) {
return pDao.create_next_product_seq(member_id);
}
@Override
public boolean step2_insert(ProductDto pDto) throws Exception {
return pDao.step2_insert(pDto);
}
@Override
public boolean notsales_insert(int product_seq,List<NotsalesDto> notsalesList) {
pDao.notsales_insert(product_seq, notsalesList);
return false;
}
@Override
public boolean update_product_options(int product_seq, String building_id, String accom_id, String bed_id,
String sguest_id) {
return pDao.update_product_options(product_seq, building_id, accom_id, bed_id, sguest_id);
}
@Override
public boolean insert_convin_options(int product_seq, List<String> convin_code_checkeds) {
if(convin_code_checkeds!=null && convin_code_checkeds.size()>0)
return pDao.insert_convin_options(product_seq, convin_code_checkeds);
else
return false;
}
@Override
public boolean insert_bath_options(int product_seq, List<String> bath_code_checkeds) {
if(bath_code_checkeds!=null && bath_code_checkeds.size()>0)
return pDao.insert_bath_options(product_seq, bath_code_checkeds);
else
return false;
}
@Override
public boolean insert_safety_options(int product_seq, List<String> safety_code_checkeds) {
if(safety_code_checkeds!=null && safety_code_checkeds.size()>0)
return pDao.insert_safety_options(product_seq, safety_code_checkeds);
else
return false;
}
@Override
public boolean insert_regulation_options(int product_seq, List<String> regulation_code_checkeds) {
if(regulation_code_checkeds!=null && regulation_code_checkeds.size()>0)
return pDao.insert_regulation_options(product_seq, regulation_code_checkeds);
else
return false;
}
@Override
public boolean insert_space_options(int product_seq, List<String> space_checkeds) {
if(space_checkeds!=null && space_checkeds.size()>0)
return pDao.insert_space_options(product_seq, space_checkeds);
else
return false;
}
@Override
public List<ProductDto> select_product_search(double lng, double lat, int number_of_people) throws Exception {
return pDao.select_product_search(lng, lat, number_of_people);
}
@Override
public boolean insert_product_images(int product_seq, List<String> pimgs) {
if(pimgs!=null && pimgs.size()>0)
return pDao.insert_product_images(product_seq, pimgs);
else
return false;
}
@Override
public ProductDto select_product_detail(int product_seq) throws Exception {
return pDao.select_product_detail(product_seq);
}
@Override
public List<Safety_code> product_safety(int product_seq) throws Exception {
return pDao.product_safety(product_seq);
}
@Override
public List<Convin_code> product_convin(int product_seq) throws Exception {
return pDao.product_convin(product_seq);
}
@Override
public List<Space_code> product_space(int product_seq) throws Exception {
return pDao.product_space(product_seq);
}
@Override
public List<Regulation_code> product_regulation(int product_seq) throws Exception {
return pDao.product_regulation(product_seq);
}
@Override
public MemberDto product_member(int product_seq) throws Exception {
return pDao.product_member(product_seq);
}
@Override
public List<ProductImgDto> selectAllproductPicture(int product_seq) {
return pDao.selectAllproductPicture(product_seq);
}
@Override
public List<ProductDto> select_product_list(String member_id) throws Exception {
return pDao.select_product_list(member_id);
}
@Override
public List<ProductDto> select_product_new() throws Exception {
return pDao.select_product_new();
}
}
|
Java
|
UTF-8
| 6,148 | 2.4375 | 2 |
[] |
no_license
|
package edu.eur.absa.data;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import edu.eur.absa.Framework;
import edu.eur.absa.model.Dataset;
import edu.eur.absa.model.Span;
import edu.eur.absa.model.Word;
import edu.eur.absa.nlp.NLPTask;
/**
* This class can read a single file or directory of files where each file is the output
* of the frog natural language processor (for Dutch)
* Frog is a binary that cannot easily be loaded in the framework, so that has to be run separately.
* @author Kim Schouten
*
*/
public class FrogReader implements IDataReader {
private String textualUnit = "document";
private String frogOutputFileExtension = ".out";
public static void main(String[] args) throws Exception{
// Dataset test = (new FrogReader()).read(new File("C:/workspace/alettesproject/data/items/"));
// (new DatasetJSONWriter()).write(test, new File(Framework.DATA_PATH+"Aardbeving-Media.json"));
// (new DatasetJSONWriter(true)).write(test, new File(Framework.DATA_PATH+"Aardbeving-Media.pretty.json"));
//
// Dataset check = (new DatasetJSONReader()).read(new File(Framework.DATA_PATH+"Aardbeving-Media.json"));
// (new DatasetJSONWriter(true)).write(check, new File(Framework.DATA_PATH+"Check.json"));
//
Dataset test = (new FrogReader()).read(new File("C:/workspace/alettesproject/data/politicalItems/"));
(new DatasetJSONWriter()).write(test, new File(Framework.DATA_PATH+"Aardbeving-Debatten.json"));
(new DatasetJSONWriter(true)).write(test, new File(Framework.DATA_PATH+"Aardbeving-Debatten.pretty.json"));
// Dataset check = (new DatasetJSONReader()).read(new File(Framework.DATA_PATH+"Aardbeving-Debatten.json"));
// (new DatasetJSONWriter(true)).write(check, new File(Framework.DATA_PATH+"Check.json"));
//
}
public FrogReader(){
}
public FrogReader(String frogOutputFileExtension){
this.frogOutputFileExtension = frogOutputFileExtension;
}
@Override
public Dataset read(File file) throws Exception {
Framework.log(file.getName());
Dataset dataset = new Dataset(file.getName(),textualUnit);
if (file.isDirectory()){
File[] files = file.listFiles(new FilenameFilter(){
@Override
public boolean accept(File dir, String name) {
return name.endsWith(frogOutputFileExtension);
}
});
for (File f : files){
Framework.log(f.getName());
readDocument(f, dataset);
}
} else {
Framework.log(file.getName());
readDocument(file, dataset);
}
Framework.log(""+dataset.getAnnotationDataTypes());
dataset.getAnnotationDataTypes().put("morphSegments", ArrayList.class);
dataset.getAnnotationDataTypes().put("posDetails", ArrayList.class);
dataset.getPerformedNLPTasks().add(NLPTask.TOKENIZATION);
dataset.getPerformedNLPTasks().add(NLPTask.SENTENCE_SPLITTING);
dataset.getPerformedNLPTasks().add(NLPTask.POS_TAGGING);
dataset.getPerformedNLPTasks().add(NLPTask.LEMMATIZATION);
dataset.getPerformedNLPTasks().add(NLPTask.NER);
dataset.getPerformedNLPTasks().add(NLPTask.CHUNKING);
return dataset;
}
public void readDocument(File file, Dataset dataset) throws IOException{
Span doc = null;
Span sentence = null;
BufferedReader in = new BufferedReader(new FileReader(file));
String line;
int offset = 0;
Word previousWord = null;
String sentenceText = "";
String documentText = "";
while ((line = in.readLine())!=null){
//Framework.log(line);
if (line.trim().length() > 0){
//if not a new line, this is another word for the current sentence
//start doc if we haven't done so already
if (doc == null){
// Framework.log("Starting new document");
doc = new Span(textualUnit, dataset);
}
String[] parts = line.split("\t");
if (parts[0].equalsIgnoreCase("1")){
//a new sentence starts
// Framework.log("Starting new sentence");
if (sentence!=null){
// sentence.getAnnotations().put("text", sentenceText.trim());
}
sentence = new Span("sentence", doc);
sentenceText = "";
}
//Framework.log("Creating Word object");
String text = parts[1].replaceAll("[_]", " ");
String lemma = parts[2].replaceAll("[_]", " ");
String morphSegmentsText = parts[3];
morphSegmentsText = morphSegmentsText.substring(1, morphSegmentsText.length()-1);
String[] morphSegments = morphSegmentsText.split("[\\]][_]?[\\[]");
String posText = parts[4];
String pos = posText.substring(0, posText.indexOf("("));
String posDetails[] = posText.substring(posText.indexOf("(")+1, posText.indexOf(")")).split(",");
double posConfidence = Double.parseDouble(parts[5]);
String ner = parts[6].split("[_]")[0];
String chunk = parts[7].split("[_]")[0];
Word word;
if (previousWord == null){
word = new Word(text, offset, doc, dataset);
} else {
word = new Word(text, offset, previousWord);
}
previousWord = word;
offset += text.length()+1;
sentenceText += text + " ";
documentText += text + " ";
// word.getAnnotations().put("lemma", lemma);
// word.getAnnotations().put("pos", pos);
// word.getAnnotations().put("posConfidence", posConfidence);
// word.getAnnotations().put("ner", ner);
// word.getAnnotations().put("chunk", chunk);
//
// ArrayList<String> morphs = new ArrayList<String>();
// for (String morph : morphSegments){
// morphs.add(morph);
// }
// word.getAnnotations().put("morphSegments", morphs);
//
// ArrayList<String> posDets = new ArrayList<String>();
// for (String posDet : posDetails){
// posDets.add(posDet);
// }
// word.getAnnotations().put("posDetails", posDets);
sentence.add(word);
}
}
if (doc!=null){
// sentence.getAnnotations().put("text", sentenceText.trim());
// doc.getAnnotations().put("text", documentText);
}
in.close();
}
}
|
Markdown
|
UTF-8
| 775 | 2.546875 | 3 |
[] |
no_license
|
# stickybeak
___Trigger actions on filesystem events___
[](https://travis-ci.org/justanotherdot/stickybeak)

## Install
Presently only linux is supported, but in due time other platforms will hopefully
be supported as well. You'll need the inotify library which you can get by
following the instructions [here](https://github.com/rvoicilas/inotify-tools/wiki).
Next, clone the repository and build with stack.
```bash
git clone https://www.github.com/justanotherdot/stickybeak.git
cd stickybeak && stack build
```
## Example Usage
```bash
stickybeak "src" "runTests.sh"
```
To watch some source directory and run a test suite on changes.
|
Markdown
|
UTF-8
| 969 | 2.9375 | 3 |
[] |
no_license
|
---
title: ๅพฎไฟกไน็ธๅ
ณๅไธๅผๅ
date: 2017-11-04 19:31:19
tags:
- ๅพฎไฟก
---
ๅพฎไฟกไธบๆไปฌๆไพไบๅพๅฅฝ็ๅนณๅฐ๏ผๅบไบๅพฎไฟกๅฏไปฅๅๅชไบๅไธๅผๅๅข๏ผ
ๅพฎไฟกๅ
ฌไผๅท็ๅ็ฑป๏ผ
2012ๅนด8ๆ๏ผๅพฎไฟกๅ
ฌไผๅนณๅฐไธ็บฟใ
2013ๅนด9ๆ๏ผๅไธบไบ่ฎข้
ๅทๅๆๅกๅทใ
2014ๅนด9ๆ๏ผๅขๅ ไบไผไธๅทใไผไธๅทไธป่ฆๆฏ็จๆฅ็ฎก็ๅๅทฅ็๏ผไพๅฆๆๅกไปไน็ใ
ไผไธๅท็ฎๅๅพๅฐใ
ไธ่ฌๆ่ฎข้
ๅทๅๆๅกๅท้ฝๅผๅฏ็ใ
่ฎข้
ๅทๅๆๅกๅท็ๅบๅซ๏ผ
1ใๆจ้้ขๆฌกไธไธๅใ
ๆๅกๅท๏ผๆฏๆ4ๆกใ้ฃๅคงๆฆๅฐฑๆฏไธๅจไธๆกใไฝๆฏไฝ ๅฏไปฅๅจไธๅคฉๆ4ๆก้ฝ็จๅฎใ
่ฎข้
ๅท๏ผๆฏๅคฉ1ๆกใ
2ใๅ่ฝๅทฎๅซใ
ๆๅกๅท๏ผๅ่ฝๅคใ
่ฎข้
ๅท๏ผๅ่ฝๆ้ใ
3ใๆถๆฏๆฅๅๅบๅซใ
ๆๅกๅท๏ผๆพ็คบๅจๅฏน่ฏๅ่กจ้ใ
่ฎข้
ๅท๏ผ่ขซๆถๅจไธไธชๆไปถๅคน้ใๆไปถๅคนๅๅญๅฐฑๅซ่ฎข้
ๅทใ
่ฟๆ ท่ขซๆๅ ๅฐๆไปถๅคน้๏ผ็จๆทๆถๅฐๅนฒๆฐๅฐ๏ผไนๅฏไปฅ้ไธญ้
่ฏปใ
|
C#
|
UTF-8
| 1,646 | 3.171875 | 3 |
[] |
no_license
|
๏ปฟusing System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
namespace LoadTest.Console
{
class Program
{
static void Main(string[] args)
{
string url = "http://localhost:63695";
int threadCount = 10;
if (args.Length == 2)
url = args[1];
if (args.Length >= 1)
threadCount = int.Parse(args[0]);
List<Thread> workers = new List<Thread>();
for(int i=0;i<threadCount;i++)
{
Thread pt = new Thread(new ParameterizedThreadStart(DoRequest));
workers.Add(pt);
}
System.Console.WriteLine("Execeuting requests");
foreach(var worker in workers)
worker.Start(url);
System.Console.WriteLine("done");
System.Console.ReadKey();
}
private static void DoRequest(object obj)
{
System.Diagnostics.Stopwatch sw = new Stopwatch();
sw.Start();
System.Console.WriteLine(string.Format("#{0} request", Thread.CurrentThread.ManagedThreadId));
var request = WebRequest.Create((string)obj);
var response = (HttpWebResponse)request.GetResponse();
var httpStatusCode = response.StatusCode;
sw.Stop();
System.Console.WriteLine(string.Format("#{0} returned {1}\t took {2}", Thread.CurrentThread.ManagedThreadId, httpStatusCode, sw.Elapsed));
}
}
}
|
C
|
UTF-8
| 397 | 3.078125 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
int main(int argc, char* argv[]){
errno = 0;
int fd;
fd = open("destination.txt", O_CREAT|O_RDONLY);
if (fd < 0){
printf("\n open() failed \n");
perror("open");
return -1;
} else {
printf("\n open() success \n");
}
close(fd);
return 0;
}
|
Java
|
ISO-8859-2
| 2,935 | 3.578125 | 4 |
[] |
no_license
|
package model.data_structures;
import java.util.Iterator;
/**
* Vrtice de un grafo.
* @author Camilo Martnez & Nicols Quintero
*/
public class Vertex<K extends Comparable<K>, V extends Comparable<V>, E extends Comparable<E>>
implements Comparable<Vertex<K, V, E>>
{
/**
* ID asociado al vrtice.
*/
private int id;
/**
* Informacin del vrtice.
*/
private String info;
/**
* Items contenidos dentro del vrtice.
*/
private HashTable<K, V> items = new HashTable<>( );
/**
* Item distintivo del vrtice.
*/
private E distinctiveItem;
/**
* Inicializa un vrtice con el ID dado por parmetro.
* @param id ID del vrtice. 0 <= id
*/
public Vertex( int id )
{
this.id = id;
this.distinctiveItem = null;
}
/**
* Inicializa un vrtice con el ID dado por parmetro y con el item distintivo
* dado.
* @param id ID del vrtice. 0 <= id
* @param distinctiveItem Item distintivo del vrtice. distinctiveItem != null
*/
public Vertex( int id, E distinctiveItem )
{
this.id = id;
this.distinctiveItem = distinctiveItem;
}
/**
* @return ID del vrtice.
*/
public int getId( )
{
return id;
}
/**
* Inserta el par llave-valor dados por parmetro en la tabla de items del
* vrtice.
* @param key Llave del par. key != null
* @param item Item del par. item != null
*/
public void insertItem( K key, V item )
{
items.put( key, item );
}
/**
* @param key Llave a obtener su valor.
* @return Valor asociado a la llave.
*/
public V getItem( K key )
{
return items.get( key );
}
/**
* @return Item distintivo del nodo.
*/
public E getDistinctiveItem( )
{
return distinctiveItem;
}
/**
* Cambia el item distintivo del nodo por uno dado por parmetro.
* @param distinctiveItem Nuevo item distintivo.
*/
public void setDistinctiveItem( E distinctiveItem )
{
this.distinctiveItem = distinctiveItem;
}
/**
* Asigna la informacin del vrtice al valor dado por parmetro.
* @param info Informacin del vrtice. info != null, != ""
*/
public void setInfo( String info )
{
this.info = info;
}
/**
* @return Informacin del vrtice.
*/
public String getInfo( )
{
return info;
}
/**
* @return Nmero de items guardados en el vrtice.
*/
public int numberOfItems( )
{
return items.getSize( );
}
/**
* @return Iterador sobre todos los items guardados en el vrtice.
*/
public Iterator<V> items( )
{
return new Iterator<V>( )
{
private Iterator<K> iter = items.keys( );
@Override
public boolean hasNext( )
{
return iter.hasNext( );
}
@Override
public V next( )
{
return items.get( iter.next( ) );
}
};
}
@Override
public int compareTo( Vertex<K, V, E> o )
{
if( this.numberOfItems( ) < o.numberOfItems( ) )
return -1;
else if( this.numberOfItems( ) > o.numberOfItems( ) )
return 1;
else
return 0;
}
}
|
Java
|
UTF-8
| 309 | 2.078125 | 2 |
[] |
no_license
|
package Enums;
/**
* Created by Victor on 02.01.2017.
*/
public enum TypeCode {
Empty,
Byte,
SByte,
Char,
UUID,
Int16,
Int32,
Int64,
UInt16,
UInt32,
UInt64,
Single,
String,
Object,
Double,
Decimal,
Boolean,
DateTime,
ByteArray,
}
|
Java
|
UTF-8
| 702 | 1.828125 | 2 |
[] |
no_license
|
package bean_promotion;
import java.util.List;
import bean_center.ct_res_response;
public class pm_res_promotion {
ct_res_response resp;
List<pm_res_listpromotion> list_pm;
public pm_res_promotion() {
super();
// TODO Auto-generated constructor stub
}
public pm_res_promotion(ct_res_response resp,
List<pm_res_listpromotion> list_pm) {
super();
this.resp = resp;
this.list_pm = list_pm;
}
public ct_res_response getResp() {
return resp;
}
public void setResp(ct_res_response resp) {
this.resp = resp;
}
public List<pm_res_listpromotion> getList_pm() {
return list_pm;
}
public void setList_pm(List<pm_res_listpromotion> list_pm) {
this.list_pm = list_pm;
}
}
|
Java
|
UTF-8
| 2,319 | 3.546875 | 4 |
[] |
no_license
|
package model;
import model.exceptions.*;
/**
* A coffee maker used to train baristas.
*
* Class invariant: cups remaining >= 0, time since last brew >= 0
*/
public class CoffeeMaker {
private int timeSinceLastBrew;
private int cupsRemaining;
//EFFECTS: sets time since last brew, cups remaining to 0
public CoffeeMaker(){
timeSinceLastBrew = 0;
cupsRemaining = 0;
}
//EFFECTS: sets cups remaining to full (20 cups) and time since last brew to 0,
// throws BeansAmountException if beans are not between 2.4 and 2.6 cups,
// throws WaterException if water <= 14.75
public void brew(double beans, double water) throws BeansAmountException, WaterException{
if (water <= 14.75)
throw new WaterException(water);
if (beans >= 2.4) {
if (beans <= 2.6) {
cupsRemaining = 20;
timeSinceLastBrew = 0;
} else {
throw new TooManyBeansException(beans);
}
} else {
throw new NotEnoughBeansException(beans);
}
}
//MODIFIES: this
//EFFECTS: subtracts one cup from cups remaining
// throws NoCupsRemainingException if cups remaining <= 0
// throws StaleCoffeeException if time since last brew >= 60
public void pourCoffee() throws StaleCoffeeException, NoCupsRemainingException {
if(!areCupsRemaining()){
throw new NoCupsRemainingException();
} else if (timeSinceLastBrew >= 60){
throw new StaleCoffeeException(timeSinceLastBrew);
} else {
cupsRemaining--;
}
}
//getters
public int getTimeSinceLastBrew(){
return timeSinceLastBrew; //stub
}
//EFFECTS: returns how many cups remaining in pot (a full pot is 20 cups)
public int getCupsRemaining(){
return cupsRemaining;
}
//EFFECTS: returns true if there are cups remaining
public boolean areCupsRemaining(){
return cupsRemaining > 0;
}
//REQUIRES: a non-negative integer
//EFFECTS: sets time since last brew
public void setTimeSinceLastBrew(int time){
this.timeSinceLastBrew = time;
}
}
|
Markdown
|
UTF-8
| 11,683 | 3.875 | 4 |
[] |
no_license
|
---
date: 2015-04-30T10:07:00+08:00
title: "SQLite3็ฑปๅ็ณป็ป"
---
SQLite3้ๅธธ[ไธไผไธๅ](https://www.sqlite.org/different.html)ใๅฎ็็ฑปๅ็ณป็ปไนไธๅไบๅคง้จๅ็ๆฐๆฎๅบ็ฎก็็ณป็ป(DBMS)ใ
้ๅธธ๏ผDBMSไฝฟ็จ้ๆ็ฑปๅ(static typing)๏ผๅณๆฐๆฎ่กจ็ๆฏไธๅไธญๅช่ฝๅญๆพๅไธ็ง็ฑปๅ็ๆฐๆฎ๏ผ่ฟไธช็ฑปๅๅจๅๅปบ่กจ็ๆถๅๅฐฑๅทฒ็ป็กฎๅฎใ่SQLite3ไฝฟ็จ็งฐไธบmanifest typing็็ฑปๅ็ณป็ป๏ผๅฎๅ
่ฎธๆฏไธๅไธญๅญๆพไธๅ็ฑปๅ็ๅ
็ด ๏ผๅฎ้
ไธๅพๅๅจๆ็ฑปๅใManifest typing็ๅ็กฎ่ฏๆณๆไธ็ฅ้ใๆ็
งๅญ้ขๆๆๅฏไปฅ็ฟป่ฏๆโๆพๅผ็ฑปๅโ๏ผๅฏๆฏ่ฟๅๆ ๆณไฝ็ฐๅฎๅจๆ็ฑปๅ็็น็นใ
ๆณจ๏ผๆ็ๆๆๆ่ก็งฐไธบโ่ฎฐๅฝโ๏ผๆๅ็งฐไธบโๅญๆฎตโใๆ่ฎคไธบ่ฟไบๅๅญๅนถไธๅฝข่ฑก๏ผๅฏน็่งฃๆฐๆฎ่กจๅธฎๅฉไธๅคงใ
้ฆๅ
๏ผๆฐๆฎ่กจ็ๆฏไธๅๅนถๆฒกๆไธฅๆ ผ็ๆฐๆฎ็ฑปๅ๏ผๅชๆๅ
ทไฝ็ๆฐๆฎๆ็ฑปๅใSQLite3็ๆฐๆฎ็ฑปๅๆ5็ง๏ผๅฆไธ้ข็ไพๅญๆ็คบใ
```
SELECT
TYPEOF(NULL),
TYPEOF(-9223372036854775808),
TYPEOF(1e-5),
TYPEOF('hello, world'),
TYPEOF(X'DEADBEEF');
--> null|integer|real|text|blob
```
่ฝ็ถๅ้ๆ็ฑปๅๆๅพๅคง็ไธๅ๏ผไฝๆฏๅฎ้
ไฝฟ็จ็ๆถๅ๏ผSQLite3ๅไฝฟ็จ้ๆ็ฑปๅ็DBMSๆฏๅ
ผๅฎน็ใ
```
CREATE TABLE BOOKS(
ID INTEGER PRIMARY KEY,
NAME VARCHAR(255),
PRICE REAL
);
INSERT INTO BOOKS(NAME, PRICE) VALUES
('The Art of Computer Programming', 259.99),
('Concrete Mathematics', 57.57);
```
ไฝ ็
งๆ ทๅฏไปฅๅจๅๅปบ่กจๆ ผ็ๆถๅๆๅฎๅไธชๅ็็ฑปๅ๏ผไธ่ฟๅฎไปฌๅชๆฏไธไธชๆ่ฎพ๏ผๅนถไธไผ่ขซSQLite3ไธฅๆ ผๆง่ก๏ผๆไธไบไพๅค๏ผ่งไธๆ๏ผใไบๅฎไธ๏ผSQLite3ไธญๆ นๆฌๆฒกๆ```VARCHAR(255)```่ฟไธชๆฐๆฎ็ฑปๅ๏ผไฝ ๅฏไปฅๆๅฎไปปๆๅ็งฐ็ๆฐๆฎ็ฑปๅใ่ฟๆ ทๅๅฎ้
ไธๆ้ซไบSQLite3ๅๅ
ถไปDBMS็ๅ
ผๅฎนๆงใ
<!--more-->
ๅจ่ฟไธชไพๅญ้๏ผๆฐๆฎ่กจๅไธชๅ็ๆไนๆ็กฎ๏ผๆฐๆฎ็ฑปๅไธ่ฌๆฅ่ฏดไน้ฝๆฏไธๆ ท็๏ผไธป้ฎไธๅฎๆฏๆดๆฐ๏ผไนฆ็ฑ็ๅ็งฐไธๅฎๆฏๅญ็ฌฆไธฒ่ไธไผๆฏๅฎๆฐๆ่
ๅซ็ไปไนไธ่ฅฟ๏ผ็ญ็ญใ
ไบๅฎไธ๏ผSQLite3็manifest typingไธญๆไธไธชไพๅคๆ
ๅต๏ผ้ฃๅฐฑๆฏ่ขซๅฃฐๆๆ```INTEGER PRIMARY KEY```็ๅๅช่ฝๅญๆพๆดๆฐๅผ๏ผ่ไธ่ฝๆฏๅ
ถไป็ๅผใ
ๅฏนไบๅ
ถไป็ๅ่่จ๏ผๅฆๆๆๅ
ฅ็ๆฐๆฎๆฒกๆ้ตไปๅฃฐๆ็็ฑปๅ๏ผ็ฑไบmanifest typing็็น็น๏ผSQLite3ๅ
่ฎธ่ฟๆ ท็ๆไฝ๏ผ่ไธไผๅไฝ ๆฅๅ้่ฏฏใไพๅฆ๏ผ
```
INSERT INTO BOOKS(NAME, PRICE) VALUES
(1984, '6.00');
```
่ฟๆ ท็ๆๅ
ฅๆไฝไนๆฏ่ขซๅ
่ฎธ็ใๅจ่ฟไธชไพๅญ้๏ผ่ขซๆๅ
ฅ็ๆฐๆฎๅฎ้
ไธๆฏๆๆไน็๏ผๆฌๆๆฏๆๅ
ฅ```('1984', 6.00)```๏ผใไฝๆฏ๏ผๅฎ้
ๆไฝๆฐๆฎ็ๆถๅ๏ผไผไธไผไบง็ๆๅค็ๆ
ๅต๏ผ
็็ไธ้ข่ฟไธชๆฅ่ฏข๏ผ
```
SELECT * FROM BOOKS WHERE PRICE < 100;
```
ๆฌๆๆฏ้ๅบไปทๆ ผๅฐไบ100็ไนฆ็ฑใๅฏๆฏ๏ผๅฏนไบ *1984* ่ฟๆฌไนฆ่่จ๏ผๅฎ็```PRICE```ๅๅญๆพ็ๅผๆฏๅญ็ฌฆไธฒ```'6.00'```่ไธๆฏไธไธชๆฐๅผ๏ผๅฎ้
ไธๅนถ้ๅฆๆญค๏ผ่งไธๆ๏ผใๅญ็ฌฆไธฒๅๆฐๅผๆฏ่พๅคงๅฐ๏ผๆไนๆฏ่พๅข๏ผ
ๅฏ่ฝ็ๅๆณๆ๏ผ
1. ๆๅบ้่ฏฏ๏ผๆ็ปๆฏ่พใ
2. ๆ```'6.00'```่ฝฌๆขไธบๆฐๅผ๏ผๅ100ๆฏ่พใ่ฟๆ ทๆ```'6.00' < 100```ใ
3. ๆ100่ฝฌๆขไธบๅญ็ฌฆไธฒ๏ผๅ```'6.00'```ๆฏ่พใๅญ็ฌฆไธฒ็ๆฏ่พ๏ผๅฐฑๆฏ้ไธชๅญ็ฌฆๆฏ่พๅคงๅฐ็ดๅฐๅๅบ็ปๆไธบๆญขใ่ฟๆ ทๆ```'6.00' > 100```ใ
ๅฏไปฅ็ๅพๅบๆฅ๏ผmanifest typingๅฏ่ฝไผๅธฆๆฅไธไบๅคๆ็ๆ
ๅตใไปฅไธ3ไธญๅๆณ๏ผๅนถๆฒกๆๅชไธ็งๆฏ็นๅซๆพ็ถ็๏ผ่ฟๆ ทไผ็ปไฝฟ็จ่
ๅธฆๆฅ้บป็ฆใไบๅฎไธ๏ผSQLite3็ๅๆณ**ๅนถไธๆฏไปฅไธ3็ง็ไปปไฝไธ็ง**ใๅฎ็่งๅๆฏ๏ผ
1. ๆฏ่พไธๅ็ฑปๅ็ๆถๅ๏ผ้ฆๅ
ๆNULL < (INTEGER ๆ REAL) < TEXT < BLOB
2. ๆฏ่พINTEGERๅREAL๏ผๆฏ่พๅฎ้
ๆฐๅผใ
3. ๆฏ่พไธคไธชTEXTๆ่
ไธคไธชBLOB็ๆถๅ๏ผไฝฟ็จๅ```memcmp```็ฑปไผผ็่งๅใ
ๆไปฅๅฎ้
ไธๆฏๆ นๆฎ็ฌฌ1ๆก่งๅๅฏไปฅ็กฎๅฎ```'6.00' > 100```ใ
ๅฆๆไธๆฏๅฟ
่ฆ๏ผๆ**ๅผบ็ๅปบ่ฎฎ**ไธ่ฆไพ่ตไธ่ฟฐ่งๅ๏ผๅ ไธบ่ฟไบ่งๅๆฏ่พๅคๆ๏ผๅฎนๆๆ้๏ผไนไธไพฟไบ็งปๆคใ
ๅฆๆๅไธไธชๅฎ้ช๏ผๅไผๅ็ฐๆฐ็โๆๅคโๆ
ๅต๏ผ
```
SELECT * FROM BOOKS WHERE PRICE < 100;
--> 2|Concrete Mathematics|57.57
--> 3|1984|6.0
```
ๆไปฌๅ็ฐไบๅฎไธ *1984* ่ขซ้ไบๅบๆฅใ่ฟๆ ท็็ปๆ๏ผ็ฌฆๅ็ด่งๅๆฅ่ฏข่
็ๆฌๆ๏ผไฝๅไธๆ่ฟ่ก็็ๆง็ๅๆๅไธไธๆ ทใ
ๅบ็ฐ่ฟ็ง็ปๆ็ๅๅ ๆฏ๏ผไธบไบๅๅฐๆๅค็็ปๆ๏ผ่ฟไธๆญฅๆ้ซSQLite3ๅๅ
ถไปDBMS็ๅ
ผๅฎนๆง๏ผๅ่
ๅๅผๅ
ฅไบtype affinity็ๆฆๅฟตใType affinity็ๅ็กฎ่ฏๆณๆไธ็ฅ้ใๆ็ไบบ่ฏๆ็ฑปๅไบฒๅๆง๏ผๆ็ไบบ่ฏๆ็ฑปๅ่ฟไผผใ่ฟไบ่ฏๆณ้ฝๆฏๅญ้ข็ฟป่ฏใๅฎ็ไฝ็จๆฏๆไพไธ็ง็ฑปๅ็ๅๅ๏ผไปฅไพฟSQLite3ๅจๆฐๅฝ็ๆถๅๅไธไบ้ๅผ็็ฑปๅ่ฝฌๆขใ
SQLite3็type affinityไนๆ5็ง๏ผ
1. INTEGERใๅฃฐๆ็็ฑปๅไธญๅซๆๅญ็ฌฆไธฒ```INT```็๏ผๅฝ็ปๅฐๅฎใ
2. TEXTใๅฃฐๆ็็ฑปๅไธญๅซๆๅญ็ฌฆไธฒ```CHAR```, ```CLOB```ๆ่
```TEXT```็๏ผๅฝ็ปๅฐๅฎใไพๅฆ๏ผ```VARCHAR(255)```ๅฐฑๅ
ทๆTEXT affinityใ
3. NONEใๅฃฐๆ็็ฑปๅๆฏ```BLOB```ๆ่
ๆฒกๆๅฃฐๆ็ฑปๅ็๏ผๅฝ็ปๅฐๅฎใ
4. REALใๅฃฐๆ็็ฑปๅไธญๅซๆๅญ็ฌฆไธฒ```REAL```, ```FLOA```ๆ่
```DOUB```็๏ผๅฝ็ปๅฐๅฎใ
5. NUMERICใไปฅไธๅ็งๆ
ๅฝขไนๅค็๏ผๅฝ็ปๅฐๅฎใไพๅฆ```DECIMAL```็type affinityๅฐฑๆฏNUMERICใ
ๆณจ๏ผๆไบๅ่ฏ๏ผไพๅฆINTEGERๅREAL๏ผๆขๆฏๆฐๆฎ็ฑปๅ็ๅ็งฐ๏ผๅๆฏtype affinity็ๅ็งฐใไฝๅฎไปฌ่กจ็คบไธๅ็ๆฆๅฟต๏ผไธๅบๆททๆทใ
ๆ นๆฎไปฅไธ่งๅ๏ผๆไปฌ็ฅ้๏ผ่กจไธญ็```NAME```ๅ```PRICE```ๅญๆฎตๅๅซๅ
ทๆTEXTๅREAL็type affinityใ่ฟๅฏนๆฐๆฎๅบๆไฝๆไปไนๅฝฑๅๅข๏ผ
ๆ้่ฆ็ๅฝฑๅๅฐฑๆฏ๏ผๅฝๆๅ
ฅๆฐๆฎ็ๆถๅ๏ผSQLite3ไผๅฐ่ฏๅ็ฑปๅ่ฝฌๆขใ่ฝฌๆข็่งๅๅๆ ทๅพๅคๆ๏ผ
1. NULLๅBLOB็ฑปๅ็ๆฐๆฎๆฐธ่ฟไธไผ่ขซ่ชๅจๅฐ่ฝฌๆขใ
2. ๅฆๆๅ็type affinityๆฏ๏ผ
1. NONE๏ผๅๅพ
ๆๅ
ฅ็ๆฐๆฎไธไผ่ขซ่ฝฌๆข็ฑปๅใ
2. TEXT๏ผๅๅพ
ๆๅ
ฅ็ๆฐๆฎไผ่ขซ่ฝฌๆขไธบTEXT็ฑปๅใ
3. INTEGERๆ่
NUMERIC๏ผๅๅพ
ๆๅ
ฅ็ๆฐๆฎไผ่ขซ่ฝฌๆขไธบINTEGERๆ่
REAL็ฑปๅ๏ผๅฆๆ็ธๅบ็่ฝฌๆขไธไผๅผ่ตท็ฒพๅบฆๆๅคฑ็่ฏใ
4. REAL๏ผๅๅพ
ๆๅ
ฅ็ๆฐๆฎไผ่ขซ่ฝฌๆขไธบREAL็ฑปๅ๏ผๅฆๆ็ธๅบ็่ฝฌๆขไธไผๅผ่ตท็ฒพๅบฆๆๅคฑ็่ฏใ
ๆ นๆฎ่ฟไบ่งๅ๏ผๆไปฌ็ฅ้๏ผๅจๆๅ
ฅ```(1984, '6.00')```็ๆถๅ๏ผไธคไธชๆฐๆฎๅผๅฐฑๅทฒ็ป่ขซ่ชๅจๅฐ่ฝฌๆขๆไธบไบ```'1984'```ๅ```6.0```ใๆไปฅ๏ผไนๅ็ๆฅ่ฏข่ช็ถๅฏไปฅ็ปๅบ็ฌฆๅ็ด่ง็็ปๆใ
่ฏ่ฏดๅๆฅ๏ผไธๅ็ไธๅ๏ผ้ฝๆฏๅ ไธบไธๆก้่ฏฏ็ๆๅ
ฅ่ฏญๅฅๅผ่ตท็๏ผๅฆๆไนๅๆๅฎๆญฃ็กฎๅฐๅๆ
```
INSERT INTO BOOKS(NAME, PRICE) VALUES
('1984', 6.00);
```
้ฃไนๅฐฑไธ้่ฆไพ้ type affinity่ฟไบๅคๆ็่งๅๆฅโไฟฎๆญฃโใ
็ถ่type affinity็่งๅ่ฟไธๆญขไบๆญคใๅฝๆฏ่พไธคไธชๆฐๆฎ็ๆถๅ๏ผ
1. ๅฆๆ่กจ่พพๅผๆฏ่ฟ็ฎ็ฌฆ```IN```ๅ```NOT IN```็ๅณๆไฝๆฐ๏ผ
1. ่กจ่พพๅผๆฏไธไธชๅ่กจ๏ผๅๅฎ็type affinityๆฏNONEใ
2. ่กจ่พพๅผๆฏไธไธชSELECT๏ผๅๅฎ็type affinityๅ็ปๆ้็type affinityไธๆ ทใ
2. ๅฆๆ่กจ่พพๅผๆฏๅ็ๅ็งฐ๏ผๅๅฎtype affinityๆฏ่ฟไธชๅ็type affinityใ
3. ๅฆๆ่กจ่พพๅผๅ
ทๆ```CAST(expr AS type)```็ๅฝขๅผ๏ผๅๅฎ็type affinityๅๆฐๆฎ็ฑปๅ```type```ๅฏนๅบ็type affinityไธๆ ทใ
4. ๅ
ถไปๆ
ๅต็่กจ่พพๅผ็type affinityๆฏNONEใ
่ฟๆ ท๏ผๅจๆฏ่พไนๅ๏ผไบๅ
่ฟๆๅฏ่ฝ่ฟ่ก้ๅผ็็ฑปๅ่ฝฌๆข๏ผ
1. ๅฆๆไธ่พน็type affinityๆฏINTEGER, REALๆ่
NUMERIC๏ผ่ๅฆไธ่พนๆฏTEXTๆ่
NONE๏ผๅๅฆไธ่พน่ขซ่ฝฌๆขไธบNUMERICใ
2. ๅฆๆไธ่พน็type affinityๆฏTEXT๏ผ่ๅฆไธ่พนๆฏNONE๏ผๅๅฆไธ่พน่ขซ่ฝฌๆขไธบTEXTใ
3. ๅ
ถไปๆ
ๅตไธไธๅ็ฑปๅ่ฝฌๆขใ
ไธ้ขๆฏๆฅ่ชSQLite3ๅฎๆนๆๆกฃ็ไธไธช็ปผๅ็ไพๅญใ
```
CREATE TABLE t1(
a TEXT, -- text affinity
b NUMERIC, -- numeric affinity
c BLOB, -- no affinity
d -- no affinity
);
-- Values will be stored as TEXT, INTEGER, TEXT, and INTEGER respectively
INSERT INTO t1 VALUES('500', '500', '500', 500);
SELECT typeof(a), typeof(b), typeof(c), typeof(d) FROM t1;
text|integer|text|integer
-- Because column "a" has text affinity, numeric values on the
-- right-hand side of the comparisons are converted to text before
-- the comparison occurs.
SELECT a < 40, a < 60, a < 600 FROM t1;
0|1|1
-- Text affinity is applied to the right-hand operands but since
-- they are already TEXT this is a no-op; no conversions occur.
SELECT a < '40', a < '60', a < '600' FROM t1;
0|1|1
-- Column "b" has numeric affinity and so numeric affinity is applied
-- to the operands on the right. Since the operands are already numeric,
-- the application of affinity is a no-op; no conversions occur. All
-- values are compared numerically.
SELECT b < 40, b < 60, b < 600 FROM t1;
0|0|1
-- Numeric affinity is applied to operands on the right, converting them
-- from text to integers. Then a numeric comparison occurs.
SELECT b < '40', b < '60', b < '600' FROM t1;
0|0|1
-- No affinity conversions occur. Right-hand side values all have
-- storage class INTEGER which are always less than the TEXT values
-- on the left.
SELECT c < 40, c < 60, c < 600 FROM t1;
0|0|0
-- No affinity conversions occur. Values are compared as TEXT.
SELECT c < '40', c < '60', c < '600' FROM t1;
0|1|1
-- No affinity conversions occur. Right-hand side values all have
-- storage class INTEGER which compare numerically with the INTEGER
-- values on the left.
SELECT d < 40, d < 60, d < 600 FROM t1;
0|0|1
-- No affinity conversions occur. INTEGER values on the left are
-- always less than TEXT values on the right.
SELECT d < '40', d < '60', d < '600' FROM t1;
1|1|1
```
ๅฏไปฅ่ฏดๅจSQLite3ไธญ๏ผtype affinityๆฏไธไธช็ธๅฝๅคๆ็ๆฆๅฟต๏ผ็จๅฎๆฅๅบๆๆซ่่ฏ้ข๏ผๆๆๆฏๅๅฅฝไนๆฒกๆไบใๅฎ้
ไธ๏ผSQLite3ไนๆไปฅ่ฎพ่ฎก่ฟๆ ทไธไธช็ธๅฝๅคๆ็ๆบๅถ๏ผๅ่กทๆฏไธบไบๅฐฝ้้ฟๅ
ๆๅคๆ
ๅต๏ผๆ้ซๅฎๅๅ
ถไปDBMS็ๅ
ผๅฎนๆงใๆไปฅ๏ผๆ**ๅผบ็ๅปบ่ฎฎ**็จๆทไธ่ฆไพ่ต่ฟไบๅ
ทไฝ็็นๆงใ่ฟๅฐฑๅฅฝๅๆฏไฝๅฎ
ๆฅผไธ๏ผ็ชๆทๅค่พนไฟฎ็็ดงๆฅ้็ๆขฏ๏ผๆฏไธ็งๅๅค้้กนใๅชๆๆฅผๆฟๅคฑ็ซ็ๆถๅ๏ผๆๅบ่ฏฅๅๅฉ่ฟไธชๆขฏๅญ้็๏ผ่ไธๆฏ่ฎฉไฝๆทๅคฉๅคฉไป่ฟไธช้็ๆขฏ่ฟๅบๆฟๅฑใๆ่ถฃ็ๆฏ๏ผไธญๅฝ็ๆฅผๆฟๆฒกๆไธไธชๅจ็ชๅคไฟฎๅปบ้็ๆขฏ็๏ผ่ๆฏไฟฎๅปบๅจๆฅผๆฟๅ
้จ๏ผ๏ผๅ ไธบๅกๆฏๆไพไธ็งๆบๅถ๏ผๅฐฑๆ่ขซๆปฅ็จ็ๅฏ่ฝๆงใ
> โๅจ็ช่พนไฟฎ้็ๆขฏ๏ผ้ฃๅฒไธๆฏๅคชๆนไพฟไบ้ฃไบๅฐๅทไปฌไปๆฅผไธ้ป่ฟๆฅไบๅใโ
ๆณจ๏ผๆๅนถไธ่ฎคไธบๆ้็ๆขฏไฟฎๅจ็ชๅคๆฏไธไธชๅฅฝไธปๆใๅฎ้
ไธ๏ผ่ฟๆฏ็พๅฝ็ๆฟๅฐไบงๅไธบไบ่็บฆๆๆฌๅๆถๆปก่ถณๆถ้ฒ่ฆๆฑ่ๆณๅบๆฅ็็นๅญใๅจๆ็ๆฅ๏ผ่ฟๆ ทๅ็กฎๅฎๅพไธๅฆฅๅฝใๆๅชๆฏไธบไบ่ฏดๆ(้็)ๆบๅถไผ่ขซ(ๅฐๅท)ๆปฅ็จ่ๅไบไธไธชๆฏๅปใๆญคๅคๆ่ฟ่งๅพ๏ผไธ็ง็็ข่ๆ ๅ
ณ็ดง่ฆ็ไธ่ฅฟ๏ผๆปๆฏ่ขซๆฟๆฅๅ่่ฏ้ข๏ผไนๆฏไธ็งๆปฅ็จใ
ๆๅ๏ผ่ฟๆไธ็ฑป้ๅผ็ฑปๅ่ฝฌๆข๏ผๅtype affinityๆ ๅ
ณ๏ผ้ฃๅฐฑๆฏๆฐๅญฆ่ฟ็ฎ็ฌฆใๆฐๅญฆ่ฟ็ฎ็ฌฆๅคฉ็ๅช่ฝๅฏนๆฐๅญ่ฟ่ก่ฟ็ฎ๏ผๆไปฅๅฎไธค่พน็ๆไฝๆฐ้ฝไผๆ็
งNUMERIC type affinity็่งๅ่ฟ่ก็ฑปๅ่ฝฌๆขใๅฆๆไธไธชๆไฝๆฐๆฏNULL๏ผๅๆฐๅญฆ่ฟ็ฎ็็ปๆๆฏNULLใ
ๆณจ๏ผ่ฟ้๏ผSQLite3็[ๅฎๆนๆๆกฃ](http://www.sqlite.org/datatype3.html)ไผผไนๆ่ฏฏใๅๆ่ฏด็ๆฏ
> ... cast both operands to the NUMERIC **storage class** prior to being carried out.
ไฝไบๅฎไธๅนถไธๅญๅจๅไธบNUMERIC็storage class๏ผๅณๆฌๆๆ่ฏด็ๆฐๆฎ็ฑปๅ๏ผใ็ๆฅๅณไพฟๆฏSQLite3็ๅไฝ่
๏ผไนๅฎนๆ่ขซ่ฟไบๅคๆ็ๆฆๅฟตๆๆใ(ๅฝ็ถ๏ผไปๅนถ้ๅไธๆธ
่ฟไบๆฆๅฟตโโๅฆๅไนๆฒกๆณๅๅบๅฎ็ฐไบโโๅชๆฏๅฎนๆไบง็็ฌ่ฏฏ่ๅทฒใ)
|
TypeScript
|
UTF-8
| 9,837 | 3.28125 | 3 |
[
"MIT"
] |
permissive
|
import * as moore from 'moore';
import * as fs from 'fs';
import {Parser} from 'json2csv';
import * as util from 'util';
enum states {Susceptible, Infected};
enum neighbours {North = 0, NorthEast, East, SouthEast, South, SouthWest, West, NorthWest};
interface GridCell {
id: number;
value: states;
y: number;
x: number;
}
/**
* Performs a move for cell: array[y][x]
* y - the vertical co-ordinate
* x - the horizontal co-ordinate
*/
function doMove(array:Array<Array<states>>, y:number, x: number): Array<[number, number]> {
//For the cell, loop through it's neighbours and determine if there is movement
//probbility if movement is 1/8 times 0.25 (i.e. 25% a cells population will move, somewhere)
//return list of infected cells
const cell:states = array[y][x];
const newinfected: Array<[number, number]> = new Array();
if (cell == states.Infected) {
for (let i = 0; i < 8 /*number of neghbours*/; i++) {
const rand = Math.random();
if (rand < 0.25) {// 0.25 * 0.125
try {
const infectedNeighbour: [number, number] = neighbourCoords(i, y, x);
if (array[y][x] != states.Infected) {
newinfected.push(infectedNeighbour);
}
}
catch(error) {
console.log(error);
console.log(`Unable to infect ${y}, ${x} neighbour ${neighbours[i]}`);
}
}
}
}
return newinfected;
}
/**
* Determine the co-ordinates of a neighbour, given the origin co-ords and neighbour direction.
*/
function neighbourCoords(direction:neighbours, y:number, x:number): [number, number] {
let coords:[number, number];
switch (direction) {
case neighbours.North: {
coords = [y-1,x];
break;
}
case neighbours.East: {
coords = [y, x+1];
break;
}
case neighbours.South: {
coords = [y+1, x];
break;
}
case neighbours.West: {
coords = [y, x-1];
break;
}
case neighbours.NorthEast: {
coords = [y-1, x+1];
break;
}
case neighbours.SouthEast: {
coords = [y+1, x+1];
break;
}
case neighbours.NorthWest: {
coords = [y-1, x-1];
break;
}
case neighbours.SouthWest: {
coords = [y+1, x-1];
break;
}
}
if ((typeof coords == "undefined") || (coords[0] < 0) || (coords[1] < 0)) {
throw "Invalid co-ordinates created"
}
else {
return coords;
}
}
function movementPhase(array:Array<Array<states>>, height: number, width: number): Array<[number, number]> {
//Go through all the cells, picking them at random.
//For each cell perform a move
//return list of infected cells
let newinfected: Array<[number, number]> = new Array();
for (let i = 0; i < height; i++) {
for (let j = 0; j < width; j++) {
newinfected = newinfected.concat(doMove(array, i, j));
}
}
return newinfected;
}
function calculateNoInfectedNeighbours(array:Array<Array<states>>, y:number, x:number, n:number): number {
//Calculate the number of infected cells for an extended moore neighbourhood
const mooreneighbours: Array<[number, number]> = moore(n,2);
const neighbours = mooreneighbours.map((elem) => [y+elem[0], x+elem[1]]);
const infectedCells: number = neighbours.reduce((sum, elem) => {
try {
const cell = array[elem[0]][elem[1]];
if (cell == states.Infected) {
return sum+1;
}
} catch (error) {
//console.log(`Unable to get cell ${elem[0]}, ${elem[1]}`);
}
return sum;
}, 0);
return infectedCells;
}
function infectionIndex(array:Array<Array<states>>, y:number, x:number, n:number): number {
//Calculate the infection index up to a neighbourhood of size n
/* The infection index is the sum of infecteds within a cells extended moore neighbourhood, where the distance from the cell is used to give closer infecteds more influence. The distance is the neigbourhoods range */
let infectionIndex = 0;
let nminus1Infecteds = 0;
for (let i = 1; i <= n; i++) {
const infecteds = calculateNoInfectedNeighbours(array, y, x, i);
const newInfecteds = infecteds-nminus1Infecteds;
nminus1Infecteds = infecteds;
infectionIndex += (newInfecteds / i);
}
return infectionIndex;
}
function doInfection(array:Array<Array<states>>, y:number, x: number): boolean {
//Calculate infection index from cells up to 10th degree of neighbour
//Compute random infetion threshold, between 0 and 100
//If index > threshold, cell is infected
//return boolean
const index = infectionIndex(array, y, x, 5);
const threshold = Math.floor((Math.random() * 100));
return (index > threshold) ? true : false;
}
function infectionPhase(array:Array<Array<states>>, height: number, width: number): Array<[number, number]> {
//Loop through cells, and determine if any get infected.
//return list of infected cells
let newinfected: Array<[number, number]> = new Array();
for (let i = 0; i < height; i++) {
for (let j = 0; j < width; j++) {
if (array[i][j] != states.Infected) {
if (doInfection(array, i, j)) {
newinfected.push([i, j]);
}
}
}
}
return newinfected;
}
function cellPhase(array:Array<Array<states>>, height: number, width: number): Array<Array<states>> {
//build up list of infected cells
//update theWorld array of cells
let newWorld = JSON.parse(JSON.stringify(array));
let newinfected: Array<[number, number]> = new Array();
newinfected = newinfected.concat(movementPhase(array, height, width));
newinfected = newinfected.concat(infectionPhase(array, height, width));
for (let i in newinfected) {
const y = newinfected[i][0];
const x = newinfected[i][1];
try {
newWorld[y][x] = states.Infected;
}
catch (error) {
console.log(`Unable to update cell ${y}, ${x}`);
}
}
return newWorld;
}
function createWorld(worldHeight: number, worldWidth: number): Array<Array<states>> {
let theWorld: Array<Array<states>> = new Array();
for(let i = 0; i < worldHeight; i++) {
let row: Array<states> = new Array();
for(let j = 0; j < worldWidth; j++) {
let cell = states.Susceptible;
row.push(cell);
}
theWorld.push(row);
}
return theWorld;
}
function seed(array:Array<Array<states>>): Array<Array<states>> {
/* Starting Cells IDs (31 values pre -5500):
1559, 1714, 1767, 1768, 1834, 1926, 1930, 1965, 2061, 2111, 2122, 2168, 2193, 2252, 2260, 2330, 2452, 2518, 2588, 2649, 2790, 2858, 2859, 2930, 2931, 2933, 2992, 2994, 2998, 3062, 3128*/
/*ys
0-68 = 0
69-136= 1
136-204= 2
xs (x % 68) - 1
0,69,136,.. = 0
1,70,137,.. = 1
2,71,138,... = 2
*/
const source: Array<[number, number]> = new Array();
source.push([22,41]);
source.push([24,58]);
source.push([25,42]);
source.push([25,43]);
source.push([26,40]);
source.push([27,63]);
source.push([27,67]);
source.push([28,33]);
source.push([29,60]);
source.push([30,41]);
source.push([30,52]);
source.push([31,29]);
source.push([31,54]);
source.push([32,44]);
source.push([32,52]);
source.push([33,53]);
source.push([35,37]);
source.push([36,34]);
source.push([37,35]);
source.push([38,27]);
source.push([40,30]);
source.push([41,29]);
source.push([41,30]);
source.push([42,32]);
source.push([42,33]);
source.push([42,35]);
source.push([43,25]);
source.push([43,27]);
source.push([43,31]);
source.push([44,26]);
source.push([45,23]);
for (let i in source) {
const y = source[i][0];
const x = source[i][1];
try {
array[y][x] = states.Infected;
}
catch (error) {
console.log(`Unable to seed cell ${y}, ${x}`);
}
}
return array;
}
function convertToGrid(world: Array<Array<states>>, worldHeight: number, worldWidth: number): Array<GridCell> {
const grid: Array<GridCell> = new Array();
for (let i = 0, id = 0; i < worldHeight; i++) {
for (let j = 0; j < worldWidth; j++, id++) {
grid.push({id: id, value: world[i][j], y: i, x: j});
}
}
return grid;
}
function runModel(runs: number) {
//perform n runs of cell phase
//transform theWorld array into csv
//write csv file to disk
const worldHeight = 46;
const worldWidth = 69;
let theWorld: Array<Array<states>> = createWorld(worldHeight, worldWidth);
theWorld = seed(theWorld);
for (let i = 0; i < runs; i++) {
theWorld = cellPhase(theWorld, worldHeight, worldWidth)
}
const values = convertToGrid(theWorld, worldHeight, worldWidth);
const json2csv = new Parser();
const csv = json2csv.parse(values);
fs.writeFile('./data/modeloutput.csv', csv, { encoding: 'utf8' }, (err) => {
if (err) throw err;
console.log("file written");
});
}
runModel(10);
|
Markdown
|
UTF-8
| 4,345 | 2.609375 | 3 |
[] |
no_license
|
# Microbiome, Cancer, and Beyond
### Emily Davenport, Cornell, *Simultaneously modeling host genetics and microbiome composition reveals the heritability and the proportion of variance explained due to the microbiome of immune-related traits*
* Composition of of microbiome determined by method of birth, diet, antibiotics, some genetics
* For complex traits imn humans - how much inter-individual variability is explained by genetics vs the microbiome?
* If we include microbiome as a covariate in GWAS can we improve our power to identify genetic associations with a trait?
* normal GWAS linear mixed model: phenotype=[covariates]+relatedness
* extend GWAS linear mixed model to microbiome: phenotype=[covariates]+relatedness+microbiome relatedness(beta diversity)
* microbiome explains some (~25%) of variance
* traits with a large amount of variance explained by microbiome also increase power in GWAS of these traits
* **TL;DR**- you would think microbiome data would be a GWAS slam dunk, but it's not
### Tommi Maklin, University of Helsinki, *Accurate bacterial genome assembly from multi-strain enrichment cultures*
* steps strain identification - sweep & sequence, pseudoalign reads w/ kallisto, estimate proportions, then genome assembly
* pseudo-alignment grouped by clonal complex or sequence type
* model consists of pseudoalignment vectors, latent cluster indicators, mixing proportions
* prior- dirichlet, posterior- collapsed variation bayes
* **TL;DR** - assembling genomes would be helpful for antibiotic resistance, read binning based probabilities can help this problem
### Anastasia Teterina, University of Oregon, *Mode of reproduction drives the distribution of polymorphism across the genomeโTheory and empirical tests in Caenorhabditis nematodes*
* genetic variability affected by genome structure and population structure, including differences in mating types
- mating types affects population size, recombination freq
* effect of recombination of variation?
- dna polymorphism correlates with recombination rates
### Quaid Morris, University of Toronto, *Pair-tree: Reconstructing cancer phylogenies using pairwise correlations*
* cancer evolution makes nearly perfect phylogenies
* infinite sites assumption- each single nucleotide variant only occurs once during evolution and never reverts
* clonal mutations are present in all cancer cells - occur somewhere between fertilized egg and most recent common ancestors
* collinear mutations- one mutation is a descendent of another mutation type
* branched mutation- mutually exclusive set of mutations
* each collinear mutation represents a subclonal lineage aka subclone
* perfect phylogenies only made of branched/collinear mutations
* reconstructing perfect phylogenies requires only pairwise relationships, can solve in linear time
* not really perfect though... many cancers are highly aneuploid, mostly use population sequencing
* generative modeling solution - phyloWGS
* sum rule identifies some collinear pairs - if frequencies of two mutations is > 100% cannot be branching
* two mutations cannot be collinear because neither's cells can be the subset of the other's
* four gamete rule - if not branching or collinear, cannot be perfect phylogeny
* pairwise rules highly constrain phylogenies
* **TL;DR** making cancer phylogenies is harder than you'd expect, there are simple rules to make clever programs to make it easier though
### Heather Gibling, Ontario Institute for Cancer Research
* repetitive regions are difficult to genotype - solution k-mers
* PRDM9 impacts pan-cancer genomic landscape
* use k-mer count profiles to call alleles
* k-mer count profile similarity measured using the probability mass function of a Poisson distribution
* eventually going to use paired end allele calling and genotyping
* **TL;DR** using kmer counting can call alleles more accurate in repetitive regions
### David Enard, U of A, *Detecting ancient viral epidemics in human evolution*
* adaption against viruses- fast evolving anti-viral proteins
* PKR - abundant adaption in mammals
* viruses that interact with host proteins - could be ~20% of the human proteome
* viral interacting proteins are broadly conserved and constrained proteins
* VIPs are specifically enriched in strong adaptive events, in animals and fungi
* viral interacting proteins are enriched in selective sweeps
*
|
C
|
UTF-8
| 1,134 | 2.640625 | 3 |
[] |
no_license
|
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<stdio.h>
#include<unistd.h>
#include<error.h>
#include<stdlib.h>
#include"strc.h"
#include"struct.h"
#include<fcntl.h>
int socketfd=-1;
void client_req(void)
{
int connected;
struct sockaddr_in myclientaddr;
socketfd=socket(AF_INET,SOCK_STREAM,0);
if(socketfd==-1)
{
perror("client:failed to creat a socket\n");
exit(1);
}
myclientaddr.sin_family=AF_INET;
myclientaddr.sin_addr.s_addr=inet_addr("192.168.1.36");
myclientaddr.sin_port=htons(6666);
printf("client : connecting to the server\n");
connected=connect(socketfd,(struct sockaddr
*)&myclientaddr,sizeof(myclientaddr));
if(connected==-1)
{
perror("client: connect system failed\n");
close(socketfd);
exit(1);
}
}
int client (struct ch *q)
{
int retval;
retval=write(socketfd,q,sizeof(struct ch));
printf("client :write retval %d\n",retval);
return(retval);
}
int client_read(struct server *y)
{
int retval;
retval=read(socketfd,y,sizeof(struct server));
printf("client :read retval from server %d\n",retval);
return(retval);
}
|
Java
|
UTF-8
| 10,574 | 2.015625 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.gogul.tickets.service;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.json.JSONArray;
import org.json.JSONObject;
import org.junit.jupiter.api.MethodOrderer.OrderAnnotation;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import com.gogul.tickets.data.Constants;
@SpringBootTest
@TestMethodOrder(OrderAnnotation.class)
public class MovieServiceTest {
@Autowired
private MovieScheduleService movieScheduleService;
@Autowired
private ClientService clientService;
private long DUMMYID = 9999L;
private long THEATREID = 3001L;
private long SCREENID=4001L;
private long LAYOUTID=5001L;
private long MOVIEID = 20001L;
private long SCHEDULEID = 30001L;
private long USERID = 1001L;
@Test
@Order(1)
public void checkSchedule() throws Exception {
assertEquals(movieScheduleService.existsByScheduleId(DUMMYID),false);
assertEquals(movieScheduleService.existsByScheduleId(SCHEDULEID),true);
assertEquals(movieScheduleService.findScheduleByMovieId(DUMMYID).size(), 0);
assertEquals(movieScheduleService.findScheduleByMovieId(MOVIEID).size(), 1);
assertEquals(movieScheduleService.findScheduleByTheatreId(DUMMYID).size(), 0);
assertEquals(movieScheduleService.findScheduleByTheatreId(THEATREID).size(), 1);
List<Long> theatreIds = new ArrayList<Long>();
assertEquals(movieScheduleService.findScheduleByListOfTheatreId(theatreIds).size(),0);
theatreIds.add(THEATREID);
assertEquals(movieScheduleService.findScheduleByListOfTheatreId(theatreIds).size(),1);
theatreIds.add(THEATREID+1);
theatreIds.add(THEATREID+2);
assertEquals(movieScheduleService.findScheduleByListOfTheatreId(theatreIds).size(),3);
assertEquals(movieScheduleService.findScheduleByScreenId(DUMMYID).size(),0);
assertEquals(movieScheduleService.findScheduleByScreenId(SCREENID).size(),1);
assertEquals(movieScheduleService.findAll().size(), 5);
List<Long> movieIdList = new ArrayList<Long>();
assertEquals(movieScheduleService.findScheduleWithParam(movieIdList).size(), 0);
assertEquals(movieScheduleService.findScheduleByTheatreIdWithParam(DUMMYID,movieIdList).size(), 0);
assertEquals(movieScheduleService.findScheduleByTheatreIdWithParam(THEATREID,movieIdList).size(), 0);
assertEquals(movieScheduleService.findScheduleByScreenIdWithParam(DUMMYID,movieIdList).size(), 0);
assertEquals(movieScheduleService.findScheduleByScreenIdWithParam(SCREENID,movieIdList).size(), 0);
movieIdList.add(MOVIEID);
movieIdList.add(MOVIEID+1);
assertEquals(movieScheduleService.findScheduleWithParam(movieIdList).size(), 2);
assertEquals(movieScheduleService.findScheduleByTheatreIdWithParam(DUMMYID,movieIdList).size(), 0);
assertEquals(movieScheduleService.findScheduleByTheatreIdWithParam(THEATREID,movieIdList).size(), 1);
assertEquals(movieScheduleService.findScheduleByScreenIdWithParam(DUMMYID,movieIdList).size(), 0);
assertEquals(movieScheduleService.findScheduleByScreenIdWithParam(SCREENID,movieIdList).size(), 1);
}
@Test
@Order(2)
public void checkSeatsListMethod() throws Exception{
Optional<Map<Long, Map<String, Integer>>> seatMap = clientService.getSeatLayout(SCREENID);
assertEquals(seatMap.isPresent(), true);
assertEquals(seatMap.get().containsKey(LAYOUTID),true);
assertEquals(seatMap.get().get(LAYOUTID).size(),10);
Optional<Map<Long,Map<String,List<String>>>> seats = movieScheduleService.findAvailableSeats(
SCREENID,SCHEDULEID,seatMap.get());
assertEquals(seats.isPresent(), true);
assertEquals(seats.get().size(),1);
assertEquals(seats.get().containsKey(LAYOUTID),true);
assertEquals(seats.get().get(LAYOUTID).size(),3);
assertEquals(seats.get().get(LAYOUTID).containsKey("available"),true);
assertEquals(seats.get().get(LAYOUTID).containsKey("booked"),true);
assertEquals(seats.get().get(LAYOUTID).containsKey("blocked"),true);
assertEquals(seats.get().get(LAYOUTID).get("available").size(),100);
assertEquals(seats.get().get(LAYOUTID).get("booked").size(),0);
assertEquals(seats.get().get(LAYOUTID).get("blocked").size(),0);
assertEquals(seats.get().get(LAYOUTID).values().stream().flatMap(object->object.stream()).count(),100);
}
@Test
@Order(3)
public void checkBlockSeatMethod() throws Exception{
Optional<Map<Long, Map<String, Integer>>> seatMap = clientService.getSeatLayout(SCREENID);
Optional<Map<Long,Map<String,List<String>>>> seats = movieScheduleService.findAvailableSeats(
SCREENID,SCHEDULEID,seatMap.get());
JSONObject object = new JSONObject();
object.put("userId",USERID);
object.put("selectedSeats",new JSONArray());
assertEquals(movieScheduleService.blockSelectedSeats(
SCHEDULEID, DUMMYID, DUMMYID, object, seatMap.get()).isPresent(),false);
assertEquals(movieScheduleService.blockSelectedSeats(
SCHEDULEID, SCREENID, DUMMYID, object, seatMap.get()).isPresent(),false);
assertEquals(movieScheduleService.blockSelectedSeats(
SCHEDULEID, SCREENID, LAYOUTID, object, seatMap.get())
.get().getBoolean("status"),false);
object.put("selectedSeats", new JSONArray(Arrays.asList("A1","A2","A3","A4","A5","A6","A7")));
assertEquals(movieScheduleService.blockSelectedSeats(
SCHEDULEID, SCREENID, LAYOUTID, object, seatMap.get())
.get().getBoolean("status"),false);
object.put("selectedSeats", new JSONArray(Arrays.asList("A1","A2","A3","A4","A5","A6")));
assertEquals(movieScheduleService.blockSelectedSeats(
SCHEDULEID, SCREENID, LAYOUTID, object, seatMap.get())
.get().getBoolean("status"),true);
assertEquals(movieScheduleService.blockSelectedSeats(
SCHEDULEID, SCREENID, LAYOUTID, object, seatMap.get())
.get().getBoolean("status"),false);
seats = movieScheduleService.findAvailableSeats(
SCREENID,SCHEDULEID,seatMap.get());
assertEquals(seats.get().get(LAYOUTID).get("available").size(),94);
assertEquals(seats.get().get(LAYOUTID).get("booked").size(),0);
assertEquals(seats.get().get(LAYOUTID).get("blocked").size(),6);
object.put("selectedSeats", new JSONArray(Arrays.asList("B1","B2","B3","B4","B5")));
assertEquals(movieScheduleService.blockSelectedSeats(
SCHEDULEID, SCREENID, LAYOUTID, object, seatMap.get())
.get().getBoolean("status"),true);
seats = movieScheduleService.findAvailableSeats(
SCREENID,SCHEDULEID,seatMap.get());
assertEquals(seats.get().get(LAYOUTID).get("available").size(),95);
assertEquals(seats.get().get(LAYOUTID).get("booked").size(),0);
assertEquals(seats.get().get(LAYOUTID).get("blocked").size(),5);
object.put("selectedSeats", new JSONArray(Arrays.asList("B6","B7","B8","B9","B10")));
object.put("userId",USERID+1);
assertEquals(movieScheduleService.blockSelectedSeats(
SCHEDULEID, SCREENID, LAYOUTID, object, seatMap.get())
.get().getBoolean("status"),true);
seats = movieScheduleService.findAvailableSeats(
SCREENID,SCHEDULEID,seatMap.get());
assertEquals(seats.get().get(LAYOUTID).get("available").size(),90);
assertEquals(seats.get().get(LAYOUTID).get("booked").size(),0);
assertEquals(seats.get().get(LAYOUTID).get("blocked").size(),10);
object.put("selectedSeats", new JSONArray(Arrays.asList("B3","B4","B5","B6","B7","B8")));
object.put("userId",USERID+2);
assertEquals(movieScheduleService.blockSelectedSeats(
SCHEDULEID, SCREENID, LAYOUTID, object, seatMap.get())
.get().getBoolean("status"),true);
seats = movieScheduleService.findAvailableSeats(
SCREENID,SCHEDULEID,seatMap.get());
assertEquals(seats.get().get(LAYOUTID).get("available").size(),94);
assertEquals(seats.get().get(LAYOUTID).get("booked").size(),0);
assertEquals(seats.get().get(LAYOUTID).get("blocked").size(),6);
Thread.sleep((Constants.BLOCK_SEATS_EXPIRY_TIME_IN_SECONDS+1)*1000);
seats = movieScheduleService.findAvailableSeats(
SCREENID,SCHEDULEID,seatMap.get());
assertEquals(seats.get().get(LAYOUTID).get("available").size(),100);
assertEquals(seats.get().get(LAYOUTID).get("booked").size(),0);
assertEquals(seats.get().get(LAYOUTID).get("blocked").size(),0);
}
@Test
@Order(4)
public void checkBookSeatMethod() throws Exception{
Optional<Map<Long, Map<String, Integer>>> seatMap = clientService.getSeatLayout(SCREENID);
JSONObject object = new JSONObject();
object.put("userId",USERID);
object.put("screenId", DUMMYID);
object.put("seatLayoutId", DUMMYID);
object.put("seats",new JSONArray());
assertEquals(movieScheduleService.bookSeats(SCHEDULEID, object).isPresent(),false);
object.put("screenId", SCREENID);
assertEquals(movieScheduleService.bookSeats(SCHEDULEID, object).isPresent(),false);
object.put("seatLayoutId", LAYOUTID);
assertEquals(movieScheduleService.bookSeats(SCHEDULEID, object).isPresent(),false);
object.put("seats", new JSONArray(Arrays.asList("A1","A2","A3","A4","A5","A6","A7")));
assertEquals(movieScheduleService.bookSeats(SCHEDULEID, object).isPresent(),false);
object.put("seats", new JSONArray(Arrays.asList("A1","A2","A3","A4","A5","A6")));
assertEquals(movieScheduleService.bookSeats(SCHEDULEID, object).isPresent(),false);
object.put("selectedSeats", new JSONArray(Arrays.asList("A1","A2","A3","A4","A5","A6")));
assertEquals(movieScheduleService.blockSelectedSeats(
SCHEDULEID, SCREENID, LAYOUTID, object, seatMap.get())
.get().getBoolean("status"),true);
Optional<Map<Long,Map<String,List<String>>>> seats = movieScheduleService.findAvailableSeats(
SCREENID,SCHEDULEID,seatMap.get());
assertEquals(seats.get().get(LAYOUTID).get("available").size(),94);
assertEquals(seats.get().get(LAYOUTID).get("booked").size(),0);
assertEquals(seats.get().get(LAYOUTID).get("blocked").size(),6);
assertEquals(movieScheduleService.bookSeats(SCHEDULEID, object).isPresent(),true);
seats = movieScheduleService.findAvailableSeats(
SCREENID,SCHEDULEID,seatMap.get());
assertEquals(seats.get().get(LAYOUTID).get("available").size(),94);
assertEquals(seats.get().get(LAYOUTID).get("booked").size(),6);
assertEquals(seats.get().get(LAYOUTID).get("blocked").size(),0);
assertEquals(movieScheduleService.blockSelectedSeats(
SCHEDULEID, SCREENID, LAYOUTID, object, seatMap.get())
.get().getBoolean("status"),false);
}
}
|
Java
|
UTF-8
| 456 | 1.9375 | 2 |
[] |
no_license
|
package com.raqun.contentparser.api;
/**
* Created by tyln on 10.10.2016.
*/
public final class Constants {
private Constants() {
// Empty private constructor
}
public static final String URL = "https://google.com.tr";
public static final String ERROR_UNKNOWN = "Unkown Error!!!";
public static final String ERROR_CONTENT = "Content is not available!!!";
public static final String ERROR_EMPTY_CHAR = "Empty char!";
}
|
C
|
UTF-8
| 1,247 | 2.8125 | 3 |
[] |
no_license
|
//
// time_test_fibo.c
//
//
// Created by Cesar Angeles on 07/09/2020.
//
/*Include standard headers*/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
/*Include modules header we directly invoke here: */
#include "funcionesfibo.h"
#include "archivos.h"
#include "timetest.h"
/*The function main */
int main(void){
long long int value =0;
int index =0;
clock_t start, stop;
double cput =0;
double mean =0;
FILE * record = NULL;
long double buffer [OBSERVATIONS][VALUES] ={0};
size_t obs =0;
record = file_new("FIBO_TIME.dat","w");
for(obs=0; obs < OBSERVATIONS; obs++){
printf(" %zu\n",obs);
start = clock();
for( index=0; index <= 100; index++){
Sequences_rfibo(obs);
}
stop = clock();
cput= ((double)(stop-start)) /CLOCKS_PER_SEC /100;
buffer[obs][0] = obs;
buffer[obs][1] = cput;
printf("Recursiva %f s \t", cput);
start = clock();
for( index=0; index <= 100; index++){
Sequences_sfibo(obs);
}
stop = clock();
cput= ((double)(stop-start)) /CLOCKS_PER_SEC /100;
buffer[obs][2] = cput*1e3;
printf("Secuencial %f ms \t", cput*1e3);
}
file_num_write(record, VALUES, buffer, OBSERVATIONS);
fclose(record);
}
|
Markdown
|
UTF-8
| 1,418 | 2.59375 | 3 |
[] |
no_license
|
# Cats n' Dogs [](https://travis-ci.com/borisskert/cats-n-dogs)
This project contains code examples created for myself to reuse simple patterns in other projects.
## Folder structure
| sub-folder | description | documentation |
|------------|-------------|---------------|
| `./angular` | Angular with ngrx examples | [README](./angular/README.md) |
| `./springboot` | Spring boot examples written in java | [README](./springboot/README.md) |
| `./keycloak` | Realm configuration which is about to be imported to Keycloak | [Keycloak config CLI](https://github.com/adorsys/keycloak-config-cli) |
## Build the solution
Consider corresponding README files within the sub-folders.
## Run the solution
### Run with images from docker hub
```bash
$ docker-compose --project-name hub.catsndocs --file hub.docker-compose.yml down --remove-orphans && \
docker-compose --project-name hub.catsndocs --file hub.docker-compose.yml pull && \
docker-compose --project-name hub.catsndocs --file hub.docker-compose.yml up
```
## Run from the source code
You can run the solution after you built it within docker.
Use this command:
```bash
$ docker-compose down --remove-orphans && docker-compose up --build
```
## Further links
* [Repository on docker hub](https://cloud.docker.com/u/borisskert/repository/docker/borisskert/cats-n-dogs)
|
Java
|
UTF-8
| 519 | 2.296875 | 2 |
[] |
no_license
|
package com.rwb.util;
import com.alibaba.dubbo.rpc.cluster.Merger;
import org.springframework.stereotype.Component;
@Component
public class UserMerger implements Merger<String> {
@Override
public String merge(String... items) {
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append("่ฟๆฏๅๅนถ่ฟๅ็็ปๆ : ");
for (int i = 0; i < items.length; i++) {
stringBuffer.append(items[i]).append("|");
}
return stringBuffer.toString();
}
}
|
Markdown
|
UTF-8
| 1,517 | 3.484375 | 3 |
[
"MIT"
] |
permissive
|
# `date`
`date` adds an editable date field to the schema. A friendly date picker UI is presented when the field is clicked. Dates are stored as strings in `YYYY-MM-DD` format.
## Example 1
```javascript
{
name: 'date',
label: 'Date',
type: 'date'
}
```
The date picker UI uses [pikaday](https://github.com/dbushell/Pikaday#usage) for configuration.
## Example with configuration of date picker
```javascript
{
name: 'date',
label: 'Date',
type: 'date',
pikadayOptions: {
format: 'DD/MM/YYYY',
firstDay: 1
}
}
```
::: tip NOTE
Apostrophe tries its best to convert any date picker format to the above mentioned `YYYY-MM-DD` friendly sorting format, but very advanced configurations may not work out of the box, so please keep that in mind.
:::
## Settings
| Property | Type | Default | Description |
|---|---|---|---|
|name | `string` | | Sets the name of the field in the database |
|label | `string` | | Sets the label of the field that the user sees |
|required | `boolean` | false | If true, the field is mandatory |
|contextual | `boolean` | false | If true, it will prevent the field from appearing in a dialog box |
|type | `string` | | Specifies the field type |
|readOnly | `boolean` | false | If true, prevents the user from editing the field |
|help | `string` | | Help text for the field that will appear with the field's label |
|htmlHelp | `string` | | Help text with support for HTML markup |
|pikadayOptions | `object` | | Allows configuration of the date format |
|
C++
|
UTF-8
| 2,209 | 3.0625 | 3 |
[] |
no_license
|
#ifndef INCLUDE_CHOLESKY_H_
#define INCLUDE_CHOLESKY_H_
#include "common.h"
#include "graph.h"
struct EliminatedVertex {
size_t v;
size_t first_arc;
FLOAT degree;
};
struct CholeskyFactor {
size_t n;
std::vector<EliminatedVertex> elims;
std::vector<ArcC> elim_arcs;
};
void Cholesky(AdjacencyMap& graph, CholeskyFactor& chol);
class CholeskySolver {
public:
CholeskyFactor cholesky_factor;
CholeskySolver() { }
CholeskySolver(AdjacencyMap& graph) {
Cholesky(graph, cholesky_factor);
}
void Factorize(AdjacencyMap& graph) {
Cholesky(graph, cholesky_factor);
}
void Solve(const std::vector<FLOAT>& b, std::vector<FLOAT>& x) const;
void ForwardSubstitution(const std::vector<FLOAT>& b,
std::vector<FLOAT>& y) const;
void BackSubstitution(const std::vector<FLOAT>& y,
std::vector<FLOAT>& x) const;
};
struct UpperTriangular {
size_t n;
std::vector<ArcC> arcs;
std::vector<size_t> first_arc;
UpperTriangular() {
n = 0;
}
UpperTriangular(const EdgeListC& es) {
BuildGraph(es);
}
void BuildGraph(const EdgeListC& es) {
n = es.n;
size_t m = es.edges.size();
arcs.resize(m);
first_arc.resize(n + 1);
std::vector<size_t> degrees(n);
for (typename std::vector<EdgeC>::const_iterator it = es.edges.begin();
it != es.edges.end();
++it) {
degrees[std::min(it->u, it->v)]++;
}
first_arc[0] = 0;
for (size_t i = 0; i < n - 1; i++) {
first_arc[i + 1] = degrees[i] + first_arc[i];
}
first_arc[n] = m;
for (typename std::vector<EdgeC>::const_iterator it = es.edges.begin();
it != es.edges.end();
++it) {
size_t u = std::min(it->u, it->v);
size_t v = std::max(it->u, it->v);
arcs[first_arc[u]].v = v;
arcs[first_arc[u]].conductance = it->conductance;
first_arc[u]++;
}
first_arc[0] = 0;
for (size_t i = 0; i < n - 1; i++) {
first_arc[i + 1] = degrees[i] + first_arc[i];
}
first_arc[n] = m;
}
void FreeMemory() {
n = 0;
arcs = std::vector<ArcC>();
first_arc = std::vector<size_t>();
}
};
#endif // INCLUDE_CHOLESKY_SOLVER_H_
|
Java
|
UTF-8
| 3,765 | 1.960938 | 2 |
[
"Apache-2.0"
] |
permissive
|
package org.zackratos.appstore.base.applist;
import com.google.gson.Gson;
import org.zackratos.appstore.base.RxPresenter;
import org.zackratos.appstore.error.ErrorConsumer;
import org.zackratos.appstore.result.BaseResult;
import org.zackratos.appstore.http.ServiceApi;
import org.zackratos.appstore.main.PageParams;
import org.zackratos.appstore.result.AppInfo;
import org.zackratos.appstore.result.PageBean;
import org.zackratos.appstore.utils.RxUtils;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
/**
*
* Created by xiboke on 2017/10/25.
*/
public abstract class AppListPresenter extends RxPresenter<AppListContract.View> implements AppListContract.Presenter {
protected ServiceApi serviceApi;
private int page;
private PageParams pageParams;
private Gson gson;
public AppListPresenter(ServiceApi serviceApi, Gson gson, PageParams params) {
this.serviceApi = serviceApi;
this.gson = gson;
this.pageParams = params;
}
private Observable<PageBean<AppInfo>> getTopListObservable() {
return Observable.just(page)
.subscribeOn(Schedulers.io())
.map(new Function<Integer, String>() {
@Override
public String apply(@NonNull Integer integer) throws Exception {
pageParams.setPage(integer);
return gson.toJson(pageParams);
}
})
.flatMap(new Function<String, ObservableSource<BaseResult<PageBean<AppInfo>>>>() {
@Override
public ObservableSource<BaseResult<PageBean<AppInfo>>> apply(@NonNull String s) throws Exception {
// return serviceApi.rxTopList(s);
return getBaseResultObservable(s);
}
})
.compose(RxUtils.<PageBean<AppInfo>>handlerBaseError())
.observeOn(AndroidSchedulers.mainThread());
}
@Override
public void loadFirstPage() {
page = 0;
Disposable disposable = getTopListObservable()
.subscribe(new Consumer<PageBean<AppInfo>>() {
@Override
public void accept(PageBean<AppInfo> appInfoPageBean) throws Exception {
view.setFirstData(appInfoPageBean);
page++;
}
}, new ErrorConsumer() {
@Override
public void handlerError(String message) {
view.loadFirstFail(message);
}
});
addSubscribe(disposable);
}
@Override
public void loadMore() {
Disposable disposable = getTopListObservable()
.subscribe(new Consumer<PageBean<AppInfo>>() {
@Override
public void accept(PageBean<AppInfo> appInfoPageBean) throws Exception {
view.setMoreData(appInfoPageBean);
page++;
}
}, new ErrorConsumer() {
@Override
public void handlerError(String message) {
view.loadMoreFail(message);
}
});
addSubscribe(disposable);
}
protected abstract ObservableSource<BaseResult<PageBean<AppInfo>>> getBaseResultObservable(String params);
}
|
Java
|
UTF-8
| 1,451 | 2.328125 | 2 |
[] |
no_license
|
package iit.cs445.models.products;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.assertEquals;
@RunWith(Arquillian.class)
public class InstallableTest {
private InstallableImplementationTest installableImplementationTest;
@Deployment
public static JavaArchive createDeployment() {
return ShrinkWrap.create(JavaArchive.class)
.addClass(Installable.class)
.addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml");
}
@Before
public void setUp() throws Exception {
installableImplementationTest = new InstallableImplementationTest();
}
@After
public void tearDown() throws Exception {
installableImplementationTest = null;
}
@Test
public void installPrice() throws Exception {
assertEquals(new Float(0F), installableImplementationTest.installPrice());
}
@Test
public void installEquipments() throws Exception {
assertEquals(0, installableImplementationTest.installEquipments().size());
}
private class InstallableImplementationTest implements Installable {
}
}
|
TypeScript
|
UTF-8
| 3,631 | 2.578125 | 3 |
[] |
no_license
|
import { Request,Response, RequestHandler, NextFunction } from 'express'
import {nanoid} from 'nanoid';
import Square from 'square';
type OrderReceipt = {
orderId: string;
price: number;
date: Date;
}
//type Req = { email: string; housenumber: string; streetnumber: string; orderid: string };
export default function processPayment(req: Request,res: Response, next: NextFunction): RequestHandler<Request,Response,NextFunction> {
try {
let url = 'https://connect.squareupsandbox.com/v2/payments'
if (process.env.NODE_ENV === "production") {
url = 'https://connect.squareup.com/v2/payments'
}
if (process.env?.STAGING === "true") {
url = 'https://connect.squareupsandbox.com/v2/payments'
}
//let pymtreq = new CreatePaymentRequest();
let pymtreq: Square.CreatePaymentRequest = {
sourceId: req.body.nonce,
idempotencyKey: nanoid(),
amountMoney: {
amount: BigInt(parseInt(req.body.price)), // convert to cents for Square API!
currency: 'USD'
},
locationId: process.env.REACT_APP_LOCATION_ID,
orderId: req.body.orderid
}
let clientEnvironmentSandbox = {
accessToken: process.env.SQUARE_ACCESS_TOKEN,
environment: Square.Environment.Sandbox,
customUrl: "https://connect.squareupsandbox.com"
}
let clientEnvironmentProduction = {
accessToken: process.env.SQUARE_ACCESS_TOKEN,
environment: Square.Environment.Production
}
let clientEnvironment;
clientEnvironment = clientEnvironmentSandbox;
if (process.env.NODE_ENV === "production") {
clientEnvironment = clientEnvironmentProduction;
}
if (process.env?.STAGING === "true") {
clientEnvironment = clientEnvironmentSandbox;
}
let client = new Square.Client(clientEnvironment);
const paymentsApi = client.paymentsApi;
paymentsApi.createPayment(pymtreq).then(pymtRes => {
if (!pymtRes.hasOwnProperty("errors") || 0 === pymtRes.result.errors?.length) {
res.json({
orderId: pymtreq.orderId,
price: parseInt(req.body.price),
date: Date.now(),
vendorInfo: JSON.stringify(pymtRes.body)
})
} else {
next("error calling paymentsApi.createPayment: " + pymtRes.result.errors?.join(" "))
}
}).catch(error => {
console.error(error.message);
if (undefined !== error.body) {
console.error(error.body);
res.statusCode = 401;
res.setHeader("Content-Type","application/json")
let newerrorbody = error.body.replace("^\"","\"$",'')
res.send(newerrorbody);
} else {
next(`payment failed, error: ${error.message}`)
}
});
} catch (error) {
console.error(error.message);
if (undefined !== error.body) {
console.error(error.body);
res.statusCode = 401;
res.setHeader("Content-Type","application/json")
let newerrorbody = error.body.replace("^\"","\"$",'')
res.send(newerrorbody);
} else {
next(error)
}
}
return((void(null) as unknown) as RequestHandler<Request,Response>);
}
export {processPayment}
|
SQL
|
UTF-8
| 2,775 | 3.875 | 4 |
[] |
no_license
|
CREATE TABLE IF NOT EXISTS public.tariffs (
tariff_id BIGINT NOT NULL PRIMARY KEY UNIQUE,
monthly_payment FLOAT NOT NULL,
minutes_per_month INTEGER
);
CREATE TABLE IF NOT EXISTS public.customers (
customer_id BIGINT NOT NULL PRIMARY KEY UNIQUE,
tariff_id BIGINT NOT NULL REFERENCES public.tariffs,
phone_number VARCHAR(12) NOT NULL,
name VARCHAR(255) NOT NULL,
address VARCHAR(255) NOT NULL
);
CREATE TABLE IF NOT EXISTS public.payments (
payment_id BIGINT NOT NULL PRIMARY KEY UNIQUE,
customer_id BIGINT NOT NULL REFERENCES public.customers,
created_at DATE,
amount FLOAT NOT NULL
);
-- Insert some test data
INSERT INTO public.tariffs (tariff_id, monthly_payment, minutes_per_month) VALUES (1, 500, -1);
INSERT INTO public.tariffs (tariff_id, monthly_payment, minutes_per_month) VALUES (2, 400, 300);
INSERT INTO public.customers (customer_id, tariff_id, phone_number, name, address)
VALUES (1, 1, '+79990000001', 'Ivanov Ivan Ivanovich', 'Kovalikhinskaya, 8');
INSERT INTO public.customers (customer_id, tariff_id, phone_number, name, address)
VALUES (2, 2, '+79990000002', 'Petrov Petr Petrovich', 'Kovalikhinskaya, 9');
INSERT INTO public.payments (payment_id, customer_id, created_at, amount)
VALUES (1, 1, to_date('09-11-2017', 'MM-DD-YYYY'), 600);
-- This two will be represented as one entry in result (if everything was correct)
INSERT INTO public.payments (payment_id, customer_id, created_at, amount)
VALUES (2, 1, to_date('10-11-2017', 'MM-DD-YYYY'), 300);
INSERT INTO public.payments (payment_id, customer_id, created_at, amount)
VALUES (3, 1, to_date('10-20-2017', 'MM-DD-YYYY'), 200);
INSERT INTO public.payments (payment_id, customer_id, created_at, amount)
VALUES (4, 1, to_date('11-11-2017', 'MM-DD-YYYY'), 400);
INSERT INTO public.payments (payment_id, customer_id, created_at, amount)
VALUES (5, 1, to_date('12-11-2017', 'MM-DD-YYYY'), 500);
INSERT INTO public.payments (payment_id, customer_id, created_at, amount)
VALUES (6, 2, to_date('09-21-2017', 'MM-DD-YYYY'), 400);
INSERT INTO public.payments (payment_id, customer_id, created_at, amount)
VALUES (7, 2, to_date('10-21-2017', 'MM-DD-YYYY'), 300);
-- This two will be represented as one entry in result (if everything was correct)
INSERT INTO public.payments (payment_id, customer_id, created_at, amount)
VALUES (8, 2, to_date('11-01-2017', 'MM-DD-YYYY'), 100);
INSERT INTO public.payments (payment_id, customer_id, created_at, amount)
VALUES (9, 2, to_date('11-21-2017', 'MM-DD-YYYY'), 300);
INSERT INTO public.payments (payment_id, customer_id, created_at, amount)
VALUES (10, 2, to_date('12-21-2017', 'MM-DD-YYYY'), 400);
-- At the end, customer 1 is fine, but customer 2 must be in debt by -100 points and do not have minutes available (0)
|
Java
|
UTF-8
| 1,878 | 2.296875 | 2 |
[] |
no_license
|
package com.ard.arduino;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.media.MediaRecorder;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.util.Log;
import android.widget.Button;
public class Recorder implements Runnable{
MediaRecorder recorder ;
String CameraURL;
boolean record=true;
public Recorder(String url) {
// TODO Auto-generated constructor stub
recorder= new MediaRecorder();
CameraURL=url;
}
@Override
public void run() {
// TODO Auto-generated method stub
int port = 8080;
Socket socket=null;
try {
socket = new Socket(InetAddress.getByName(CameraURL), port);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ParcelFileDescriptor pfd = ParcelFileDescriptor.fromSocket(socket);
// Additional MediaRecorder setup (output format ... etc.) omitted
recorder.setOutputFile(pfd.getFileDescriptor());
recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
String filename=System.nanoTime()+"";
//Bitmap bm = viewStreaming.getDrawingCache();
File filepath = new File(Environment.getExternalStorageDirectory()+"/DCIM/Simori/Video/Simori_"+filename+".avi");
recorder.setOutputFile(filepath.getAbsolutePath());
try {
recorder.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
recorder.start();
while(record){
Log.d("Recorder", "Recording...");
}
recorder.stop();
}
public void stopRec(){
record=false;
}
}
|
JavaScript
|
UTF-8
| 514 | 3.5625 | 4 |
[] |
no_license
|
//
// This is only a SKELETON file for the "Bob" exercise. It's been provided as a
// convenience to get you started writing code faster.
//
const Bob = () => {
isUpperCase = x => {
return /[a-zA-Z]/.test(x) && x.toUpperCase() === x
}
return {
hey: (input) => {
if (input.endsWith('?') && !isUpperCase(input)) return 'Sure.'
if (isUpperCase(input)) return 'Whoa, chill out!'
if (!input.trim()) return 'Fine. Be that way!'
return 'Whatever.'
}
}
}
module.exports = Bob
|
C++
|
UTF-8
| 322 | 2.6875 | 3 |
[] |
no_license
|
//NodeIterator.h
#ifndef _NODE_ITERATOR_H
#define _NODE_ITERATOR_H
#include "MenuNode.h"
class NodeIterator
{
public:
virtual void First() = 0;
virtual void Next() = 0;
virtual void Prev() = 0;
virtual bool IsDone() const = 0;
virtual MenuNode* CurrentNode() const = 0;
protected:
NodeIterator();
};
#endif
|
C
|
UTF-8
| 2,081 | 3.34375 | 3 |
[] |
no_license
|
#include <test/task_queue.h>
void tq_sanity() {
task_queue tq;
tq_init(&tq);
assert(tq.size == 0);
}
void tq_push_basic() {
task_queue tq;
tq_init(&tq);
assert(tq.size == 0);
TaskDescriptor t;
tq_push(&tq, &t);
assert(tq.size == 1);
tq_push(&tq, &t);
tq_push(&tq, &t);
assert(tq.size == 3);
}
/**
* Pushes 1 task to queue and validates popped result.
*/
void tq_pop_basic() {
task_queue tq;
tq_init(&tq);
TaskDescriptor t1, t2;
td_init(&t1);
td_init(&t2);
tq_push(&tq, &t1);
assert(tq.size == 1);
TaskDescriptor *td;
int ret;
ret = tq_pop(&tq, &td);
assert(tq.size == 0);
assert(ret == 0);
assert(td == &t1);
ret = tq_pop(&tq, &td);
assert(ret == ETQ_EMPTY);
}
/**
* Pushes 2 tasks to queue and validates popped results.
*/
void tq_pop_2() {
task_queue tq;
tq_init(&tq);
TaskDescriptor t1, t2;
td_init(&t1);
td_init(&t2);
TaskDescriptor *td;
int ret;
tq_push(&tq, &t1);
assert(tq.size == 1);
tq_push(&tq, &t2);
assert(tq.size == 2);
ret = tq_pop(&tq, &td);
assert(tq.size == 1);
assert(ret == 0);
assert(td == &t1);
ret = tq_pop(&tq, &td);
assert(tq.size == 0);
assert(ret == 0);
assert(td == &t2);
}
/**
* Pushes 2 tasks to queue and validates popped results twice
*/
void tq_pop_22() {
task_queue tq;
tq_init(&tq);
TaskDescriptor t1, t2;
td_init(&t1);
td_init(&t2);
TaskDescriptor *td;
int ret;
tq_push(&tq, &t1);
assert(tq.size == 1);
tq_push(&tq, &t2);
assert(tq.size == 2);
ret = tq_pop(&tq, &td);
assert(tq.size == 1);
assert(ret == 0);
assert(td == &t1);
ret = tq_pop(&tq, &td);
assert(tq.size == 0);
assert(ret == 0);
assert(td == &t2);
tq_push(&tq, &t1);
assert(tq.size == 1);
tq_push(&tq, &t2);
assert(tq.size == 2);
ret = tq_pop(&tq, &td);
assert(tq.size == 1);
assert(ret == 0);
assert(td == &t1);
ret = tq_pop(&tq, &td);
assert(tq.size == 0);
assert(ret == 0);
assert(td == &t2);
}
void task_queue_tests() {
tq_sanity();
tq_push_basic();
tq_pop_basic();
tq_pop_2();
tq_pop_22();
}
|
C++
|
UTF-8
| 2,315 | 2.84375 | 3 |
[] |
no_license
|
//
// Created by smorzhov on 22.02.16.
//
#include <sstream>
#include "IPv4Address.h"
IPv4Address::IPv4Address() {
ip = "0.0.0.0/0";
prefix = maskbits = 0;
}
IPv4Address::IPv4Address(const char *s) {
ip = s;
pair<uint32_t, uint8_t> pair = parseIPV4string(s);
prefix = pair.first;
maskbits = pair.second;
}
bool IPv4Address::isDisjoint(const void *ip) const {
const IPv4Address *ipv4 = static_cast<const IPv4Address *>(ip);
if (!this->isSubnetAddress() && !ipv4->isSubnetAddress())
return !(maskbits == ipv4->maskbits && prefix == ipv4->prefix);
if (maskbits < ipv4->maskbits && !this->isSubnetAddress())
return true;
if (ipv4->maskbits < maskbits && !ipv4->isSubnetAddress())
return true;
uint8_t mask = 0xffffffff << (32 - min(maskbits, ipv4->maskbits));
return ((prefix & mask) != (ipv4->prefix & mask));
}
bool IPv4Address::isSubnetAddress() const {
return (prefix & (0xffffffff << (32 - maskbits))) == prefix;
}
bool IPv4Address::isSubset(void *ip) const {
IPv4Address *s = static_cast<IPv4Address *>(ip);
if (!this->isSubnetAddress() && !s->isSubnetAddress())
return maskbits == s->maskbits && prefix == s->prefix;
if (s->maskbits > maskbits) return false;
uint32_t mask = 0xffffffff << (32 - s->maskbits);
return (s->isSubnetAddress() && ((prefix & mask) == (s->prefix & mask)));
}
bool IPv4Address::equals(void *ip) const {
IPv4Address *ipv4 = static_cast<IPv4Address *>(ip);
return prefix == ipv4->prefix && maskbits == ipv4->maskbits;
}
pair<uint32_t, uint8_t> IPv4Address::parseIPV4string(const char* ipAddress) {
unsigned char ipbytes[4], mask;
sscanf(ipAddress, "%hhd.%hhd.%hhd.%hhd/%hhd", &ipbytes[0], &ipbytes[1], &ipbytes[2], &ipbytes[3], &mask);
uint32_t prefix =
uint32_t(ipbytes[0]) << 24 |
uint32_t(ipbytes[1]) << 16 |
uint32_t(ipbytes[2]) << 8 |
uint32_t(ipbytes[3]);
return make_pair(prefix, mask % 32);
}
const string IPv4Address::getPrefix() const {
char ipAddr[16];
snprintf(ipAddr, sizeof ipAddr, "%u.%u.%u.%u",
(prefix & 0xff000000) >> 24,
(prefix & 0x00ff0000) >> 16,
(prefix & 0x0000ff00) >> 8,
(prefix & 0x000000ff));
return ipAddr;
}
|
TypeScript
|
UTF-8
| 803 | 2.515625 | 3 |
[] |
no_license
|
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class Base64Service {
constructor() { }
strBase64ToPdfBlob(strBase64: string) {
let binaryDoc = atob(strBase64);
let binaryDocLength = binaryDoc.length;
let arrayBuffer = new ArrayBuffer(binaryDocLength);
let uInt8Array = new Uint8Array(arrayBuffer);
for (let i = 0; i < binaryDocLength; i++) {
uInt8Array[i] = binaryDoc.charCodeAt(i);
}
let outputBlob = new Blob([uInt8Array], {type: 'application/pdf'});
return outputBlob;
}
strBase64ToPdfUrl(strBase64: string) {
let pdfBlob = this.strBase64ToPdfBlob(strBase64);
return this.createUrlFromPdfBlob(pdfBlob);
}
createUrlFromPdfBlob(pdfBlob: Blob) {
return URL.createObjectURL(pdfBlob);
}
}
|
Markdown
|
UTF-8
| 1,830 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
+++
date = 2014-12-11T00:00:00 # Schedule page publish date.
title = "The Value of True Belief"
time_start = 2014-12-11T13:00:00
time_end = 2014-12-11T15:00:00
abstract = "I cover some initially plausible accounts of why we ought to value knowledge over mere true belief, as well as why we ought to value mere true belief over false belief. I introduce a case of two epistemic agents with the same capabilities, although one epistemic agent's beliefs are parasitic over the other's. If we care only for the instrumental value of knowledge, we should be indifferent in our preferences to be either epistemic agent. This conclusion is absurd. I then introduce the proposal that instantiation of particular epistemic virtues distinguishes between these epistemic agents, even though both epistemic agents are just as knowledgable as one another. I conclude that instantiation of epistemic virtues is valuable in-itself."
abstract_short = ""
event = "Third OZSW Philosophy Conference"
event_url = "http://www.ozsw.nl/ozsw-conference-2014-radboud-university-nijmegen/"
location = "Radboud University Nijmegen. Nijmegen, The Netherlands."
# Is this a selected talk? (true/false)
selected = true
# Projects (optional).
# Associate this talk with one or more of your projects.
# Simply enter the filename (excluding '.md') of your project file in `content/project/`.projects = ["deep-learning"]
# Links (optional).
url_pdf = ""
url_slides = "files/slides/truebelief.pdf"
url_video = ""
url_code = ""
# Does the content use math formatting?
math = true
# Does the content use source code highlighting?
highlight = true
# Featured image
# Place your image in the `static/img/` folder and reference its filename below, e.g. `image = "example.jpg"`.[header]/ image = "headers/bubbles-wide.jpg"/ caption = "My caption :smile:"
+++
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.