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
294
3.40625
3
[ "MIT" ]
permissive
#include<stdio.h> int main(void) { int p, n; float r, i; printf("Enter Principle Amount \n"); scanf("%i",&p); printf("Enter Rate of Interest in Percentage \n"); scanf("%f",&r); printf("Enter Number of Months \n"); scanf("%i",&n); i=p*r*n/100; printf("Interest Value is %f \n",i); }
C#
UTF-8
608
2.734375
3
[]
no_license
using System.Runtime.InteropServices; public string GetUserName() { byte[] user = new byte[256]; Int32[] len = new Int32[1]; len[0] = 256; GetUserName(user, len); return (System.Text.Encoding.ASCII.GetString(user)); } [DllImport("Advapi32.dll", EntryPoint = "GetUserName", ExactSpelling = false, SetLastError = true)] static extern bool GetUserName([MarshalAs(UnmanagedType.LPArray)] byte[] lpBuffer, [MarshalAs(UnmanagedType.LPArray)] Int32[] nSize);
Python
UTF-8
818
3.875
4
[]
no_license
class User: def __init__(self, name, score): self.name = name self.score = score def increase_score(self): self.score += 1 def get_score(self): return self.score def __str__(self): return f"<<User object: name={self.name} score={self.score}>>" class Customer(User): def __init__(self, name, score): super().__init__(name, score) user_1 = User("John", 0) user_2 = User("John", 0) user_1.increase_score() user_1.increase_score() user_2.increase_score() user_1_score = user_1.get_score() user_2_score = user_2.get_score() print(f"user_1_score: {user_1_score}") print(f"user_2_score: {user_2_score}") print(f"This is user_1 detail: {str(user_1)}") customer_1 = Customer("Abe", 10) print(f"This is customer_1 detail: {str(customer_1)}") print(isinstance(customer_1, User))
Markdown
UTF-8
2,884
3.015625
3
[]
no_license
# Events Manager Import Export (Network mode) Basic import and export function for [Events Manager](https://wordpress.org/plugins/events-manager/). Forked version to fix issues related to network mode Wordpress Installation. Original project(s) on github: - https://github.com/asmartin/events-manager-import-export - https://github.com/webaware/events-manager-import-export ## Example Import CSV A CSV imported into Wordpress should contain the following columns: - uid - a unique number representing this event - summary - title of the event - dtstart - start date and time of the event (in format matching the `dtformat` column) - dtend - end date and time of the event (in format matching the `dtformat` column) - dtformat - format of the `dtstart` and `dtend` columns in the [PHP date() format](http://php.net/manual/en/function.date.php) - categories - a comma-separated list of categories that the event should be added to - post_content - description of the event - location_name - name of the location (optional) - location_address - street address of the location - location_town - city or town portion of the location address - location_state - state portion of the address - location_postcode - zipcode portion of the address - location_country - country portion of the address - location_latitude - latitude for the location (optional) - location_longitude - longitude for the location (optional) Below is an example row: ``` "uid","summary","dtstart","dtend","dtformat","categories","post_content","location_name","location_address","location_town","location_state","location_postcode","location_country","location_latitude","location_longitude" "233","My Example Event","2016-06-16 11:00:00","2016-06-16 21:00:00","Y-m-d H:i:s","My Category 1,My Category 2","This is a description of the event.","The White House","1600 Pennsylvania Avenue","Washington","DC","20500","US","38.89761","-77.03673" ``` ## Note from the original author Although I never officially released this plugin, it seems to have leaked out and become a part of quite a few websites. I figure that means I ought to get it up and onto [GitHub](https://github.com/webaware/events-manager-import-export) where people can find it and report bugs. I probably won't be releasing this on WordPress.org because there's already a pretty good plugin for synchronising events between websites: * [Events Manager ESS](https://wordpress.org/plugins/events-manager-ess/) -- recommended for sychronising events between websites However, for those who want to continue using this plugin, please feel free to lodge issues and create pull requests. I can't promise that I'll address them in a timely fashion, but I'll try my best. [Donations are always welcome](http://shop.webaware.com.au/donations/?donation_for=Events+Manager+Import+Export) :smiley:
Python
UTF-8
1,987
2.5625
3
[]
no_license
import os import boto3 from flask import Flask from flask import jsonify, request app = Flask(__name__) # USERS_TABLE = os.environ['cpfevents'] tablename = 'BaseC' client = boto3.client('dynamodb') @app.route('/') def index(): return 'Index Page' @app.route('/hello') def hello(): return 'Hello, World' @app.route("/test/<string:cpfnumber>") def getcpf(cpfnumber): return 'cpf: {}'.format(cpfnumber) @app.route("/getLastEvent/<string:cpfnumber>") def get_LastEvent(cpfnumber): resp = client.get_item( TableName=tablename, Key={ 'cpf': { 'S': cpfnumber } } ) item = resp.get('Item') if not item: return jsonify({'error': 'Event does not exist'}), 404 return jsonify({ 'event': item.get('event').get('S'), 'value': item.get('value').get('S') }) @app.route("/getEvent/<string:cpfnumber>/<string:event>") def get_specificEvents(cpfnumber,event): resp = client.get_item( TableName=tablename, Key={ 'cpf': { 'S': cpfnumber }, 'event': {'S': event } } ) item = resp.get('Item') if not item: return jsonify({'error': 'Event does not exist'}), 404 return jsonify({ 'event': item.get('event').get('S'), 'value': item.get('value').get('S') } ) @app.route("/addEvent", methods=["POST"]) def create_event(): cpf = request.json.get('cpf') event = request.json.get('event') value = request.json.get('value') if not cpf or not event or not value: return jsonify({'error': 'Please provide cpf, event and value'}), 400 resp = client.put_item( TableName=tablename, Item={ 'cpf': {'S': cpf }, 'event': {'S': event }, 'value': {'S': value } } ) return jsonify({ 'cpf': cpf, 'event': event, 'value': value }) # if __name__ == '__main__': # app.run()
Markdown
UTF-8
667
2.9375
3
[]
no_license
Banana Bread Ingredients: * 3 ripe bananas * 256 g (2 cups) all-purpose flour * 6 g (1 tsp) salt * 4 g (1 tsp) baking powder * 5 g (1 tsp) baking soda * 113 g (1/2 cup) soft butter * 201 g (1 cup) sugar * 2 large eggs * 1/4 tsp vanilla * 1 tbsp milk * 1 cup chopped walnuts * 53.3 g (1/3 cup) dark chocolate chips Steps: * mash banana * mix flour, salt, baking powder, baking soda in a bowl (extra 1tsp cinnamon) * mix soft butter and sugar (spatula), whisk in banana mixture ** then the 2 eggs, one at a time ** add vanilla, milk, nuts, chocolate, flour mix, then fold until flour is barely integrated *Bake in a 9x4 loaf pan at 160C for about 1 hour 10 minutes.
C++
UTF-8
441
2.671875
3
[]
no_license
#include <iostream> #include <algorithm> #include <math.h> #include <vector> #include <string> #include <queue> #include <map> #include <utility> using namespace std; using ll = long long; int main() { ll n; cin >> n ; vector <ll> a(n); for (ll i=0;i<n;i++) { cin >>a[i]; } sort(a.begin(),a.end()); for (ll i=1;i<n;i++) { if (a[i] == a[i-1]) { cout << "NO" << endl; return 0; } } cout << "YES" << endl; return 0; }
C++
UTF-8
985
2.515625
3
[ "MIT" ]
permissive
// // Created by everettjf on 2017/7/23. // #include "LoadCommandsViewNode.h" MOEX_NAMESPACE_BEGIN void LoadCommandsViewNode::Init(MachHeaderPtr mh){ mh_ = mh; for(auto & cmd : mh_->loadcmds_ref()){ LoadCommandViewNodePtr o = LoadCommandViewNodeFactory::Create(cmd); cmds_.push_back(o); } } void LoadCommandsViewNode::ForEachChild(std::function<void(ViewNode*)> callback){ for(auto & cmd : cmds_){ callback(cmd.get()); } } void LoadCommandsViewNode::InitViewDatas(){ using namespace moex::util; // Table { TableViewDataPtr t = std::make_shared<TableViewData>(); t->AddRow("","","Number of commands",AsString(cmds_.size())); AddViewData(t); } // Binary { BinaryViewDataPtr b = std::make_shared<BinaryViewData>(); b->offset = (char*)mh_->header_start() + mh_->DATA_SIZE(); b->size = mh_->data_ptr()->sizeofcmds; AddViewData(b); } } MOEX_NAMESPACE_END
JavaScript
UTF-8
42,753
2.796875
3
[]
no_license
$(document).ready(function() { let januaryArray = [ '&ldquo;I believe that if one always looked at the skies, one would end up with wings.&rdquo; <br /> &mdash;Gustave Flaubert', '&ldquo;It is a matter of shame that in the morning the birds should be awake earlier than you.&rdquo; <br /> &mdash;Abu Bakr', '&ldquo;Even in winter an isolated patch of snow has a special quality.&rdquo; <br /> &mdash;Andy Goldsworthy', '&ldquo;The least movement is of importance to all nature. The entire ocean is affected by a pebble.&rdquo; <br /> &mdash;Blaise Pascal', '&ldquo;I perhaps owe having become a painter to flowers.&rdquo; <br /> &mdash;Claude Monet', '&ldquo;I did not become a vegetarian for my health, I did it for the health of the chickens.&rdquo; <br /> &mdash;Isaac Bashevis Singer', '&ldquo;My boy, one small breeze doesn&rsquo;t make a wind storm.&rdquo; <br /> &mdash;John McGraw', '&ldquo;If people think nature is their friend, then they sure don&rsquo;t need an enemy.&rdquo; <br /> &mdash;Kurt Vonnegut', '&ldquo;The fall of dropping water wears away the Stone.&rdquo; <br /> &mdash;Lucretius', '&ldquo;We won&rsquo;t have a society if we destroy the environment.&rdquo; <br /> &mdash;Margaret Mead', '&ldquo;Sunlight is painting.&rdquo; <br /> &mdash;Nathaniel Hawthorne', '&ldquo;The rose and the thorn, and sorrow and gladness are linked together.&rdquo; <br /> &mdash;Saadi', '&ldquo;Nature reserves the right to inflict upon her children the most terrifying jests.&rdquo; <br /> &mdash;Thornton Wilder', '&ldquo;The earth has received the embrace of the sun and we shall see the results of that love.&rdquo; <br /> &mdash;Sitting Bull', '&ldquo;There is nothing in a caterpillar that tells you it&rsquo;s going to be a butterfly.&rdquo; <br /> &mdash;R. Buckminster Fuller', '&ldquo;Truth makes on the ocean of nature no one track of light; every eye, looking on, finds its own.&rdquo; <br /> &mdash;Edward G. Bulwer-Lytton', '&ldquo;The ocean is a mighty harmonist.&rdquo; <br /> &mdash;William Wordsworth', '&ldquo;Bad weather always looks worse through a window.&rdquo; <br /> &mdash;Tom Lehrer', '&ldquo;If the Sun and Moon should ever doubt, they&rsquo;d immediately go out.&rdquo; <br /> &mdash;William Blake', '&ldquo;The day, water, sun, moon, night &ndash; I do not have to purchase these things with money.&rdquo; <br /> &mdash;Plautus', '&ldquo;Men stumble over pebbles, never over mountains.&rdquo; <br /> &mdash;Marilyn French', '&ldquo;That which is not good for the bee-hive cannot be good for the bees.&rdquo; <br /> &mdash;Marcus Aurelius', '&ldquo;For greed all nature is too little.&rdquo; <br /> &mdash;Lucius Annaeus Seneca', '&ldquo;How glorious a greeting the sun gives the mountains!&rdquo; <br /> &mdash;John Muir', '&ldquo;He could not die when trees were green, for he loved the time too well.&rdquo; <br /> &mdash;John Clare', '&ldquo;Nature is wont to hide herself.&rdquo; <br /> &mdash;Heraclitus', '&ldquo;Nothing is more beautiful than the loveliness of the woods before sunrise.&rdquo; <br /> &mdash;George Washington Carver', '&ldquo;Gray skies are just clouds passing over.&rdquo; <br /> &mdash;Duke Ellington', '&ldquo;The universe seems neither benign nor hostile, merely indifferent.&rdquo; <br /> &mdash;Carl Sagan', '&ldquo;What makes the desert beautiful is that somewhere it hides a well.&rdquo; <br /> &mdash;Antoine de Saint-Exupery', '&ldquo;All are but parts of one stupendous whole, Whose body Nature is, and God the soul.&rdquo; <br /> &mdash;Alexander Pope' ] let februaryArray = [ '&ldquo;The only Zen you can find on the tops of mountains is the Zen you bring up there.&rdquo; <br /> &mdash;Robert M. Pirsig', '&ldquo;Nature soaks every evil with either fear or shame.&rdquo; <br /> &mdash;Tertullian', '&ldquo;Simplicity is natures first step, and the last of art.&rdquo; <br /> &mdash;Philip James Bailey', '&ldquo;If you cut down a forest, it doesn&rsquo;t matter how many sawmills you have if there are no more trees.&rdquo; <br /> &mdash;Susan George', '&ldquo;Waters are distilled out of Herbs, Flowers, Fruits, and Roots.&rdquo; <br /> &mdash;Nicholas Culpeper', '&ldquo;Land really is the best art.&rdquo; <br /> &mdash;Andy Warhol', '&ldquo;The most important thing about Spaceship Earth &ndash; an instruction book didn&rsquo;t come with it.&rdquo; <br /> &mdash;R. Buckminster Fuller', '&ldquo;Sorrows are like thunderclouds, in the distance they look black, over our heads scarcely gray.&rdquo; <br /> &mdash;Jean Paul', '&ldquo;There&rsquo;s no night without stars.&rdquo; <br /> &mdash;Andre Norton', '&ldquo;Nature always wears the colors of the spirit.&rdquo; <br /> &mdash;Ralph Waldo Emerson', '&ldquo;The longer one is alone, the easier it is to hear the song of the earth.&rdquo; <br /> &mdash;Robert Anton Wilson', '&ldquo;A garden must combine the poetic and the mysterious with a feeling of serenity and joy.&rdquo; <br /> &mdash;Luis Barragan', '&ldquo;Sunsets are so beautiful that they almost seem as if we were looking through the gates of Heaven.&rdquo; <br /> &mdash;John Lubbock', '&ldquo;The sky lovingly smiles on the earth and her children.&rdquo; <br /> &mdash;Henry Morton Stanley', '&ldquo;The sky broke like an egg into full sunset and the water caught fire.&rdquo; <br /> &mdash;Pamela Hansford Johnson', '&ldquo;During all these years there existed within me a tendency to follow Nature in her walks.&rdquo; <br /> &mdash;John James Audubon', '&ldquo;The sky is filled with stars, invisible by day.&rdquo; <br /> &mdash;Henry Wadsworth Longfellow', '&ldquo;Solitary trees, if they grow at all, grow strong.&rdquo; <br /> &mdash;Winston Churchill', '&ldquo;For the mind disturbed, the still beauty of dawn is nature&rsquo;s finest balm.&rdquo; <br /> &mdash;Edwin Way Teale', '&ldquo;The Lord grant we may all be tillers of the soil.&rdquo; <br /> &mdash;Nikolai Gogol', '&ldquo;Eagles commonly fly alone. They are crows, daws, and starlings that flock together.&rdquo; <br /> &mdash;John Webster', '&ldquo;The world is always in movement.&rdquo; <br /> &mdash;V. S. Naipaul', '&ldquo;Land is the secure ground of home, the sea is like life, the outside, the unknown.&rdquo; <br /> &mdash;Stephen Gardiner', '&ldquo;They are ill discoverers that think there is no land, when they can see nothing but sea.&rdquo; <br /> &mdash;Francis Bacon', '&ldquo;Twilight drops her curtain down, and pins it with a star.&rdquo; <br /> &mdash;Lucy Maud Montgomery', '&ldquo;Consider what each soil will bear, and what each refuses.&rdquo; <br /> &mdash;Virgil', '&ldquo;The Sun, Moon and Stars are there to guide us.&rdquo; <br /> &mdash;Dennis Banks', '&ldquo;Self-defence is Nature&rsquo;s eldest law.&rdquo; <br /> &mdash;John Dryden', '&ldquo;The stars that have most glory have no rest.&rdquo; <br /> &mdash;Samuel Daniel' ] let marchArray = [ '&ldquo;In the depth of winter I finally learned that there was in me an invincible summer.&rdquo; <br /> &mdash;Albert Camus', '&ldquo;It appears to be a law that you cannot have a deep sympathy with both man and nature.&rdquo; <br /> &mdash;Henry David Thoreau', '&ldquo;The poetry of the earth is never dead.&rdquo; <br /> &mdash;John Keats', '&ldquo;Big doesn&rsquo;t necessarily mean better. Sunflowers aren&rsquo;t better than violets.&rdquo; <br /> &mdash;Edna Ferber', '&ldquo;I believe a leaf of grass is no less than the journey-work of the stars.&rdquo; <br /> &mdash;Walt Whitman', '&ldquo;One touch of nature makes the whole world kin.&rdquo; <br /> &mdash;William Shakespeare', '&ldquo;Look deep into nature, and then you will understand everything better.&rdquo; <br /> &mdash;Albert Einstein', '&ldquo;Rebellion without truth is like spring in a bleak, arid desert.&rdquo; <br /> &mdash;Khalil Gibran', '&ldquo;This continent, an open palm spread frank before the sky.&rdquo; <br /> &mdash;James Agee', '&ldquo;The best place to find God is in a garden. You can dig for him there.&rdquo; <br /> &mdash;George Bernard Shaw', '&ldquo;Sound is the vocabulary of nature.&rdquo; <br /> &mdash;Pierre Schaeffer', '&ldquo;I believe in God, only I spell it Nature.&rdquo; <br /> &mdash;Frank Lloyd Wright', '&ldquo;The flower is the poetry of reproduction. It is an example of the eternal seductiveness of life.&rdquo; <br /> &mdash;Jean Giraudoux', '&ldquo;Blue thou art, intensely blue; Flower, whence came thy dazzling hue?&rdquo; <br /> &mdash;James Montgomery', '&ldquo;A forest bird never wants a cage.&rdquo; <br /> &mdash;Henrik Ibsen', '&ldquo;What nature delivers to us is never stale. Because what nature creates has eternity in it.&rdquo; <br /> &mdash;Isaac Bashevis Singer', '&ldquo;All theory, dear friend, is gray, but the golden tree of life springs ever green.&rdquo; <br /> &mdash;Johann Wolfgang von Goethe', '&ldquo;Words, like nature, half reveal and half conceal the soul within.&rdquo; <br /> &mdash;Alfred Lord Tennyson', '&ldquo;We must return to nature and nature&rsquo;s god.&rdquo; <br /> &mdash;Luther Burbank', '&ldquo;As the twig is bent the tree inclines.&rdquo; <br /> &mdash;Virgil', '&ldquo;Oaths are but words, and words are but wind.&rdquo; <br /> &mdash;Samuel Butler', '&ldquo;I believe I can even yet remember when I saw the stars for the first time.&rdquo; <br /> &mdash;Max Muller', '&ldquo;Art will never be able to exist without nature.&rdquo; <br /> &mdash;Pierre Bonnard', '&ldquo;The stars don&rsquo;t look bigger, but they do look brighter.&rdquo; <br /> &mdash;Sally Ride', '&ldquo;Strangely enough, they have a mind to till the soil, and the love of possessions is a disease in them.&rdquo; <br /> &mdash;Sitting Bull', '&ldquo;The continued existence of wildlife and wilderness is important to the quality of life of humans.&rdquo; <br /> &mdash;Jim Fowler', '&ldquo;I learn something every time I go into the mountains.&rdquo; <br /> &mdash;Michael Kennedy', '&ldquo;Water and air, the two essential fluids on which all life depends, have become global garbage cans.&rdquo; <br /> &mdash;Jacques Yves Cousteau', '&ldquo;Miracles are not contrary to nature, but only contrary to what we know about nature.&rdquo; <br /> &mdash;Saint Augustine', '&ldquo;The very winds whispered in soothing accents, and maternal Nature bade me weep no more.&rdquo; <br /> &mdash;Mary Shelley', '&ldquo;We are learning, too, that the love of beauty is one of Nature&rsquo;s greatest healers.&rdquo; <br /> &mdash;Ellsworth Huntington' ] let aprilArray = [ '&ldquo;It is not only fine feathers that make fine birds.&rdquo; <br /> &mdash;Aesop', '&ldquo;What would be ugly in a garden constitutes beauty in a mountain.&rdquo; <br /> &mdash;Victor Hugo', '&ldquo;Set your course by the stars, not by the lights of every passing ship.&rdquo; <br /> &mdash;Omar N. Bradley', '&ldquo;With the coming of spring, I am calm again.&rdquo; <br /> &mdash;Gustav Mahler', '&ldquo;The sea complains upon a thousand shores.&rdquo; <br /> &mdash;Alexander Smith', '&ldquo;The best thing one can do when it&rsquo;s raining is to let it rain.&rdquo; <br /> &mdash;Henry Wadsworth Longfellow', '&ldquo;Heaven is under our feet as well as over our heads.&rdquo; <br /> &mdash;Henry David Thoreau', '&ldquo;The fulness of the godhead dwelt in every blade of grass.&rdquo; <br /> &mdash;Elias Hicks', '&ldquo;Great men are like eagles, and build their nest on some lofty solitude.&rdquo; <br /> &mdash;Arthur Schopenhauer', '&ldquo;A hen is only an egg&rsquo;s way of making another egg.&rdquo; <br /> &mdash;Samuel Butler', '&ldquo;God writes the Gospel not in the Bible alone, but also on trees, and in the flowers and clouds and stars.&rdquo; <br /> &mdash;Martin Luther', '&ldquo;To destroy is still the strongest instinct in nature.&rdquo; <br /> &mdash;Max Beerbohm', '&ldquo;If people sat outside and looked at the stars each night, I&rsquo;ll bet they&rsquo;d live a lot differently.&rdquo; <br /> &mdash;Bill Watterson', '&ldquo;We are an impossibility in an impossible universe.&rdquo; <br /> &mdash;Ray Bradbury', '&ldquo;No occupation is so delightful to me as the culture of the earth, and no culture comparable to that of the garden.&rdquo; <br /> &mdash;Thomas Jefferson', '&ldquo;Conservation is a state of harmony between men and land.&rdquo; <br /> &mdash;Aldo Leopold', '&ldquo;Nature is often hidden, sometimes overcome, seldom extinguished.&rdquo; <br /> &mdash;Francis Bacon', '&ldquo;There are no lines in nature, only areas of colour, one against another.&rdquo; <br /> &mdash;Edouard Manet', '&ldquo;God, I can push the grass apart and lay my finger on Thy heart.&rdquo; <br /> &mdash;Edna St. Vincent Millay', '&ldquo;I have always wanted a bunny and I&rsquo;ll always have a rabbit the rest of my life.&rdquo; <br /> &mdash;Amy Sedaris', '&ldquo;I&rsquo;ve always regarded nature as the clothing of God.&rdquo; <br /> &mdash;Alan Hovhaness', '&ldquo;Scenery is fine &ndash; but human nature is finer.&rdquo; <br /> &mdash;John Keats', '&ldquo;The sun, too, shines into cesspools and is not polluted.&rdquo; <br /> &mdash;Diogenes', '&ldquo;In the world of words, the imagination is one of the forces of nature.&rdquo; <br /> &mdash;Wallace Stevens', '&ldquo;Nature does not hurry, yet everything is accomplished.&rdquo; <br /> &mdash;Lao Tzu', '&ldquo;Let every dawn be to you as the beginning of life, and every setting sun be to you as its close.&rdquo; <br /> &mdash;John Ruskin', '&ldquo;The fairest thing in nature, a flower, still has its roots in earth and manure.&rdquo; <br /> &mdash;D. H. Lawrence', '&ldquo;He who does not become familiar with nature through love will never know her.&rdquo; <br /> &mdash;Karl Wilhelm Friedrich Schlegel', '&ldquo;Buildings, too, are children of Earth and Sun.&rdquo; <br /> &mdash;Frank Lloyd Wright', '&ldquo;Life is a great sunrise. I do not see why death should not be an even greater one.&rdquo; <br /> &mdash;Vladimir Nabokov' ] let mayArray = [ '&ldquo;You can cut all the flowers but you cannot keep spring from coming.&rdquo; <br /> &mdash;Pablo Neruda', '&ldquo;Self-preservation is the first law of nature.&rdquo; <br /> &mdash;Samuel Butler', '&ldquo;Human judges can show mercy. But against the laws of nature, there is no appeal.&rdquo; <br /> &mdash;Arthur C. Clarke', '&ldquo;The earth is the very quintessence of the human condition.&rdquo; <br /> &mdash;Hannah Arendt', '&ldquo;The supernatural is the natural not yet understood.&rdquo; <br /> &mdash;Elbert Hubbard', '&ldquo;&lsquo;Healing,&rsquo; Papa would tell me, &lsquo;is not a science, but the intuitive art of wooing nature.&rsquo;&rdquo; <br /> &mdash;W. H. Auden', '&ldquo;If your knees aren&rsquo;t green by the end of the day, you ought to seriously re-examine your life.&rdquo; <br /> &mdash;Bill Watterson', '&ldquo;Earth is a flower and it&rsquo;s pollinating.&rdquo; <br /> &mdash;Neil Young', '&ldquo;In all things of nature there is something of the marvelous.&rdquo; <br /> &mdash;Aristotle', '&ldquo;Adopt the pace of nature: her secret is patience.&rdquo; <br /> &mdash;Ralph Waldo Emerson', '&ldquo;The violets in the mountains have broken the rocks.&rdquo; <br /> &mdash;Tennessee Williams', '&ldquo;Night comes to the desert all at once, as if someone turned off the light.&rdquo; <br /> &mdash;Joyce Carol Oates', '&ldquo;In search of my mother&rsquo;s garden, I found my own.&rdquo; <br /> &mdash;Alice Walker', '&ldquo;Use plants to bring life.&rdquo; <br /> &mdash;Douglas Wilson', '&ldquo;Shadow owes its birth to light.&rdquo; <br /> &mdash;John Gay', '&ldquo;A good garden may have some weeds.&rdquo; <br /> &mdash;Thomas Fuller', '&ldquo;Literature and butterflies are the two sweetest passions known to man.&rdquo; <br /> &mdash;Vladimir Nabokov', '&ldquo;Nature is not human hearted.&rdquo; <br /> &mdash;Lao Tzu', '&ldquo;Sweet April showers do spring May flowers.&rdquo; <br /> &mdash;Thomas Tusser', '&ldquo;The foot feels the foot when it feels the ground.&rdquo; <br /> &mdash;Buddha', '&ldquo;Nature is inside art as its content, not outside as its model.&rdquo; <br /> &mdash;Marilyn French', '&ldquo;Spring beckons! All things to the call respond; the trees are leaving and cashiers abscond.&rdquo; <br /> &mdash;Ambrose Bierce', '&ldquo;Nature uses as little as possible of anything.&rdquo; <br /> &mdash;Johannes Kepler', '&ldquo;There were no temples or shrines among us save those of nature.&rdquo; <br /> &mdash;Charles Eastman', '&ldquo;Nature never makes any blunders, when she makes a fool she means it.&rdquo; <br /> &mdash;Archibald Alexander', '&ldquo;Nothing leads to good that is not natural.&rdquo; <br /> &mdash;Friedrich Schiller', '&ldquo;My soul can find no staircase to Heaven unless it be through Earth&rsquo;s loveliness.&rdquo; <br /> &mdash;Michelangelo', '&ldquo;Life comes from the earth and life returns to the earth.&rdquo; <br /> &mdash;Zhuangzi', '&ldquo;One could not pluck a flower without troubling a star.&rdquo; <br /> &mdash;Loren Eiseley', '&ldquo;Don&rsquo;t pray when it rains if you don&rsquo;t pray when the sun shines.&rdquo; <br /> &mdash;Satchel Paige', '&ldquo;Flowers are happy things.&rdquo; <br /> &mdash;P. G. Wodehouse' ] let juneArray = [ '&ldquo;All things are artificial, for nature is the art of God.&rdquo; <br /> &mdash;Thomas Browne', '&ldquo;A morning-glory at my window satisfies me more than the metaphysics of books.&rdquo; <br /> &mdash;Walt Whitman', '&ldquo;The eye of a human being is a microscope, which makes the world seem bigger than it really is.&rdquo; <br /> &mdash;Khalil Gibran', '&ldquo;In the presence of eternity, the mountains are as transient as the clouds.&rdquo; <br /> &mdash;Robert Green Ingersoll', '&ldquo;Never does nature say one thing and wisdom another.&rdquo; <br /> &mdash;Juvenal', '&ldquo;Swans sing before they die &ndash; &lsquo;twere no bad thing should certain persons die before they sing.&rdquo; <br /> &mdash;Samuel Taylor Coleridge', '&ldquo;Let the rain kiss you. Let the rain beat upon your head with silver liquid drops. Let the rain sing you a lullaby.&rdquo; <br /> &mdash;Langston Hughes', '&ldquo;If the path be beautiful, let us not ask where it leads.&rdquo; <br /> &mdash;Anatole France', '&ldquo;Plans to protect air and water, wilderness and wildlife are in fact plans to protect man.&rdquo; <br /> &mdash;Stewart Udall', '&ldquo;You cannot step into the same river twice.&rdquo; <br /> &mdash;Heraclitus', '&ldquo;I am following Nature without being able to grasp her, I perhaps owe having become a painter to flowers.&rdquo; <br /> &mdash;Claude Monet', '&ldquo;Poetry is the synthesis of hyacinths and biscuits.&rdquo; <br /> &mdash;Carl Sandburg', '&ldquo;How strange that nature does not knock, and yet does not intrude!&rdquo; <br /> &mdash;Emily Dickinson', '&ldquo;The groves were God&rsquo;s first temples.&rdquo; <br /> &mdash;William Cullen Bryant', '&ldquo;Great things are done when men and mountains meet.&rdquo; <br /> &mdash;William Blake', '&ldquo;My father considered a walk among the mountains as the equivalent of churchgoing.&rdquo; <br /> &mdash;Aldous Huxley', '&ldquo;The sky is the part of creation in which nature has done for the sake of pleasing man.&rdquo; <br /> &mdash;John Ruskin', '&ldquo;The lake and the mountains have become my landscape, my real world.&rdquo; <br /> &mdash;Georges Simenon', '&ldquo;There are no passengers on spaceship earth. We are all crew.&rdquo; <br /> &mdash;Marshall McLuhan', '&ldquo;What a man needs in gardening is a cast-iron back, with a hinge in it.&rdquo; <br /> &mdash;Charles Dudley Warner', '&ldquo;Study nature, love nature, stay close to nature. It will never fail you.&rdquo; <br /> &mdash;Frank Lloyd Wright', '&ldquo;I only ask to be free. The butterflies are free.&rdquo; <br /> &mdash;Charles Dickens', '&ldquo;If I had to choose a religion, the sun as the universal giver of life would be my god.&rdquo; <br /> &mdash;Napoleon Bonaparte', '&ldquo;Heaven lent you a soul, Earth will lend a grave.&rdquo; <br /> &mdash;Christian Nestell Bovee', '&ldquo;And out of darkness came the hands that reach thro&rsquo; nature, moulding men.&rdquo; <br /> &mdash;Alfred Lord Tennyson', '&ldquo;Fishes live in the sea, as men do a-land; the great ones eat up the little ones.&rdquo; <br /> &mdash;William Shakespeare', '&ldquo;If you would know strength and patience, welcome the company of trees.&rdquo; <br /> &mdash;Hal Borland', '&ldquo;The temple bell stops but I still hear the sound coming out of the flowers.&rdquo; <br /> &mdash;Matsuo Basho', '&ldquo;Flowers are the sweetest things God ever made and forgot to put a soul into.&rdquo; <br /> &mdash;Henry Ward Beecher', '&ldquo;Won&rsquo;t you come into the garden? I would like my roses to see you.&rdquo; <br /> &mdash;Richard Brinsley Sheridan' ] let julyArray = [ '&ldquo;Pity the meek, for they shall inherit the earth.&rdquo; <br /> &mdash;Don Marquis', '&ldquo;Nature, like man, sometimes weeps from gladness.&rdquo; <br /> &mdash;Benjamin Disraeli', '&ldquo;Go forth under the open sky, and list To Nature&rsquo;s teachings.&rdquo; <br /> &mdash;William Cullen Bryant', '&ldquo;To make us love our country, our country ought to be lovely.&rdquo; <br /> &mdash;Edmund Burke', '&ldquo;Oh, the summer night, Has a smile of light, And she sits on a sapphire throne.&rdquo; <br /> &mdash;Bryan Procter', '&ldquo;The Dove, on silver pinions, winged her peaceful way.&rdquo; <br /> &mdash;James Montgomery', '&ldquo;Clouds symbolize the veils that shroud God.&rdquo; <br /> &mdash;Honore de Balzac', '&ldquo;But friendship is the breathing rose, with sweets in every fold.&rdquo; <br /> &mdash;Oliver Wendell Holmes, Sr.', '&ldquo;Nature&rsquo;s far too subtle to repeat herself.&rdquo; <br /> &mdash;Paul Muni', '&ldquo;If one way be better than another, that you may be sure is nature&rsquo;s way.&rdquo; <br /> &mdash;Aristotle', '&ldquo;Mere goodness can achieve little against the power of nature.&rdquo; <br /> &mdash;Georg Wilhelm Friedrich Hegel', '&ldquo;Death is the ugly fact which Nature has to hide, and she hides it well.&rdquo; <br /> &mdash;Alexander Smith', '&ldquo;We sit in the mud&hellip; and reach for the stars.&rdquo; <br /> &mdash;Ivan Turgenev', '&ldquo;Weeds are flowers too, once you get to know them.&rdquo; <br /> &mdash;A. A. Milne', '&ldquo;Against her ankles as she trod The lucky buttercups did nod.&rdquo; <br /> &mdash;Jean Ingelow', '&ldquo;I had to live in the desert before I could understand the full value of grass in a green ditch.&rdquo; <br /> &mdash;Ella Maillart', '&ldquo;Nature is something outside our body, but the mind is within us.&rdquo; <br /> &mdash;Bhumibol Adulyadej', '&ldquo;Be truthful, nature only sides with truth.&rdquo; <br /> &mdash;Adolf Loos', '&ldquo;If the stars should appear but one night every thousand years how man would marvel and stare.&rdquo; <br /> &mdash;Ralph Waldo Emerson', '&ldquo;All the universe is full of the lives of perfect creatures.&rdquo; <br /> &mdash;Konstantin Tsiolkovsky', '&ldquo;Nature is an infinite sphere of which the center is everywhere and the circumference nowhere.&rdquo; <br /> &mdash;Blaise Pascal', '&ldquo;There is the sky, which is all men&rsquo;s together.&rdquo; <br /> &mdash;Euripides', '&ldquo;Show me your garden and I shall tell you what you are.&rdquo; <br /> &mdash;Alfred Austin', '&ldquo;What we observe is not nature itself, but nature exposed to our method of questioning.&rdquo; <br /> &mdash;Werner Heisenberg', '&ldquo;Where hast thou wandered, gentle gale, to find the perfumes thou dost bring?&rdquo; <br /> &mdash;William Cullen Bryant', '&ldquo;Flowers grow out of dark moments.&rdquo; <br /> &mdash;Corita Kent', '&ldquo;Don&rsquo;t tell me the moon is shining; show me the glint of light on broken glass.&rdquo; <br /> &mdash;Anton Chekhov', '&ldquo;Time will pass and seasons will come and go.&rdquo; <br /> &mdash;Roy Bean', '&ldquo;Ah, summer, what power you have to make us suffer and like it.&rdquo; <br /> &mdash;Russell Baker', '&ldquo;In nature there are few sharp lines.&rdquo; <br /> &mdash;A. R. Ammons', '&ldquo;Hey sky, take off your hat, I&rsquo;m on my way!&rdquo; <br /> &mdash;Valentina Tereshkova' ] let augustArray = [ '&ldquo;Trees are the earth&rsquo;s endless effort to speak to the listening heaven.&rdquo; <br /> &mdash;Rabindranath Tagore', '&ldquo;We cannot command Nature except by obeying her.&rdquo; <br /> &mdash;Francis Bacon', '&ldquo;Give me odorous at sunrise a garden of beautiful flowers where I can walk undisturbed.&rdquo; <br /> &mdash;Walt Whitman', '&ldquo;There are a thousand hacking at the branches of evil to one who is striking at the root.&rdquo; <br /> &mdash;Henry David Thoreau', '&ldquo;When I have a terrible need of &ndash; shall I say the word &ndash; religion. Then I go out and paint the stars.&rdquo; <br /> &mdash;Vincent Van Gogh', '&ldquo;I love not man the less, but Nature more.&rdquo; <br /> &mdash;Lord Byron', '&ldquo;To sit in the shade on a fine day and look upon verdure is the most perfect refreshment.&rdquo; <br /> &mdash;Jane Austen', '&ldquo;Sadness is but a wall between two gardens.&rdquo; <br /> &mdash;Khalil Gibran', '&ldquo;However much you knock at nature&rsquo;s door, she will never answer you in comprehensible words.&rdquo; <br /> &mdash;Ivan Turgenev', '&ldquo;Nature provides exceptions to every rule.&rdquo; <br /> &mdash;Margaret Fuller', '&ldquo;The flower that smells the sweetest is shy and lowly.&rdquo; <br /> &mdash;William Wordsworth', '&ldquo;Disease is the retribution of outraged Nature.&rdquo; <br /> &mdash;Hosea Ballou', '&ldquo;Nature is the master of talents; genius is the master of nature.&rdquo; <br /> &mdash;Josiah Gilbert Holland', '&ldquo;Nature is indifferent to the survival of the human species, including Americans.&rdquo; <br /> &mdash;Adlai Stevenson I', '&ldquo;The old cathedrals are good, but the great blue dome that hangs over everything is better.&rdquo; <br /> &mdash;Thomas Carlyle', '&ldquo;What would be left of our tragedies if an insect were to present us his?&rdquo; <br /> &mdash;Emil Cioran', '&ldquo;I know the joy of fishes in the river through my own joy, as I go walking along the same river.&rdquo; <br /> &mdash;Zhuangzi', '&ldquo;Nature uses human imagination to lift her work of creation to even higher levels.&rdquo; <br /> &mdash;Luigi Pirandello', '&ldquo;A lawn is nature under totalitarian rule.&rdquo; <br /> &mdash;Michael Pollan', '&ldquo;If the skies fall, one may hope to catch larks.&rdquo; <br /> &mdash;Francois Rabelais', '&ldquo;A brier rose whose buds yield fragrant harvest for the honey bee.&rdquo; <br /> &mdash;Letitia Elizabeth Landon', '&ldquo;Trees love to toss and sway; they make such happy noises.&rdquo; <br /> &mdash;Emily Carr', '&ldquo;When sparrows build and the leaves break forth, My old sorrow wakes and cries.&rdquo; <br /> &mdash;Jean Ingelow', '&ldquo;Nature hasn&rsquo;t gone anywhere. It is all around us, all the planets, galaxies and so on. We are nothing in comparison.&rdquo; <br /> &mdash;Bjork', '&ldquo;Blue, green, grey, white, or black; smooth, ruffled, or mountainous; that ocean is not silent.&rdquo; <br /> &mdash;H. P. Lovecraft', '&ldquo;Sadly, it&rsquo;s much easier to create a desert than a forest.&rdquo; <br /> &mdash;James Lovelock', '&ldquo;Nature was my kindergarten.&rdquo; <br /> &mdash;William Christopher Handy', '&ldquo;Who loves a garden loves a greenhouse too.&rdquo; <br /> &mdash;William Cowper', '&ldquo;Any landscape is a condition of the spirit.&rdquo; <br /> &mdash;Henri Frederic Amiel', '&ldquo;There is no forgiveness in nature.&rdquo; <br /> &mdash;Ugo Betti', '&ldquo;Without poets, without artists, men would soon weary of nature&rsquo;s monotony.&rdquo; <br /> &mdash;Guillaume Apollinaire' ] let septemberArray = [ '&ldquo;I would rather sit on a pumpkin and have it all to myself, than be crowded on a velvet cushion.&rdquo; <br /> &mdash;Henry David Thoreau', '&ldquo;Perhaps the truth depends on a walk around the lake.&rdquo; <br /> &mdash;Wallace Stevens', '&ldquo;The Amen of nature is always a flower.&rdquo; <br /> &mdash;Oliver Wendell Holmes, Sr.', '&ldquo;Nature&rsquo;s music is never over; her silences are pauses, not conclusions.&rdquo; <br /> &mdash;Mary Webb', '&ldquo;Nature never did betray the heart that loved her.&rdquo; <br /> &mdash;William Wordsworth', '&ldquo;You&rsquo;re only here for a short visit. Don&rsquo;t hurry, don&rsquo;t worry. And be sure to smell the flowers along the way.&rdquo; <br /> &mdash;Walter Hagen', '&ldquo;Clouds come floating into my life, no longer to carry rain or usher storm, but to add color to my sunset sky.&rdquo; <br /> &mdash;Rabindranath Tagore', '&ldquo;The winds and the waves are always on the side of the ablest navigators.&rdquo; <br /> &mdash;Edward Gibbon', '&ldquo;Too low they build, who build beneath the stars.&rdquo; <br /> &mdash;Edward Young', '&ldquo;We are embedded in a biological world and related to the organisms around us.&rdquo; <br /> &mdash;Walter Gilbert', '&ldquo;Moonlight is sculpture.&rdquo; <br /> &mdash;Nathaniel Hawthorne', '&ldquo;Adapt or perish, now as ever, is nature&rsquo;s inexorable imperative.&rdquo; <br /> &mdash;H. G. Wells', '&ldquo;When you have seen one ant, one bird, one tree, you have not seen them all.&rdquo; <br /> &mdash;E. O. Wilson', '&ldquo;Water, air, and cleanness are the chief articles in my pharmacy.&rdquo; <br /> &mdash;Napoleon Bonaparte', '&ldquo;It is only in the country that we can get to know a person or a book.&rdquo; <br /> &mdash;Cyril Connolly', '&ldquo;The world is mud-luscious and puddle-wonderful.&rdquo; <br /> &mdash;e. e. cummings', '&ldquo;The subtlety of nature is greater many times over than the subtlety of the senses and understanding.&rdquo; <br /> &mdash;Francis Bacon', '&ldquo;Unless a tree has borne blossoms in spring, you will vainly look for fruit on it in autumn.&rdquo; <br /> &mdash;Walter Scott', '&ldquo;The moon looks upon many night flowers; the night flowers see but one moon.&rdquo; <br /> &mdash;Jean Ingelow', '&ldquo;Some people are always grumbling because roses have thorns; I am thankful that thorns have roses.&rdquo; <br /> &mdash;Alphonse Karr', '&ldquo;There is not a sprig of grass that shoots uninteresting to me.&rdquo; <br /> &mdash;Thomas Jefferson', '&ldquo;No man can taste the fruits of autumn while he is delighting his scent with the flowers of spring.&rdquo; <br /> &mdash;Samuel Johnson', '&ldquo;The good man is the friend of all living things.&rdquo; <br /> &mdash;Mahatma Gandhi', '&ldquo;Autumn is my favorite season.&rdquo; <br /> &mdash;Johnny Kelly', '&ldquo;Nature knows no pause in progress and development, and attaches her curse on all inaction.&rdquo; <br /> &mdash;Johann Wolfgang von Goethe', '&ldquo;Happiness is the natural flower of duty.&rdquo; <br /> &mdash;Phillips Brooks', '&ldquo;God sleeps in the minerals, awakens in plants, walks in animals, and thinks in man.&rdquo; <br /> &mdash;Arthur Young', '&ldquo;If I had to choose, I would rather have birds than airplanes.&rdquo; <br /> &mdash;Charles Lindbergh', '&ldquo;In nature there are neither rewards nor punishments; there are consequences.&rdquo; <br /> &mdash;Robert Green Ingersoll', '&ldquo;Autumn&rsquo;s the mellow time.&rdquo; <br /> &mdash;William Allingham' ] let octoberArray = [ '&ldquo;Nothing is farther than earth from heaven; nothing is nearer than heaven to earth.&rdquo; <br /> &mdash;Augustus Hare', '&ldquo;How inappropriate to call this planet Earth when it is quite clearly Ocean.&rdquo; <br /> &mdash;Arthur C. Clarke', '&ldquo;Keep your face always toward the sunshine &ndash; and shadows will fall behind you.&rdquo; <br /> &mdash;Walt Whitman', '&ldquo;The bluebird carries the sky on his back.&rdquo; <br /> &mdash;Henry David Thoreau', '&ldquo;I drank the silence of God from a spring in the woods.&rdquo; <br /> &mdash;Georg Trakl', '&ldquo;The love of gardening is a seed once sown that never dies.&rdquo; <br /> &mdash;Gertrude Jekyll', '&ldquo;There&rsquo;s something about taking a plow and breaking new ground. It gives you energy.&rdquo; <br /> &mdash;Ken Kesey', '&ldquo;The earth is the mother of all people, and all people should have equal rights upon it.&rdquo; <br /> &mdash;Chief Joseph', '&ldquo;If nature offers no home, then we must make a home one way or another. The only question is how.&rdquo; <br /> &mdash;John Burnside', '&ldquo;No spring nor summer beauty hath such grace as I have seen in one autumnal face.&rdquo; <br /> &mdash;John Donne', '&ldquo;Human life is as evanescent as the morning dew or a flash of lightning.&rdquo; <br /> &mdash;Samuel Butler', '&ldquo;We forget that the water cycle and the life cycle are one.&rdquo; <br /> &mdash;Jacques Yves Cousteau', '&ldquo;I&rsquo;m very gregarious, but I love being in the hills on my own.&rdquo; <br /> &mdash;Norman MacCaig', '&ldquo;Man is a creative retrospection of nature upon itself.&rdquo; <br /> &mdash;Karl Wilhelm Friedrich Schlegel', '&ldquo;And when I breathed, my breath was lightning.&rdquo; <br /> &mdash;Black Elk', '&ldquo;Nature is the art of God.&rdquo; <br /> &mdash;Dante Alighieri', '&ldquo;A weed is but an unloved flower.&rdquo; <br /> &mdash;Ella Wheeler Wilcox', '&ldquo;Countless as the sands of the sea are human passions.&rdquo; <br /> &mdash;Nikolai Gogol', '&ldquo;Miracles do not, in fact, break the laws of nature.&rdquo; <br /> &mdash;C. S. Lewis', '&ldquo;Nature&hellip; is nothing but the inner voice of self-interest.&rdquo; <br /> &mdash;Charles Baudelaire', '&ldquo;Energy, like the biblical grain of the mustard-seed, will remove mountains.&rdquo; <br /> &mdash;Hosea Ballou', '&ldquo;We still do not know one thousandth of one percent of what nature has revealed to us.&rdquo; <br /> &mdash;Albert Einstein', '&ldquo;Rose is a rose is a rose is a rose.&rdquo; <br /> &mdash;Gertrude Stein', '&ldquo;I can find God in nature, in animals, in birds and the environment.&rdquo; <br /> &mdash;Pat Buckley', '&ldquo;The sea has neither meaning nor pity.&rdquo; <br /> &mdash;Anton Chekhov', '&ldquo;Wilderness is not a luxury but a necessity of the human spirit.&rdquo; <br /> &mdash;Edward Abbey', '&ldquo;You forget that the fruits belong to all and that the land belongs to no one.&rdquo; <br /> &mdash;Jean-Jacques Rousseau', '&ldquo;Without the oceans there would be no life on Earth.&rdquo; <br /> &mdash;Peter Benchley', '&ldquo;But more wonderful than the lore of old men and the lore of books is the secret lore of ocean.&rdquo; <br /> &mdash;H. P. Lovecraft', '&ldquo;The man who interprets Nature is always held in great honor.&rdquo; <br /> &mdash;Zora Neale Hurston', '&ldquo;I have seen the movement of the sinews of the sky, And the blood coursing in the veins of the moon.&rdquo; <br /> &mdash;Muhammad Iqbal' ] let novemberArray = [ '&ldquo;I know the lands are lit, with all the autumn blaze of Goldenrod.&rdquo; <br /> &mdash;Helen Hunt Jackson', '&ldquo;The tree that is beside the running water is fresher and gives more fruit.&rdquo; <br /> &mdash;Saint Teresa of Avila', '&ldquo;Nature does nothing in vain.&rdquo; <br /> &mdash;Aristotle', '&ldquo;The breaking of a wave cannot explain the whole sea.&rdquo; <br /> &mdash;Vladimir Nabokov', '&ldquo;Oh, don&rsquo;t let&rsquo;s ask for the moon. We&rsquo;ve already got the stars.&rdquo; <br /> &mdash;Bette Davis', '&ldquo;The Earth is the cradle of humanity, but mankind cannot stay in the cradle forever.&rdquo; <br /> &mdash;Konstantin Tsiolkovsky', '&ldquo;If man doesn&rsquo;t learn to treat the oceans and the rain forest with respect, man will become extinct.&rdquo; <br /> &mdash;Peter Benchley', '&ldquo;Read nature; nature is a friend to truth.&rdquo; <br /> &mdash;Edward Young', '&ldquo;All nature wears one universal grin.&rdquo; <br /> &mdash;Henry Fielding', '&ldquo;America forms the longest and straightest bone in the earth&rsquo;s skeleton.&rdquo; <br /> &mdash;Ellsworth Huntington', '&ldquo;Today&rsquo;s mighty oak is just yesterday&rsquo;s nut, that held its ground.&rdquo; <br /> &mdash;David Icke', '&ldquo;Nature is never finished.&rdquo; <br /> &mdash;Robert Smithson', '&ldquo;The view of Earth is spectacular.&rdquo; <br /> &mdash;Sally Ride', '&ldquo;Everything in excess is opposed to nature.&rdquo; <br /> &mdash;Hippocrates', '&ldquo;If you have a garden and a library, you have everything you need.&rdquo; <br /> &mdash;Marcus Tullius Cicero', '&ldquo;I saw old Autumn in the misty morn stand shadowless like silence, listening to silence.&rdquo; <br /> &mdash;Thomas Hood', '&ldquo;Now Autumn&rsquo;s fire burns slowly along the woods and day by day the dead leaves fall and melt.&rdquo; <br /> &mdash;William Allingham', '&ldquo;Behind every cloud is another cloud.&rdquo; <br /> &mdash;Judy Garland', '&ldquo;Ye stars! which are the poetry of heaven!&rdquo; <br /> &mdash;Lord Byron', '&ldquo;A light wind swept over the corn, and all nature laughed in the sunshine.&rdquo; <br /> &mdash;Anne Bronte', '&ldquo;All nature is but art unknown to thee.&rdquo; <br /> &mdash;Alexander Pope', '&ldquo;Joy in looking and comprehending is nature&rsquo;s most beautiful gift.&rdquo; <br /> &mdash;Albert Einstein', '&ldquo;A bee is never as busy as it seems; it&rsquo;s just that it can&rsquo;t buzz any slower.&rdquo; <br /> &mdash;Kin Hubbard', '&ldquo;It is only the farmer who faithfully plants seeds in the Spring, who reaps a harvest in the Autumn.&rdquo; <br /> &mdash;B. C. Forbes', '&ldquo;We have the capacity to receive messages from the stars and the songs of the night winds.&rdquo; <br /> &mdash;Ruth St. Denis', '&ldquo;The ocean moans over dead men&rsquo;s bones.&rdquo; <br /> &mdash;Thomas Bailey Aldrich', '&ldquo;This sunlight linked me through the ages to that past consciousness.&rdquo; <br /> &mdash;Richard Jefferies', '&ldquo;Autumn arrives in early morning, but spring at the close of a winter day.&rdquo; <br /> &mdash;Elizabeth Bowen', '&ldquo;Water is the driving force of all nature.&rdquo; <br /> &mdash;Leonardo da Vinci', '&ldquo;The pine stays green in winter&hellip; wisdom in hardship.&rdquo; <br /> &mdash;Norman Douglas' ] let decemberArray = [ '&ldquo;Breathless, we flung us on a windy hill, Laughed in the sun, and kissed the lovely grass.&rdquo; <br /> &mdash;Rupert Brooke', '&ldquo;One must ask children and birds how cherries and strawberries taste.&rdquo; <br /> &mdash;Johann Wolfgang von Goethe', '&ldquo;Come forth into the light of things, let nature be your teacher.&rdquo; <br /> &mdash;William Wordsworth', '&ldquo;The progress of rivers to the ocean is not so rapid as that of man to error.&rdquo; <br /> &mdash;Voltaire', '&ldquo;Curiosity is the one thing invincible in Nature.&rdquo; <br /> &mdash;Freya Stark', '&ldquo;Mountains are earth&rsquo;s undecaying monuments.&rdquo; <br /> &mdash;Nathaniel Hawthorne', '&ldquo;No snowflake in an avalanche ever feels responsible.&rdquo; <br /> &mdash;Stanislaw Jerzy Lec', '&ldquo;Nature is a petrified magic city.&rdquo; <br /> &mdash;Novalis', '&ldquo;Vegetation is the basic instrument the creator uses to set all of nature in motion.&rdquo; <br /> &mdash;Antoine Lavoisier', '&ldquo;Eagles come in all shapes and sizes, but you will recognize them chiefly by their attitudes.&rdquo; <br /> &mdash;E. F. Schumacher', '&ldquo;When nature has work to be done, she creates a genius to do it.&rdquo; <br /> &mdash;Ralph Waldo Emerson', '&ldquo;When you go in search of honey you must expect to be stung by bees.&rdquo; <br /> &mdash;Joseph Joubert', '&ldquo;We live in the world when we love it.&rdquo; <br /> &mdash;Rabindranath Tagore', '&ldquo;Nature can do more than physicians.&rdquo; <br /> &mdash;Oliver Cromwell', '&ldquo;Nature, to be commanded, must be obeyed.&rdquo; <br /> &mdash;Francis Bacon', '&ldquo;Colors are the smiles of nature.&rdquo; <br /> &mdash;Leigh Hunt', '&ldquo;Knowing trees, I understand the meaning of patience. Knowing grass, I can appreciate persistence.&rdquo; <br /> &mdash;Hal Borland', '&ldquo;We build statues out of snow, and weep to see them melt.&rdquo; <br /> &mdash;Walter Scott', '&ldquo;And finally Winter, with its bitin&rsquo;, whinin&rsquo; wind, and all the land will be mantled with snow.&rdquo; <br /> &mdash;Roy Bean', '&ldquo;How beautiful the leaves grow old. How full of light and color are their last days.&rdquo; <br /> &mdash;John Burroughs', '&ldquo;Coming from Chicago, I like a white Christmas.&rdquo; <br /> &mdash;Dennis Franz', '&ldquo;Nature never deceives us; it is we who deceive ourselves.&rdquo; <br /> &mdash;Jean-Jacques Rousseau', '&ldquo;Remember that children, marriages, and flower gardens reflect the kind of care they get.&rdquo; <br /> &mdash;H. Jackson Brown, Jr.', '&ldquo;In seed time learn, in harvest teach, in winter enjoy.&rdquo; <br /> &mdash;William Blake', '&ldquo;God gave us memory so that we might have roses in December.&rdquo; <br /> &mdash;James M. Barrie', '&ldquo;He is richest who is content with the least, for content is the wealth of nature.&rdquo; <br /> &mdash;Socrates', '&ldquo;Nature was here a series of wonders, and a fund of delight.&rdquo; <br /> &mdash;Daniel Boone', '&ldquo;We do not see nature with our eyes, but with our understandings and our hearts.&rdquo; <br /> &mdash;William Hazlitt', '&ldquo;Let us permit nature to have her way. She understands her business better than we do.&rdquo; <br /> &mdash;Michel de Montaigne', '&ldquo;Over every mountain there is a path, although it may not be seen from the valley.&rdquo; <br /> &mdash;Theodore Roethke', '&ldquo;The sun does not shine for a few trees and flowers, but for the wide world&rsquo;s joy.&rdquo; <br /> &mdash;Henry Ward Beecher' ] let date = new Date() let month = date.getMonth() let monthArray = [] if (month === 0) { monthArray = januaryArray } else if (month === 1) { monthArray = februaryArray } else if (month === 2) { monthArray = marchArray } else if (month === 3) { monthArray = aprilArray } else if (month === 4) { monthArray = mayArray } else if (month === 5) { monthArray = juneArray } else if (month === 6) { monthArray = julyArray } else if (month === 7) { monthArray = augustArray } else if (month === 8) { monthArray = septemberArray } else if (month === 9) { monthArray = octoberArray } else if (month === 10) { monthArray = novemberArray } else if (month === 11) { monthArray = decemberArray } let dayOfMonth = date.getDate() let natureQuote = monthArray[dayOfMonth - 1] let nature = `<h3>${natureQuote}</h3>` $('#nature').html(nature) })
Python
UTF-8
290
2.5625
3
[]
no_license
import cPickle import sys if __name__ == '__main__': nodes = dict() with open(sys.argv[1]) as IN: IN.readline() for line in IN: nodes[line.strip().split(' ')[0]] = 1 with open(sys.argv[2]) as IN: IN.readline() for line in IN: assert(line.strip().split(' ')[0] in nodes)
Markdown
UTF-8
1,879
2.953125
3
[]
no_license
####form 优点 1. 自动提交表单 2. 回车键绑定 3. 数据获取更轻松 ``` <div> <input id="user" /> <input id="password" /> </div> jQ 获取对应值的方式 $('user').val() ///这个看着挺简单的,但是性能损耗比较大 ///form方式的解决方案 <form id="regist"> <input id="user" /> <input id="password" /> </form> var form = document.forms.namedItem('regist') //document.getElementById('regist') <script> var form = document.forms.namedItem('regist') form['user'].oninput = function(){ console.log(this.value)///当value不存在时返回undefined } </script> ``` ##自动获取表单元素的函数 ``` <form action="" id="reg"> <input type="text" name="uname" id="user"> <input type="text" name="password" id="password"> </form> <script> ////表单的name值一定要有,否则没有数据 var form = document.forms.namedItem('reg') $.fn.serializeForm = function(){ let o = {}, a = this.serializeArray() $.each(a,function(){ if(o[this.name]!==undefined){ if(!o[this.name].push){ o[this.name] = [o[this.name]] } o[this.name].push(this.value || '') } else { o[this.name] = this.value || '' } }) return o; } form['user'].oninput = function(){ // console.log(this.value) console.log($('#reg').serializeArray()) console.log($('#reg').serializeForm()) // $('#reg').serializeForm() } </script> ```
Markdown
UTF-8
4,552
2.53125
3
[]
no_license
## Architecture The video triggering system is composed of a number of raspberry pi zero w's, one running as an access point that all the others join. A control computer also connects to that network and will recieve OSC messages to control resolume and the video output. Each individual pi broadcasts OSC, so the ips do not have to be statically assigned. ## Installation ### Raspian For all Pi's - download [noobs](https://www.raspberrypi.org/downloads/) (2.4.5) - format an sd card using [this formatter](https://www.sdcard.org/downloads/formatter_4/) set the volume name to boot and ms-dos format - put the contents of the noobs installer onto the card - boot the pi and let the install run. 20-40min ### Access Point Pi setup using dnasmasq and hostapd. based on [this tutorial](https://www.raspberrypi.org/documentation/configuration/wireless/access-point.md). - install dnsmasq (dhcp/routing) and hostapd (access point control). `sudo apt-get install dnsmasq hostapd` (will show some errors since we have no config yet. thats ok) - Give it a static ip (192.168.0.1): edit `/etc/dhcpcd.conf`. end of file should look like: ~~~ interface wlan0 static ip_address=192.168.0.1/24 ~~~ - Setup dhcp interface and address range: edit `/etc/dnsmasq.conf`: ~~~ interface=wlan0 # Use the require wireless interface - usually wlan0 dhcp-range=192.168.0.2,192.168.0.100,255.255.255.0,24h ~~~ - Setup access point settings. edit/create `/etc/hostapd/hostapd.conf` ~~~ interface=wlan0 driver=nl80211 ssid=ArtfulGuise hw_mode=g channel=7 wmm_enabled=0 macaddr_acl=0 auth_algs=1 ignore_broadcast_ssid=0 wpa=2 wpa_passphrase=your_passphrase wpa_key_mgmt=WPA-PSK wpa_pairwise=TKIP rsn_pairwise=CCMP ~~~ - set hostapd conf location to be the file we just created. edit `/etc/default/hostapd`: ~~~ #DAEMON_CONF... ~~~ becomes ~~~ DAEMON_CONF="/etc/hostapd/hostapd.conf" ~~~ - restartd dhcp, and access point: ~~~ sudo service hostapd start sudo service dnsmasq start ~~~ - enable routing: edit `/etc/sysctl.conf` and uncomment: ~~~ net.ipv4.ip_forward=1 ~~~ - Reboot the pi. Note the ssid "ArtfulGuise" will become available before the network actually is, if you connect and can't ssh into the pi, diconnect, wait a minute and try again. - `ssh [email protected]` ### All Pi Hardware setup - using [mfrc522](https://www.nxp.com/docs/en/data-sheet/MFRC522.pdf) card reader. - Pins are as follows: | purpose | rc522 pin label | pi pin number | |-------------|-----------------|---------------| | chip select | sda | 24 | | clock | sck | 23 | | serial out | mosi | 19 | | serial in | miso | 21 | | interrupt | irq | 12 | | ground | gnd | 6 | | reset | rst | 7 | | 3.3v rail | 3.3v | 1 | - dont fuck up the soldering ### All Pi software setup - boot the pi or pi's and connect to the internet via your home network. - install python deps: - `sudo pip install pyOSC` - `sudo pip install pi-rc522` - in pi's home directory clone this repo - create a serivce in `/etc/systemd/system/art.service` ~~~ [Unit] Description=RFID Scanner to OSC After=network.service [Service] ExecStart=/usr/bin/python scanner.py WorkingDirectory=/home/pi/artful-guise StandardOutput=inherit StandardError=inherit Restart=always RestartSec=5 StartLimitInterval=600 StartLimitBurst=100 User=pi [Install] WantedBy=multi-user.target ~~~ - enable the service at startup `sudo systemctl enable art` - start the service `sudo service art start` ### Connecting to pi over network. - boot the host pi. and other pi's. wait for access point to be available, then wait a bit more. - scan for pi's `nmap -sn 192.168.0.0/24` - you'll see 192.168.0.N, 1 being the host, one of them being your machine and the rest being other pi's ### Testing - ssh into the pi - stop the art service `sudo service art stop` - run it `python artful-guise/scanner.py` - will show card ids, and OSC urls if all is working if all is working - mapping of ids to osc urls is in `mapping.json` and may be changed for each pi - restart the service or reboot when done
Markdown
UTF-8
4,431
3.046875
3
[ "MIT" ]
permissive
# Nodejs ## 介绍 Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境,是一个应用程序。 官方网址 <https://nodejs.org/en/>,中文站 <http://nodejs.cn/> ## 作用 - 解析运行 JS 代码 - 操作系统资源,如内存、硬盘、网络 ## 应用场景 * APP 接口服务 * 聊天室 * 动态网站, 个人博客, 论坛, 商城等 * 后端的Web服务,例如服务器端的请求(爬虫),代理请求(跨域) * 前端项目打包(webpack, gulp) ## 使用 ### 下载安装 工具一定要到官方下载,历史版本下载 <https://npm.taobao.org/mirrors/node/> ![img](assets/20190329115938531.png) Nodejs 的版本号奇数为开发版本,偶数为发布版本,<span style="color:red">我们选择偶数号的 LTS 版本(长期维护版本 long term service)</span> ![1572676490692](assets/1572676490692.png) 双击打开安装文件,一路下一步即可😎,默认的安装路径是 `C:\Program Files\nodejs` 安装完成后,在 CMD 命令行窗口下运行 `node -v`,如显示版本号则证明安装成功,反之安装失败,重新安装。 ![1572678177784](assets/1572678177784.png) ### 初体验 #### 交互模式 在命令行下输入命令 `node`,这时进入 nodejs 的交互模式 ![1572678681282](assets/1572678681282.png) #### 文件执行 创建文件 hello.js ,并写入代码 console.log('hello world'),命令行运行 `node hello.js` 快速启动命令行的方法 * 在文件夹上方的路径中,直接输入 cmd 即可 * 使用 webstorm 和 vscode 自带的命令行窗口 ![1572680753835](assets/1572680753835.png) #### VScode 插件运行 安装插件 『code Runner』, 文件右键 -> run code ![1593782861500](assets/1593782861500.png) #### 注意 <span style="color:red">在 nodejs 环境下,不能使用 BOM 和 DOM ,也没有全局对象 window,全局对象的名字叫 global</span> ### Buffer(缓冲器) #### 介绍 Buffer 是一个和数组类似的对象,不同是 Buffer 是专门用来保存二进制数据的 #### 特点 * 大小固定:在创建时就确定了,且无法调整 * 性能较好:直接对计算机的内存进行操作 * 每个元素大小为 1 字节(byte) #### 操作 ##### 创建 Buffer * 直接创建 Buffer.alloc * 不安全创建 Buffer.allocUnsafe * 通过数组和字符串创建 Buffer.from ##### Buffer 读取和写入 可以直接通过 `[]` 的方式对数据进行处理,可以使用 toString 方法将 Buffer 输出为字符串 * ==[ ]== 对 buffer 进行读取和设置 * ==toString== 将 Buffer 转化为字符串 ##### 关于溢出 溢出的高位数据会舍弃 ##### 关于中文 一个 UTF-8 的中文字符大多数情况都是占 3 个字节 ##### 关于单位换算 1Bit 对应的是 1 个二进制位 8 Bit = 1 字节(Byte) 1024Byte = 1KB 1024KB = 1MB 1024MB = 1GB 1024GB = 1TB 平时所说的网速 10M 20M 100M 这里指的是 Bit ,所以理论下载速度 除以 8 才是正常的理解的下载速度 ### 文件系统 fs fs 全称为 file system,是 NodeJS 中的内置模块,可以对计算机中的文件进行增删改查等操作。 ##### 文件写入 * 简单写入 * fs.writeFile(file, data, [,options], callback); * fs.writeFileSync(file, data); * options 选项 * `encoding` **默认值:** `'utf8'` * `mode`**默认值:** `0o666` * `flag` **默认值:** `'w'` * 流式写入 * fs.createWriteStream(path[, options]) * path * options * ==flags== **默认值:** `'w'` * `encoding `**默认值:** `'utf8'` * `mode` **默认值:** `0o666` * 事件监听 open close eg: ws.on('open', function(){}); ##### 文件读取 * 简单读取 * fs.readFile(file, function(err, data){}) * fs.readFileSync(file) * 流式读取 * fs.createReadStream(); ##### 文件删除 * fs.unlink('./test.log', function(err){}); * fs.unlinkSync('./move.txt'); ##### 移动文件 + 重命名 * fs.rename('./1.log', '2.log', function(err){}) * fs.renameSync('1.log','2.log') ##### 文件夹操作 * mkdir 创建文件夹 * path * options * recursive 是否递归调用 * mode 权限 默认为 0o777 * callback * rmdir 删除文件夹 * readdir 读取文件夹 ## 附录 ### unicode 字符集 * https://www.tamasoft.co.jp/en/general-info/unicode.html * https://www.cnblogs.com/whiteyun/archive/2010/07/06/1772218.html
C++
UTF-8
413
2.859375
3
[]
no_license
#include<iostream> #include<algorithm> #include<vector> using namespace std; int main(){ vector<int> v{1,2,3}; next_permutation(v.begin(),v.end()); next_permutation(v.begin(),v.end()); next_permutation(v.begin(),v.end()); next_permutation(v.begin(),v.end()); next_permutation(v.begin(),v.end()); for(auto x : v){ cout<< x<< " "; } return 0; }
PHP
UTF-8
4,787
2.578125
3
[ "MIT", "BSD-3-Clause" ]
permissive
<?php namespace Ociosos\UsuarioBundle\Entity; use Symfony\Component\Security\Core\User\UserInterface; use Doctrine\ORM\Mapping as ORM; use Ociosos\ComunBundle\Entity\Centro; /** * Usuario * * @ORM\Table(name="usuario") * @ORM\Entity(repositoryClass="Ociosos\UsuarioBundle\Entity\UsuarioRepository") * */ class Usuario implements UserInterface { /** * @var integer * * @ORM\Column(name="UsuarioID", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ protected $id; /** * @var string * * @ORM\Column(name="Nombre", type="string", length=50) */ protected $nombre; /** * @var string * * @ORM\Column(name="Apellidos", type="string", length=50) */ protected $apellidos; /** * @var string * * @ORM\Column(name="Email", type="string", length=50) */ protected $email; /** * @var string * * @ORM\Column(name="Password", type="string", length=200) */ protected $password; /** * @var string * * @ORM\Column(name="Role", type="string", length=50) */ protected $role; /** * @var string * * @ORM\Column(name="Username", type="string", length=50) */ protected $username; /** * @var string * * @ORM\Column(name="Salt", type="string", length=255) */ protected $salt; /** * @ORM\ManyToOne(targetEntity="Ociosos\ComunBundle\Entity\Centro") * @ORM\JoinColumn(name="Centro_centroID", referencedColumnName="CentroID") */ protected $centro; public function __construct() { } /** * Get username * * @return string */ public function getUsername() { return $this->username; } /** * Get password * * @return string */ public function getPassword() { return $this->password; } /** * Get salt * * @return string */ public function getSalt() { return $this->salt; // return null; } public function getRoles() { return array($this->role); // return array('ROLE_USER'); } public function eraseCredentials() { return false; } public function equals(UserInterface $user) { return $this->getUsername() == $user->getUsername(); } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set nombre * * @param string $nombre * @return Usuario */ public function setNombre($nombre) { $this->nombre = $nombre; return $this; } /** * Get nombre * * @return string */ public function getNombre() { return $this->nombre; } /** * Set apellidos * * @param string $apellidos * @return Usuario */ public function setApellidos($apellidos) { $this->apellidos = $apellidos; return $this; } /** * Get apellidos * * @return string */ public function getApellidos() { return $this->apellidos; } /** * Set email * * @param string $email * @return Usuario */ public function setEmail($email) { $this->email = $email; return $this; } /** * Get email * * @return string */ public function getEmail() { return $this->email; } /** * Set password * * @param string $pass * @return Usuario */ public function setPassword($pass) { $this->password = $pass; return $this; } /** * Set role * * @param string $role * @return Usuario */ public function setRole($role) { $this->role = $role; return $this; } /** * Get role * * @return string */ public function getRole() { return $this->role; } /** * Set username * * @param string $login * @return Usuario */ public function setUsername($login) { $this->username = $login; return $this; } /** * Set salt * * @param string $salt * @return Usuario */ public function setSalt($salt) { $this->salt = $salt; return $this; } public function setCentro(Centro $centro) { $this->centro = $centro; } public function getCentro() { return $this->centro; } public function __toString(){return $this->nombre;} }
C#
UTF-8
4,282
3.015625
3
[]
no_license
using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Security.Authentication.ExtendedProtection; namespace json_to_graphql_schema { class Program { static Dictionary<string, List<string>> schema = new Dictionary<string, List<string>>(); static string jsonString; static JObject data; static void Main(string[] args) { try { string filePath = "{PATH TO THE JSON FILE}"; data = JObject.Parse(File.ReadAllText(filePath)); } catch (Exception e) { Console.WriteLine($"Error while reading the JSON file {e.Message}"); throw e; } string output = string.Empty; try { foreach (var x in data) { string key = x.Key; JToken jToken = x.Value; string valueType = ProcessValue(key, jToken); if (!schema.ContainsKey("Root")) { schema.Add("Root", new List<string>()); } List<string> rootList = schema["Root"]; rootList.Add(CreateKeyValPair(key, valueType)); schema["Root"] = rootList; } foreach (var key in schema) { output = output + $"type {key.Key} {"{"}" + Environment.NewLine; foreach (var item in key.Value) { output = output + item; output += Environment.NewLine; } output += "}"; output += Environment.NewLine; } } catch (Exception e) { Console.WriteLine($"Error while converting json to GraphQl schema {e.Message}"); throw e; } Console.WriteLine(output); } private static void ReadArguments(string[] args) { if (args.Length == 0) throw new Exception("Invalid Arguments"); } private static string CreateKeyValPair(string key, string valueType) { return $"{key} : {valueType}"; } private static string ProcessValue(string key, JToken jToken) { string finalkey = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(key.ToLower()); if (jToken.Type == JTokenType.Integer) { return "Int"; } else if (jToken.Type == JTokenType.String) { return "String"; } else if (jToken.Type == JTokenType.Boolean) { return "Boolean"; } else if (jToken.Type == JTokenType.Float) { return "Float"; } else if (jToken.Type == JTokenType.Array) { if (!jToken.HasValues) return $"[{"String"}]"; string itemType = ProcessValue(key, jToken.First); return $"[{itemType}]"; } else if (jToken.Type == JTokenType.Object) { string stringjToken = JsonConvert.SerializeObject(jToken); foreach (var x in JObject.Parse(stringjToken)) { string k = x.Key; JToken j = x.Value; string valueType = ProcessValue(k, j); if (!schema.ContainsKey(finalkey)) { schema.Add(finalkey, new List<string>()); } List<string> list = schema[finalkey]; list.Add(CreateKeyValPair(k, valueType)); schema[finalkey] = list; } return finalkey; } return null; } } }
Python
UTF-8
1,795
3.296875
3
[]
no_license
# ex15.py generate fake data import random from datetime import timedelta, datetime words = [x.strip().capitalize() for x in open("words.txt").readlines()] breeds = ['Dog', 'Cat', 'Fish', 'Unicorn'] pet_names = words[:int(len(words)/2)] owner_names = words[:int(len(words)/2):] owner_insert = '''INSERT INTO person VALUES (NULL, '{first}', '{last}', '{age}', '{dob}');''' pet_insert = '''INSERT INTO pet VALUES (NULL, '{name}', '{breed}', '{age}', '{dead}');''' relate_insert = '''INSERT INTO person_pet VALUES ({person_id}, {pet_id}, '{purchased_on}');''' sql = [] def random_date(): years = 365 * random.randint(0,50) days = random.randint(0,365) hours = random.randint(0,24) past = timedelta(days=years + days, hours=hours) return datetime.now() - past # make a bunch of random pets for i in range(0,100): age = random.randint(0,20) breed = random.choice(breeds) name = random.choice(pet_names) dead = random.randint(0,1) sql.append(pet_insert.format(age=age, breed=breed, name=name, dead=dead)) #print(sql[:5]) # make a bunch of random people for i in range(0,100): age = random.randint(0,100) first = random.choice(owner_names) last = random.choice(owner_names) dob = random_date() sql.append(owner_insert.format(age=age, first=first, last=last, dob=dob)) #print(sql[-5:]) # sample from middle to connect pets & owners for i in range(0,75): person_id = random.randint(5,95) pet_id = random.randint(5,95) purchased_on = random_date() sql.append(relate_insert.format(person_id=person_id, pet_id=pet_id, purchased_on=purchased_on)) #print(sql[-5:]) # this is destructive, normally you would check and askt overwrite with open("ex15.sql", "w") as output: output.write("\n".join(sql))
PHP
UTF-8
814
2.6875
3
[ "MIT" ]
permissive
<?php namespace App\Models; use Illuminate\Database\Eloquent\Model; /** * @property integer $id * @property string $contact_person * @property string $website * @property string $about_us * @property string $address * @property string $email * @property string $phone_number * @property string $remember_token * @property string $created_at * @property string $updated_at */ /** * Class ShopDetail * @package App\Models * */ class ShopDetail extends Model { /** * The "type" of the auto-incrementing ID. * * @var string */ protected $keyType = 'integer'; /** * @var array */ protected $fillable = ['contact_person', 'website', 'about_us', 'address', 'email', 'phone_number','latitude','longitude', 'remember_token', 'created_at', 'updated_at']; }
Java
UTF-8
1,679
2.875
3
[]
no_license
package com.team1640; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; public class MenuBar extends JMenuBar implements ActionListener{ private static final long serialVersionUID = 1L; private ScoutMobile main; public MenuBar(ScoutMobile m) { main = m; // FILE MENU JMenu menuFile = new JMenu("File"); JMenuItem menuFileNew = new JMenuItem("New"); menuFileNew.addActionListener(this); JMenuItem menuFileExit = new JMenuItem("Exit"); menuFileExit.addActionListener(this); // EDIT MENU JMenu menuEdit = new JMenu("Edit"); JMenuItem menuEditCopy = new JMenuItem("Copy"); menuEditCopy.addActionListener(this); JMenuItem menuEditPaste = new JMenuItem("Paste"); menuEditPaste.addActionListener(this); // VIEW MENU JMenu menuView = new JMenu("View"); JMenuItem menuViewSwitchViews = new JMenuItem("Switch Views"); menuViewSwitchViews.addActionListener(this); // Add elements add(menuFile); menuFile.add(menuFileNew); menuFile.add(menuFileExit); add(menuEdit); menuEdit.add(menuEditCopy); menuEdit.add(menuEditPaste); add(menuView); menuView.add(menuViewSwitchViews); } @Override public void actionPerformed(ActionEvent event) { String name = event.getActionCommand(); //FILE MENU if (name.equals("New")) { //new } else if (name.equals("Exit")) { System.exit(0); } //EDIT MENU else if (name.equals("Copy")) { //copy } else if (name.equals("Paste")) { //paste } //VIEW MENU else if (name.equals("Switch Views")) { main.switchViews(); } } }
Java
UTF-8
1,194
2.046875
2
[]
no_license
package com.xxx.model.base.service; import com.baomidou.mybatisplus.plugins.Page; import com.xxx.common.framework.base.BaseService; import com.xxx.common.util.SmsUtil; import com.xxx.model.base.dao.CareDAO; import com.xxx.model.base.entity.Care; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.Resource; import java.util.Map; /** * 客户关怀业务逻辑类 */ @Service public class CareService extends BaseService<Care> { @Resource private CareDAO careDAO; /** 保存 */ @Transactional public void save(Care care) { if(care.getId() == null){ this.insert(care); }else{ this.updateParams(care); } } public void add(Care care){ careDAO.insert(care); String[] phones = { care.getPhone() }; SmsUtil.sendSMS(phones, care.getContent(),5); } public Page<Map<String,Object>> findList(Page<Map<String,Object>> page, Care care){ return page.setRecords(careDAO.findList(page, care)); } public Map<String,Object> getCareById(int id){ return careDAO.getCareById(id); } }
Python
UTF-8
678
3.65625
4
[]
no_license
def main(): pass import random finalList = [] listA = [] listB = [] for i in range(50): listA.append(random.randint(0, 100)) listB.append(random.randint(0, 100)) print("Lista A: " + str(listA)) print("Lista B: " + str(listB)) for elementA in listA: if elementA in listB: if elementA not in finalList: finalList.append(elementA) #for elementA in [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]: # if elementA in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]: # if elementA not in finalList: # finalList.append(elementA) finalList.sort() print("Le liste hanno in comune: " + str(finalList)) if __name__ == "__main__": main()
Markdown
UTF-8
3,219
2.90625
3
[ "Apache-2.0" ]
permissive
project_path: /web/tools/_project.yaml book_path: /web/tools/_book.yaml description:由於大多數桌面設備都沒有觸摸屏、GPS 芯片和加速度計,所以測試它們比較困難。Chrome DevTools 傳感器模擬器可以通過模擬常見的移動設備傳感器來降低測試的開銷。 {# wf_updated_on: 2016-03-07 #} {# wf_published_on: 2015-04-13 #} # 模擬傳感器:地理定位與加速度計 {: .page-title } {% include "web/_shared/contributors/megginkearney.html" %} {% include "web/_shared/contributors/pbakaus.html" %} 由於大多數桌面設備都沒有 GPS 芯片和加速度計,所以測試它們比較困難。Chrome DevTools 的 Sensors 模擬窗格可以通過模擬常見的移動設備傳感器來降低測試的開銷。 ### TL;DR {: .hide-from-toc } - 模擬地理定位座標以測試地理定位替換值。 - 模擬設備方向以測試加速度計數據。 ## 訪問傳感器控件 <div class="wf-devtools-flex"> <div> <p>要訪問 Chrome DevTools 傳感器控件,請執行以下操作:</p> <ol> <li>打開 DevTools 主菜單</li> <li>在 <strong>More Tools</strong> 菜單下,點擊 <strong>Sensors</strong></li> </ol> </div> <div class="wf-devtools-flex-half"> <img src="imgs/navigate-to-sensors.png" alt="導航至 Sensors 面板"> </div> </div> 注:如果您的應用檢測到使用 JavaScript(如 Modernizr)的傳感器加載,請確保在啓用傳感器模擬器之後重新加載頁面。 ## 替換地理定位數據 與桌面設備不同,移動設備通常使用 GPS 硬件檢測位置。在 Sensors 窗格中,您可以模擬地理定位座標,以便與 <a href='http://www.w3.org/TR/geolocation-API/'>Geolocation API</a> 結合使用。 <div class="wf-devtools-flex"> <div> <p>在模擬抽屜式導航欄的 Sensors 窗格中選中 <strong>Emulate geolocation coordinates</strong> 複選框,啓用地理定位模擬。</p> </div> <div class="wf-devtools-flex-half"> <img src="imgs/emulation-drawer-geolocation.png" alt="已啓用的地理定位模擬器"> </div> </div> 您可以使用此模擬器替換 `navigator.geolocation` 的位置值,並在地理定位數據不可用時模擬用例。 ## 模擬加速度計(設備方向) <div class="wf-devtools-flex"> <div> <p>要測試來自 <a href='http://www.w3.org/TR/screen-orientation/'>Orientation API</a> 的加速度計數據,請在 Sensors 窗格中選中 <strong>Accelerometer</strong> 複選框,啓用加速度計模擬器。</p> </div> <div class="wf-devtools-flex-half"> <img src="imgs/emulation-drawer-accelerometer.png" alt="加速度計控件"> </div> </div> 您可以操作下列方向參數: <dl> <dt><abbr title="alpha">α</abbr></dt> <dd>圍繞 Z 軸旋轉。</dd> <dt><abbr title="beta">β</abbr></dt> <dd>左右傾斜。</dd> <dt><abbr title="gamma">γ</abbr></dt> <dd>前後傾斜。</dd> </dl> 您也可以點擊模型加速度計並將其拖動到所需方向。 使用此[設備方向演示](http://googlesamples.github.io/web-fundamentals/fundamentals/native-hardware/device-orientation/dev-orientation.html)試用加速度計模擬器。 {# wf_devsite_translation #}
Markdown
UTF-8
2,385
2.875
3
[ "MIT" ]
permissive
+++ title = "Sensing the real world through NHS prescriptions data" date = 2021-09-18T12:14:56+01:00 draft = false # Tags and categories # For example, use `tags = []` for no tags, or the form `tags = ["A Tag", "Another Tag"]` for one or more tags. tags = ["News"] categories = [] # Featured image # Place your image in the `static/img/` folder and reference its filename below, e.g. `image = "example.jpg"`. # Use `caption` to display an image caption. # Markdown linking is allowed, e.g. `caption = "[Image credit](http://example.org)"`. # Set `preview` to `false` to disable the thumbnail in listings. [header] image = "" caption = "" preview = true +++ Researchers and practitioners intererested in geography of health, social dynamics, economics, and everything in between are always interested methods that use data to sense health outcomes in the real world. If one can create proxies for health, and map them on to geographical units, one could ask important questions such as: a) How does health of an area relate with its socio-economic conditions? b) Are there any temporal trends or periodicities in certain health outcomes? c) What is the relationship between health indicators from the real world and the signals obtained from online data source like social media (e.g. as seen in this paper: http://social-dynamics.net/docs/icwsm-21.pdf )? d) Do certain policy or demograhic factors make an area more suseptible to particular health conditions? But in order to be creative with such questions, one needs a principled way to create proxies for health outcomes from official datasources, at scale, and map them onto geographical units. Unfortunately, most health data sources are highly protected, if not propreitary, and the processing steps required to translate raw data into geographical outcomes are tedious and often require domain knowledge. Over the past 2 years at Bell Labs, I have been working on something that would partly solve these issues. The [NHS Prescriptions parser](https://github.com/sagarjoglekar/NHSPrescriptionsParser) allows practitioners to mine the openly available NHS prescriptions data to make geo-spatial estimates about health outcomes across England. A more detailed manual about the steps for usage can be found [here](https://medium.com/@SagarJoglekar/mapping-health-outcomes-at-the-scale-of-an-entire-nation-bbe0eb949eea)
C++
WINDOWS-1251
3,120
2.953125
3
[]
no_license
#include <SFML/Graphics.hpp> using namespace sf; using namespace std; const int countWall = 50;// const int map_width = 40;// const int map_height = 20;// const int map_size = 20;// const int quantityFood = 10; const int quantityPoison = 10; int countFood = 0; int countPoison =0; class Map { int points[map_width][map_height];// public: void changePoint(int x, int y,int value) { points[x][y] = value; } void bePointEmpty(int x,int y)// { points[x][y] = 0; } int isPoint(int x, int y)// { return points[x][y]; } void createMap()// { for (int i = 0; i < map_width; i++) { for (int j = 0; j < map_height; j++) { points[i][j] = 0; } } int rx = 0, ry = 0; for (int i = 0; i < countWall; i++) { do { rx = rand()%map_width; ry = rand() % map_height; } while (isPoint(rx,ry)!=0); points[rx][ry] = 1; } for (int i = 0; i < quantityFood; i++) { do { rx = rand() % map_width; ry = rand() % map_height; } while (isPoint(rx, ry) != 0); points[rx][ry] = 2; countFood++; } for (int i = 0; i < quantityPoison; i++) { do { rx = rand() % map_width; ry = rand() % map_height; } while (isPoint(rx, ry) != 0); points[rx][ry] = 3; countPoison++; } } void servis()// { int rx = 0, ry = 0; /// int r = rand() % 100; if (countFood<quantityFood) { do { rx = rand() % map_width; ry = rand() % map_height; } while (isPoint(rx, ry) != 0); points[rx][ry] = 2; countFood++; } if (countPoison<quantityPoison) { do { rx = rand() % map_width; ry = rand() % map_height; } while (isPoint(rx, ry) != 0); points[rx][ry] = 3; countPoison++; } } void Draw(RenderWindow &window)// , { RectangleShape rectangle(Vector2f(map_size, map_size)); rectangle.setFillColor(Color(128, 128, 128)); for (int i = 0; i < map_width; i++) { for (int j = 0; j < map_height; j++) { if (points[i][j] == 1)// { rectangle.setFillColor(Color(128, 128, 128)); rectangle.setPosition(i*map_size, j*map_size); window.draw(rectangle); } if (points[i][j] ==2)// { rectangle.setFillColor(Color(0, 255, 0)); rectangle.setPosition(i*map_size, j*map_size); window.draw(rectangle); } if (points[i][j] == 3)// { rectangle.setFillColor(Color(255, 0, 0)); rectangle.setPosition(i*map_size, j*map_size); window.draw(rectangle); } } DrawLine(window, map_width*map_size , 0, map_width*map_size, map_height*map_size, Color(128, 128, 128)); } } };
JavaScript
UTF-8
755
2.546875
3
[]
no_license
import React from 'react'; import { Link } from 'react-router-dom'; const Greeting =(props)=>{ /* note tahte its porops.history.push to chagne the page basically nooooo match lul*/ const onSend = (event)=>( props.logout()//.then(res=>props.history.push('/wtfitsowrking??')) ) const withUser =()=>( <div className="whatever"> <h2 className="">Hi, {props.currentUser.username}!</h2> <button className="" onClick={onSend}>Log Out</button > </div> ) const noUser =()=>( <nav> <Link to ="users/new">Sign Up</Link> <Link to ="/login">Sign In</Link> </nav> ) return props.currentUser? withUser() : noUser() } export default Greeting;
SQL
UTF-8
220
2.578125
3
[]
no_license
CREATE TABLE games ( id INT AUTO_INCREMENT PRIMARY KEY, state VARCHAR(50) NOT NULL, players VARCHAR (100) ); insert into games (state, players) values ('PLAYING', 'bart,lisa'), ('OPEN', 'homer'), ('OPEN', NULL);
Python
UTF-8
8,291
2.53125
3
[ "MIT" ]
permissive
# # Do NOT modify or remove this copyright and license # # Copyright (c) 2019 Seagate Technology LLC and/or its Affiliates, All Rights Reserved # # This software is subject to the terms of the MIT License. If a copy of the license was # not distributed with this file, you can obtain one at https://opensource.org/licenses/MIT. # # ****************************************************************************************** # # redfish_urls.py # # ****************************************************************************************** # # @command redfish urls # # @synopsis Test all URLs reported by this REST API # # @description-start # # This command will traverse and validate all links reported by this service. # The query begins with '/redfish/v1/' and then parses the JSON data and adds # all new '@odata.id' URLs to an ordered dictionary. The process recursively # queries each unchecked URL and adds any new URLs to the dictionary. Once # all URLs have been checked, a summary is reported along with the link status. # # Example: redfish urls /redfish/v1 # # Redfish Link Validation # # [] Starting URL: /redfish/v1/ # [] Total URLs : 177 # [] Total OK : 171 # [] Total Errors: 6 # # Valid Status Reason URL # ------------------------------------------------------------------------------------------------------------------------------------ # True 200 OK /redfish/v1/ # True 200 OK /redfish/v1/Chassis# -- This will validate every URL used by this Redfish service provider and provide a summary. # False 501 Bad Request /redfish/v1/Chassis//ComputerSystem/00C0FF43C844/Storage/ # False 501 Not Found /redfish/v1/Chassis/controller_a # False 501 Not Found /redfish/v1/Chassis/controller_b # True 200 OK /redfish/v1/Chassis/enclosure_0 # Etc. # # @description-end # # import time from collections import OrderedDict from commands.commandHandlerBase import CommandHandlerBase from core.redfishSystem import RedfishSystem from core.trace import TraceLevel, Trace from core.urlAccess import UrlAccess, UrlStatus ################################################################################ # CommandHandler ################################################################################ class CommandHandler(CommandHandlerBase): """Command - redfish urls """ name = 'redfish urls' data = '' allLinks = OrderedDict() startingurl = '' def total_links_to_check(self): total = 0 for key in self.allLinks: link = self.allLinks[key] if (link.checked == False): total += 1 return total def links_to_check(self): for key in self.allLinks: link = self.allLinks[key] if (link.checked == False): return True return False def get_next_link(self): for key in sorted (self.allLinks.keys()): link = self.allLinks[key] if (link.checked == False): return link return None def dump_links(self): Trace.log(TraceLevel.TRACE, ' // allLinks -- count={}'.format(len(self.allLinks))) index = 0 for key in self.allLinks: link = self.allLinks[key] index += 1 Trace.log(TraceLevel.TRACE, ' // allLinks -- [{}/{}] key={} checked={} url={}'.format(index, len(self.allLinks), key, link.checked, link.url)) def add_links(self, data, parent): Trace.log(TraceLevel.TRACE, ' ++ add_links data ({}) parent ({})'.format(data, parent)) if isinstance(data, dict): for k, v in data.items(): if isinstance(v, dict): Trace.log(TraceLevel.TRACE, ' ++ add_links dict v ({}), k ({})'.format(v, k)) self.add_links(self, v, parent) elif isinstance(v, list): for i in v: Trace.log(TraceLevel.TRACE, ' ++ add_links list i ({}) k ({})'.format(i, k)) self.add_links(self, i, parent) else: Trace.log(TraceLevel.TRACE, ' @@ {0: >20} : {1: >24} -- {2}'.format(parent, k, v)) if (k == '@odata.id'): if (v not in self.allLinks): Trace.log(TraceLevel.DEBUG, ' @@ ++ New Link: ({}) parent ({})'.format(v, parent)) link = UrlStatus(v) link.parent = parent self.allLinks[v] = link self.dump_links(self) @classmethod def process_next_url(self, redfishConfig, link): Trace.log(TraceLevel.TRACE, ' ++ redfish urls // process_next_url ({})'.format(link.url)) UrlAccess.process_request(redfishConfig, link, 'GET', True) if (link.valid == False): Trace.log(TraceLevel.VERBOSE, ' @@ INVALID url ({}) parent ({})'.format(link.url, link.parent)) self.add_links(self, link.jsonData, link.url) @classmethod def prepare_url(self, redfishConfig, command): # Usage: redfish urls [startingurl] self.allLinks = {} words = command.split(' ') if (len(words) > 2): self.startingurl = words[2] else: RedfishSystem.initialize_service_root_uris(redfishConfig) self.startingurl = RedfishSystem.get_uri(redfishConfig, 'Root') Trace.log(TraceLevel.TRACE, ' ++ redfish urls // starting url ({})'.format(self.startingurl)) return (self.startingurl) @classmethod def process_json(self, redfishConfig, url): Trace.log(TraceLevel.TRACE, ' ++ redfish urls // process_json url ({})'.format(url)) sleepTime = redfishConfig.get_int('linktestdelay') Trace.log(TraceLevel.VERBOSE, '.. process_url START ({}) delay({})'.format(url, sleepTime)) link = UrlAccess.process_request(redfishConfig, UrlStatus(url), 'GET', True) self.allLinks[url] = link self.dump_links(self) self.add_links(self, link.jsonData, url) # While there are still URLs to check, continue to GET links and process until all links have been checked while self.links_to_check(self): if (sleepTime): time.sleep(sleepTime) Trace.log(TraceLevel.INFO, ' .. urls total ({}) urls to process ({})'.format(len(self.allLinks), self.total_links_to_check(self))) nextLink = self.get_next_link(self) if (nextLink != None): Trace.log(TraceLevel.VERBOSE, '.. process_url ({})'.format(nextLink.url)) self.process_next_url(redfishConfig, nextLink) @classmethod def display_results(self, redfishConfig): print('') print(' Redfish URL Validation') print('') totalUrls = len(self.allLinks) totalOk = 0 totalErrors = 0 for key in self.allLinks.keys(): link = self.allLinks[key] if (link.urlReason == 'OK'): totalOk += 1 else: totalErrors += 1 print(' [] Starting URL: {}'.format(self.startingurl)) print(' [] Total URLs : {0: >4}'.format(totalUrls)) print(' [] Total OK : {0: >4}'.format(totalOk)) print(' [] Total Errors: {0: >4}'.format(totalErrors)) print('') print(' Valid Status Reason URL') print('-' * (132)) for key in sorted (self.allLinks.keys()): link = self.allLinks[key] marker = '' if (link.checked == False): marker = '** Not checked!' print('{0: >6} {1: >8} {2: >16} {3: <80} {4}'.format(str(link.valid), str(link.urlStatus), str(link.urlReason), link.url, marker)) print('') print('-' * (132)) print(' [] Starting URL: {}'.format(self.startingurl)) print(' [] Total URLs : {0: >4}'.format(totalUrls)) print(' [] Total OK : {0: >4}'.format(totalOk)) print(' [] Total Errors: {0: >4}'.format(totalErrors)) print('-' * (132))
Markdown
UTF-8
600
2.65625
3
[ "MIT" ]
permissive
# Abe locale > translate Abe backoffice texts ## Config Abe set a property ```siteLocaleFolder``` to your abe.json file which link to your folder on your website source exemple : ```javascript { "siteLocaleFolder": "mylocales" } ``` Under mylocales folder you can add a folder named en-US which is the default lang value or you can override this lang inside abe.json this way ```javascript { "intlData": { "locales": "fr-FR" } } ``` After doing this you can add as many json files as you want inside mylocales/fr-FR/ and the json key values will be merged with exsting locales values
Java
UTF-8
2,520
2.078125
2
[]
no_license
/* */ package net.minecraft.network.play.server; /* */ /* */ import com.google.common.collect.Maps; /* */ import java.io.IOException; /* */ import java.util.Map; /* */ import net.minecraft.network.INetHandler; /* */ import net.minecraft.network.Packet; /* */ import net.minecraft.network.PacketBuffer; /* */ import net.minecraft.network.play.INetHandlerPlayClient; /* */ import net.minecraft.stats.StatBase; /* */ import net.minecraft.stats.StatList; /* */ /* */ /* */ /* */ public class SPacketStatistics /* */ implements Packet<INetHandlerPlayClient> /* */ { /* */ private Map<StatBase, Integer> statisticMap; /* */ /* */ public SPacketStatistics() {} /* */ /* */ public SPacketStatistics(Map<StatBase, Integer> statisticMapIn) { /* 23 */ this.statisticMap = statisticMapIn; /* */ } /* */ /* */ /* */ /* */ /* */ /* */ public void processPacket(INetHandlerPlayClient handler) { /* 31 */ handler.handleStatistics(this); /* */ } /* */ /* */ /* */ /* */ /* */ /* */ public void readPacketData(PacketBuffer buf) throws IOException { /* 39 */ int i = buf.readVarIntFromBuffer(); /* 40 */ this.statisticMap = Maps.newHashMap(); /* */ /* 42 */ for (int j = 0; j < i; j++) { /* */ /* 44 */ StatBase statbase = StatList.getOneShotStat(buf.readStringFromBuffer(32767)); /* 45 */ int k = buf.readVarIntFromBuffer(); /* */ /* 47 */ if (statbase != null) /* */ { /* 49 */ this.statisticMap.put(statbase, Integer.valueOf(k)); /* */ } /* */ } /* */ } /* */ /* */ /* */ /* */ /* */ /* */ public void writePacketData(PacketBuffer buf) throws IOException { /* 59 */ buf.writeVarIntToBuffer(this.statisticMap.size()); /* */ /* 61 */ for (Map.Entry<StatBase, Integer> entry : this.statisticMap.entrySet()) { /* */ /* 63 */ buf.writeString(((StatBase)entry.getKey()).statId); /* 64 */ buf.writeVarIntToBuffer(((Integer)entry.getValue()).intValue()); /* */ } /* */ } /* */ /* */ /* */ public Map<StatBase, Integer> getStatisticMap() { /* 70 */ return this.statisticMap; /* */ } /* */ } /* Location: C:\Users\emlin\Desktop\BetterCraft.jar!\net\minecraft\network\play\server\SPacketStatistics.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
Java
UTF-8
556
1.820313
2
[]
no_license
package com.ulane.running.dao.comtech.impl; /* * 北京优创融联科技有限公司 综合客服管理系统 -- http://www.ulane.cn * Copyright (C) 2008-2010 Beijing Ulane Technology Co., LTD */ import com.htsoft.core.dao.impl.BaseDaoImpl; import com.ulane.running.dao.comtech.CtScrCatDao; import com.ulane.running.model.comtech.CtScrCat; /** * * @author [email protected] * */ @SuppressWarnings("unchecked") public class CtScrCatDaoImpl extends BaseDaoImpl<CtScrCat> implements CtScrCatDao{ public CtScrCatDaoImpl() { super(CtScrCat.class); } }
Markdown
UTF-8
1,055
3.8125
4
[]
no_license
#### 牛客网-华为机试练习题 07 #### 题目描述 写出一个程序,接受一个正浮点数值,输出该数值的近似整数值。如果小数点后数值大于等于5,向上取整;小于5,则向下取整。 #### 输入描述: ``` 输入一个正浮点数值 ``` #### 输出描述: ``` 输出该数值的近似整数值 ``` 示例1 输入 ``` 5.5 ``` 输出 ``` 6 ``` #### 思路: 1,对数据进行取整操作,使用(int)方法,只保留整数部分,结果为i 2,然后判断d-i和0.5的关系,如果大于0.5,就返回i+1,否则返回i #### 解决代码 ```java import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner=new Scanner(System.in); double d=scanner.nextDouble(); System.out.println(getReturn(d)); } public static int getReturn(double d) { int i=(int)d; return (d-i)>=0.5?i+1:i; } } ``` #### 总结: * 双精度浮点型是double,不是Double * 强制类型转换是(int)
Shell
UTF-8
303
2.6875
3
[]
no_license
eval "$(/opt/homebrew/bin/brew shellenv)" . $(brew --prefix asdf)/libexec/asdf.sh . $(brew --prefix asdf)/etc/bash_completion.d/asdf.bash for file in $HOME/.{git-completion.sh,git-prompt.sh,exports.sh,extras.sh,bash_morgan,bash_aliases,paths.sh}; do [ -r "$file" ] && source "$file" done unset file
Markdown
UTF-8
1,641
2.828125
3
[ "MIT" ]
permissive
Assignment 2: dartboard detector This assignment detects dartboards in a set of images combining a object detector that uses Haar-like features generated by a boosting procedure with a line detector and a circle detector. The detector (or strong classifier) is the file darcascade.xml. It's generated taking a set of positive and negative images (images that contain dartboards and images that don't contain dartboard) and extracting common features. Nevertheless, the generated detector produces a lot of false positives (no false negatives in the given set of images though). In order to eliminate the false positives we assume that real dartboards have lots of lines inside them, so we remove the possible dartboards that don't have a minimum number of lines. We also assume that real dartboards have circles that have centers inside them, so we count the number of circles that each possible dartboard have inside them. Thyus, we only consider dartboards that have at least 1 circle inside them. This program detects all the dartboards from the given set of images, having only one false positive in the dart7.jpg file. When you run the program, it will generate files beginning with "output" highlighting the detected dartboards. Feel free to add more images. You will only need to follow the naming standard (dartnumber.jpg) and increase the loop size in the main function. Compiling and running instructions: g++ dart.cpp /usr/local/opencv-2.4/lib/libopencv_core.so.2.4 /usr/local/opencv-2.4/lib/libopencv_highgui.so.2.4 /usr/local/opencv-2.4/lib/libopencv_imgproc.so.2.4 /usr/local/opencv-2.4/lib/libopencv_objdetect.so ./a.out
JavaScript
UTF-8
107
3.03125
3
[]
no_license
var person = { name: 'ulff' }; person.age = 34; debugger; person.name = 'Olaf'; console.log(person);
Markdown
UTF-8
2,308
3.640625
4
[]
no_license
## 0937. Reorder Data in Log Files https://leetcode.com/problems/reorder-data-in-log-files/ ### Description > You have an array of `logs`. Each log is a space delimited string of words. > > For each log, the first word in each log is an alphanumeric *identifier*. Then, either: > > - Each word after the identifier will consist only of lowercase letters, or; > - Each word after the identifier will consist only of digits. > > We will call these two varieties of logs *letter-logs* and *digit-logs*. It is guaranteed that each log has at least one word after its identifier. > > Reorder the logs so that all of the letter-logs come before any digit-log. The letter-logs are ordered lexicographically ignoring identifier, with the identifier used in case of ties. The digit-logs should be put in their original order. > > Return the final order of the logs. > > > > **Example 1:** > > ``` > Input: logs = ["dig1 8 1 5 1","let1 art can","dig2 3 6","let2 own kit dig","let3 art zero"] > Output: ["let1 art can","let3 art zero","let2 own kit dig","dig1 8 1 5 1","dig2 3 6"] > ``` > > > > **Constraints:** > > 1. `0 <= logs.length <= 100` > 2. `3 <= logs[i].length <= 100` > 3. `logs[i]` is guaranteed to have an identifier, and a word after the identifier. > > ### Solution ------ #### First thought Split the string on the fist space, so we will get the identifier and the detail. Sort the detail fro letter-logs. Digit-logs remain in the same order. Python3: ```python class Solution: def reorderLogFiles(self, logs: List[str]) -> List[str]: def f(log): identifier, detail = log.split(" ", 1) if detail[0].isalpha(): return (0, detail, identifier) else: return (1,) return (sorted(logs, key = f)) ``` ``` ["dig1 8 1 5 1","let1 art can","dig2 3 6","let2 own kit dig","let3 art zero"] ["a1 9 2 3 1","g1 act car","zo4 4 7","ab1 off key dog","a8 act zoo"] ["a1 9 2 3 1","g1 act car","zo4 4 7","ab1 off key dog","a8 act zoo","a2 act car"] ``` ``` Runtime: 36 ms, faster than 90.79% of Python3 online submissions for Reorder Data in Log Files. Memory Usage: 12.6 MB, less than 100.00% of Python3 online submissions for Reorder Data in Log Files. Time Complexity: O(log n) Space Complexity: O(n) ```
Go
UTF-8
900
3.84375
4
[ "BSD-3-Clause" ]
permissive
package clise import "fmt" func ExampleClise_Pop() { var ( c *Clise = New(5) item interface{} ) c.Push(1, 2, 3, 4, 5, 6) item = c.Pop() for item != nil { fmt.Println(item) item = c.Pop() } // Output: // 6 // 5 // 4 // 3 // 2 } func ExampleClise_RecentSlice() { var c *Clise = New(5) c.Push(1, 2, 3) fmt.Println(c.RecentSlice()) c.Push(4, 5, 6, 7) fmt.Println(c.RecentSlice()) //Output: //[1 2 3] //[6 7] } func ExampleClise_Reset() { var c *Clise = New(5) c.Push(1, 2, 3, 4, 5) fmt.Println(c.Slice()) c.Reset() c.Push(1) fmt.Println(c.Slice()) //Output: //[1 2 3 4 5] //[1] } func ExampleClise_Slice() { var c *Clise = New(5) c.Push(1, 2) fmt.Println(c.Slice()) c.Push(3, 4, 5) fmt.Println(c.Slice()) c.Push(6) fmt.Println(c.Slice()) c.Push(7, 8, 9, 10) fmt.Println(c.Slice()) //Output: //[1 2] //[1 2 3 4 5] //[2 3 4 5 6] //[6 7 8 9 10] }
PHP
UTF-8
2,490
2.859375
3
[ "MIT" ]
permissive
<?php namespace ZfrMail\Mail; /** * Simple interface for a mail * * @author Michaël Gallego */ interface MailInterface { /** * Add a new "from" address and return a new mail * * @param string $from * @return static */ public function withFrom(string $from): MailInterface; /** * Get the "from" email * * @return string */ public function getFrom(): string; /** * Add a new "to" address and return a new mail * * @param string $to * @return static */ public function withTo(string $to): MailInterface; /** * Get the "to" email * * @return string */ public function getTo(): string; /** * Add a new "cc" addresses and return a new mail * * @param array $cc * @return static */ public function withCc(array $cc): MailInterface; /** * Get the "cc" emails * * @return array */ public function getCc(): array; /** * Add a new "bcc" addresses and return a new mail * * @param array $bcc * @return static */ public function withBcc(array $bcc): MailInterface; /** * Get the "bcc" emails * * @return array */ public function getBcc(): array; /** * Set a "reply-to" address and return a new mail * * @param string $replyTo * @return static */ public function withReplyTo(string $replyTo): MailInterface; /** * Get the "reply-to" * * @return string */ public function getReplyTo(): string; /** * Add a new attachment to a given mail * * @param AttachmentInterface $attachment * @return static */ public function withAddedAttachment(AttachmentInterface $attachment): MailInterface; /** * A multiple attachments at once * * @param AttachmentInterface[] $attachments * @return static */ public function withAttachments(array $attachments): MailInterface; /** * Get list of all attachments * * @return AttachmentInterface[] */ public function getAttachments(): array; /** * Set new options (the options are related to the mailer you use) * * @param array $options * @return static */ public function withOptions(array $options): MailInterface; /** * Get the options * * @return array */ public function getOptions(): array; }
Python
UTF-8
4,173
3.328125
3
[]
no_license
import multiprocessing import time from learning_logic import decision_tree ## -------------------- FOREST CREATION -------------------------- ## ================================================================= # Creates a decision tree for each subset inside dataset. The structure of the tree is determined by # the buildTreeFunction parameter def createDecisionTrees(dataSets, buildTreeFunction = decision_tree.buildTree, **kwargs): decisionTrees = [] start_time = time.time() for subset in dataSets: decisionTrees.append(buildTreeFunction(subset, **kwargs)) print("--- {} seconds to create trees sequential ---".format(time.time() - start_time)) return decisionTrees # Creates a decision tree for each subset inside dataset using paralel programming. # The structure of the tree is determined by the buildTreeFunction parameter. def createDecisionTreesMultiprocessing(dataSets, buildTreeFunction = decision_tree.buildTree, **kwargs): # Define an output queue output = multiprocessing.Queue() # Defines process function def seedTree(subset, output, **kwargs): output.put(buildTreeFunction(subset, **kwargs)) # Setup a list of processes that we want to run processes = [multiprocessing.Process(target=seedTree, args=(dataSets[x], output), kwargs=kwargs) for x in range(0, len(dataSets))] # Run processes start_time = time.time() for p in processes: p.start() # Exit the completed processes for p in processes: p.join() print("--- {} seconds to create trees concurrently(multiprocessing)---".format(time.time() - start_time)) # Get process results from the output queue return [output.get() for p in processes] # Creates a decision tree for each subset inside dataset using a pool of processes. # The structure of the tree is determined by the buildTreeFunction parameter. def createDecisionTreesPool(dataSets, buildTreeFunction = decision_tree.buildTree, **kwargs): processes = 4 # Sets max number of concurrent processes in pool if the value is sent in kwargs if 'processes' in kwargs: processes = kwargs.pop('processes') pool = multiprocessing.Pool(processes=processes) start_time = time.time() # Runs processes, the buildtree function is executed asynchronically until all the results are retrieved with get() results = [pool.apply_async(buildTreeFunction, (dataSets[x], ), kwargs) for x in range(0, len(dataSets))] output = [r.get() for r in results] print("--- {} seconds to create trees concurrently(pool)---".format(time.time() - start_time)) return output ## -------------------- FOREST CLASSIFICATION -------------------------- ## ======================================================================== # Classifies a random forest and returns a list of tentative classifications for a test def classifyForest(decisionTrees, test): results = [decision_tree.classifyInTree(tree, test) for tree in decisionTrees] return results # Classifies a random forest and returns a list of tentative classifications for a test # The classification against the forests are made in paralel using multiprocesses def classifyForestMultiprocessing(decisionTrees, test): # Define an output queue output = multiprocessing.Queue() # Defines process function def classify(tree, test, output): output.put(decision_tree.classifyInTree(tree, test)) # Setup a list of processes that we want to run processes = [multiprocessing.Process(target=classify, args=(tree, test, output)) for tree in decisionTrees] # Run processes start_time = time.time() for p in processes: p.start() # Exit the completed processes for p in processes: p.join() #print("--- %s seconds to classify trees concurrently(multiprocessing)---" % (time.time() - start_time)) # Get process results from the output queue return [output.get() for p in processes] # Returns the most repeated element in the result set provided by the classification of the random forest def getFinalResult(classifications): return max(set(classifications), key=classifications.count)
Markdown
UTF-8
4,016
3.421875
3
[ "Apache-2.0" ]
permissive
## Aggregate With the command and event in place we can now start adding our business logic. In Domain Driven Design all of this logic belongs within the aggregate which for our example we will call name `BankAccount`. And for our simple set of business rules, we will use two fields. ```rust,ignore #[derive(Serialize, Default, Deserialize)] pub struct BankAccount { opened: bool, // this is a floating point for our example, don't do this IRL balance: f64, } ``` In order to operate within the `cqrs-es` framework, we will need the traits, `Default`, `Serialize` and `Deserialize` (all usually derived) and we will implement `cqrs_es::Aggregate`, minus any of the business logic. ```rust #[async_trait] impl Aggregate for BankAccount { type Command = BankAccountCommand; type Event = BankAccountEvent; type Error = BankAccountError; type Services = BankAccountServices; // This identifier should be unique to the system. fn aggregate_type() -> String { "Account".to_string() } // The aggregate logic goes here. Note that this will be the _bulk_ of a CQRS system // so expect to use helper functions elsewhere to keep the code clean. async fn handle(&self, command: Self::Command, services: Self::Services) -> Result<Vec<Self::Event>, Self::Error> { todo!() } fn apply(&mut self, event: Self::Event) { match event { BankAccountEvent::AccountOpened { .. } => { self.opened = true } BankAccountEvent::CustomerDepositedMoney { amount: _, balance } => { self.balance = balance; } BankAccountEvent::CustomerWithdrewCash { amount: _, balance } => { self.balance = balance; } BankAccountEvent::CustomerWroteCheck { check_number: _, amount: _, balance, } => { self.balance = balance; } } } } ``` ### Identifying the aggregate when persisted The `aggregate_type` method is used by the cqrs-es framework to uniquely identify the aggregate and event when serialized for persistence. Each aggregate should use a unique value within your application. ```rust fn aggregate_type() -> String { "Account".to_string() } ``` ### Handling commands The `handle` method of this trait is where _all_ of the business logic will go, for now we will leave that out and just return an empty vector. ```rust // note that the aggregate is immutable and an error can be returned async fn handle(&self, command: Self::Command) -> Result<Vec<Self::Event>, AggregateError<Self::Error>> { todo!() } ``` The `handle` method does not allow any mutation of the aggregate, state should be changed _only_ by emitting events. ### Applying committed events Once events have been committed they will need to be applied to the aggregate in order for it to update its state. ```rust // note the aggregate is mutable and there is no return type fn apply(&mut self, event: Self::Event) { match event { BankAccountEvent::AccountOpened { .. } => { self.opened = true } BankAccountEvent::CustomerDepositedMoney { amount: _, balance } => { self.balance = balance; } BankAccountEvent::CustomerWithdrewCash { amount: _, balance } => { self.balance = balance; } BankAccountEvent::CustomerWroteCheck { check_number: _, amount: _, balance, } => { self.balance = balance; } } } ``` Note that the `apply` function has no return value. The act of applying an event is simply bookkeeping, the action has already taken place. > An event is a historical fact, it can be ignored, but it should never cause an error.
Java
UTF-8
485
2.171875
2
[]
no_license
package cn.xiaochuankeji.tieba.background.g; public class a { private double a; private double b; private double c; private long d; public void a(double d) { this.b = d; } public double a() { return this.a; } public void b(double d) { this.a = d; } public double b() { return this.c; } public void c(double d) { this.c = d; } public void a(long j) { this.d = j; } }
Markdown
UTF-8
8,040
3.078125
3
[ "CC0-1.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
# Unit6 - Turn on the Lion lights - Richard Turere is a 12-years-old Masai boy from Nairobi, Kenya. Richard Turereは、ケニアのナイロビ出身の12歳のマサイ少年です。 His family raises animals near the south end of Nairobi National Park. 彼の家族はナイロビ国立公園の南端近くで動物を飼育しています。 The national park does not have fences, so wild animals are free to wander into farming areas. 国立公園にはフェンスがないので、野生動物は自由に農地に迷い込むことができます。 When predators encounter farm animals, they attack. 捕食者が家畜に遭遇すると、彼らは攻撃します。 One day Richard woke up to find that his family's only bull had been killed by lions from the national park, and he was upset. ある日、リチャードは目を覚まし、家族の唯一の雄牛が国立公園のライオンに殺されたことに気づき、動揺しました。 Traditionally, the Masai have a group of lion hunters called _morans_ to protect people and livestock. 伝統的に、マサイ族には、人々と家畜を保護するためにmoransと呼ばれるライオンハンターのグループがいます。 > 群れの表現 - [List of animal names](https://en.wikipedia.org/wiki/List_of_animal_names) - > 英語には群れを表現する際に、かなりイマジナリーな表現を使う場合がある。 > > |系統|表現|備考欄| > |:--:|:--:|:--| > |犬・狼|a pack of|| > |鳥・羊・山羊|a flock of|草食動物系| > |牛・象・鹿|a herd of|| > |イルカ・鯨・アザラシ|a pod of|海に住む**哺乳類**| > |魚|a shoal of<br>a school of|| > |猿|a troop of|| > |猫<br>ライオン|a clowder of<br>a pride of|犬と違ってサイズで使う物が変わる| > |アリ|an army of|列を統率する兵隊アリのイメージ| > |ハト|a kit of pigeons|| > |カラス|a murder of crows|| > |ツバメ|a flight of|| But because of development and modern weapons, too many lions have been killed, and now they are endangered. しかし、開発と現代の武器のために、あまりにも多くのライオンが殺され、今では絶滅の危機に瀕しています。 The problem inspired Richard to look for a way to protect livestock without harming lions. この問題により、リチャードはライオンに害を与えることなく家畜を保護する方法を探すようになりました。 Farmers placed lamps in their fields at night to scare off wildfire, but Richard noticed that lions stayed away if he walked through the fields with a flashlight, because the light was moving instead of still. 農民たちは夜に野原にランプを置いて野生生物を追い払ったが、リチャードは懐中電灯を持って野原を歩いていると、光が静止するのではなく動いているため、ライオンが遠ざかっていることに気づいた。 Even as a small child, Richard was fascinated by electronics. 幼い頃から、リチャードは電子機器に魅了されていました。 His hobby was pulling apart household items, such as radios, then putting them back together again. 彼の趣味は、ラジオなどの家庭用品を分解して、再び組み立てることでした。 When he noticed the lions avoiding the moving light, he had an idea. ライオンが動く光を避けていることに気づいたとき、彼は考えを持っていました。 He got hold of some solar panels, an indicator from a motorcycle, and a car battery. 彼はいくつかのソーラーパネル、オートバイのインジケーター、そして車のバッテリーを手に入れました。 The flashed on and off, one after another. 次々と点滅しました。 The lights were fitted onto poles around the cattle field. ライトは牛畑の周りのポールに取り付けられました。 This tricked the lions into believing that someone was moving around carrying a flashlight, and the lions stopped wandering into the field. これは、誰かが懐中電灯を持って動き回っているとライオンをだまして信じさせ、ライオンは野原にさまようのをやめました。 > `trick`[動] = `deceive`[動]「騙す」 > 名詞では次が同じ意味を持つ。`trick` = `deceit` = `fraud` > ただし、形容詞変化は意味異なるので注意 > > - `deceitful`「(意図的に騙す)嘘つきの」 > - `deceptive`「(無意識で)人を騙す力がある」 > `A chameleon is deceptive.`ではあるが、決して`deceitful`ではない。 > > Magic: The gathering: `Temple of Deceit` / 欺瞞の神殿 For the first time, both the lions and the livestock were safe from harm. 初めて、ライオンと家畜の両方が危害から安全でした。 Word of Richard's invention spread, and other farmers began to install his "lion lights." リチャードの発明の言葉が広まり、他の農民は彼の「ライオンライト」を設置し始めました。 As a result, Richard won a scholarship to one of Kenya's best schools, Brookhouse International School. その結果、リチャードはケニアで最高の学校の1つであるブルックハウスインターナショナルスクールへの奨学金を獲得しました。 Fund-raising by the school enabled villages all over Kenya to install the lights. 学校による募金により、ケニア全土の村が照明を設置することができました。 Farmers have discovered tht the lights also keep away hyenas, elephants, and other wildlife. 農民は、ライトがハイエナ、ゾウ、その他の野生生物を遠ざけることも発見しました。 When National Geographic explorer Paula Kahumbu learned about the lion lights, she invited Richard to give a talk at the TED(Technology, Entertainment, Design) Conference in Long Beach, California. ナショナルジオグラフィック探検家のポーラカハンブがライオンライトについて知ったとき、彼女はリチャードをカリフォルニア州ロングビーチで開催されたTED(テクノロジー、エンターテインメント、デザイン)カンファレンスで講演するよう招待しました。 He flew in an airplane for the first time and spoke to an audience of 1,400 adults. 彼は初めて飛行機に乗って、1,400人の大人の聴衆に話しかけました。 Although he was nervous, he entertained listeners with his personality and charm, and received a standing ovation for his remarkable story. 彼は緊張していましたが、彼の個性と魅力でリスナーを楽しませ、彼の驚くべき物語に対してスタンディングオベーションを受けました。 When asked what he plans to do next, Richard said he wants to become an engineer or an airline pilot. リチャードは次に何をするつもりかと尋ねられたとき、エンジニアまたは航空会社のパイロットになりたいと言いました。 ## Vocabulary Questions Wild animals are free to _wander_ into farming areas. 野生動物は、自由に農地に入ることができる - [ ] escape「逃げる」 - [ ] walk「歩く」 - [ ] trespass「侵入する」 - [x] migrate「移動する」 --- When _predators_ encounter farm animals, they attack. 捕食者が農場の動物に遭遇した時、彼らは攻撃する - [x] meat-eaters - [ ] native species - [ ] protected species - [ ] big cats --- He _got hold of_ some solar panels, an indicator from a motorcycle, and a car battery. 彼はいくつかのソーラーパネル、オートバイのインジケーター、そして車のバッテリーを手に入れました。 - [ ] constructed - [ ] purchased - [ ] borrowed - [x] obtained --- He entertained listeners it his personality and **charm**. - [ ] humor - [x] attractiveness - [ ] good manners - [ ] intelligence ## Discussion
C
UTF-8
1,351
2.9375
3
[]
no_license
/** Author:Monk_ * Topic:inroder and predecessor **/ #include<bits/stdc++.h> using namespace std; #define ll long long #define _for(i,a,b) for(i=a;i<b;i++) #define _rfor(i,a,b) for(i=a;i>=b;i--) #define mp(a,b) make_pair(a,b) void fast(){ std::ios_base::sync_with_stdio(false); cout.tie(NULL); } class Tree{ public: ll data; Tree *left,*right; Tree(ll data){ this->data=data; left=NULL; right=NULL; } Tree(){ data=0; left=NULL; right=NULL; } }; void InWS(Tree *root){ stack<Tree *>st; Tree *curr=root; while(curr!=NULL||(!st.empty())){ while(curr!=NULL){ st.push(curr); curr=curr->left; } curr=st.top(); st.pop(); cout<<curr->data<<" "; curr=curr->right; } } Tree *insert(Tree *root,ll key,pos){ if(root==NULL)return new Tree(key); if(pos%2==0) root->left=insert(root->left,key); else if(pos%2!=0) root->right=insert(root->right,key); } int main(){ fast(); ll N,num,i; Tree *root=NULL; cin>>N; cin>>num; root=insert(root,num); _for(i,2,N+1){ cin>>num; insert(root,num,i); } InWS(root); return 0; }
C++
ISO-8859-1
23,564
2.703125
3
[]
no_license
#include <vector> #include <GL/glfw.h> #include <fstream> #include <iostream> #include <string> #include <time.h> #include <cstdlib> using namespace std; #include "Stuff.hpp" #include "Vec.hpp" #include "OBJ_Model.hpp" OBJ_Model::OBJ_Model():Escala(1),_isAABBStarted(false){}; void OBJ_Model::clear(){ Faces.clear(); Texturas.clear(); AABB.Max.clear(); AABB.Min.clear(); Escala = 1; } OBJ_Model::OBJ_Model(const OBJ_Model& m){ Faces = m.GetFaces(); Texturas = m.GetTexturas(); AABB = m.GetAABB(); _isAABBStarted = m.isAABBStarted(); Escala = m.GetEscala(); }; void OBJ_Model::LoadFromFile(std::string filename){ vector<_Material> Materiales; _Material CurrentMaterial; vector<Vec3d> v; vector<Vec2d> vt; vector<Vec3d> vn; // Reseteamos el modelo anterior, si existe clear(); ifstream file; file.open(filename); string linea; if(!file.is_open()) return; while(!file.eof()){ getline(file,linea); // Trimeamos espacios por delante while(linea[0] == ' ' && linea.size() > 0){ linea.erase(0,1); } // Trimeamos espacios por detras while(linea[linea.size()-1] == ' ' && linea.size() > 0){ linea.erase(linea.size()-1,1); } if(linea.substr(0,7) == "mtllib "){ // Archivo MTL linea.erase(0,7); string ruta = filename; while(ruta[ruta.size()-1] != '/' && ruta.size() > 0){ ruta.erase(ruta.size()-1,1); } ruta += linea; LoadMTLFromFile(ruta, Materiales); } if(linea.substr(0,7) == "usemtl "){ // Si cambiamos de Material linea.erase(0,7); // linea = nombre_del_material for(auto it:Materiales){ if(it.Name == linea) CurrentMaterial = it; } } if(linea.substr(0,2) == "v "){ // Vertices parseV(linea, v); } if(linea.substr(0,3) == "vt "){ // PuntosTextura parseVT(linea, vt); } if(linea.substr(0,3) == "vn "){ // Normales parseVN(linea, vn); } if(linea.substr(0,2) == "f "){ // Caras parseFace(linea,CurrentMaterial,v,vt,vn,Faces); } } // Centramos el objeto como a Isc le gusta for(auto it = Faces.begin(); it!=Faces.end(); it++) for(auto it2 = it->Vertices.begin(); it2!=it->Vertices.end(); it2++){ it2->x -= (AABB.Max.x+AABB.Min.x)/2; it2->y -= AABB.Min.y; it2->z -= (AABB.Max.z+AABB.Min.z)/2; } /*Ahora procesamos LAS CARAS for(int i=0; i<Caras.size(); i++){ string Temp = Caras[i]; if (Temp.substr(0,7) == "usemtl "){ Temp.erase(0,7); //Buscamos entre los materiales uno con el nombre == Temp for(int j=0; j<Materiales.size(); j++) if(Materiales[j].Name == Temp) CurrentMaterial = Materiales[j]; }else{ Temp.erase(0,2); //Quitamos el "f " vector<string> Numeros; // Vamos a sacar el formato // Saco el primer trozo hasta un espacio int Cantidad_Numeros = 1; string Formato = Temp; Formato = Formato.substr(0,Formato.find(" ")); // Vamos a contar las "/" for(int i=0; i<Formato.size(); i++) if(Formato[i] == '/') Cantidad_Numeros++; // Cantidad_Numeros = 1 -> v // Cantidad_Numeros = 2 -> v/vt // Cantidad_Numeros = 3 -> v/vt/vn cout << "Numeros: " << Cantidad_Numeros << endl; //Vamos a separar los puntos por "/" while(Temp.size() > 0 || Temp.find("/") != string::npos){ if(Temp.size() > 0 && Temp.find("/") == string::npos){ //Recogemos el ultimo numero Numeros.push_back(Temp); break; } string Temp2, Temp3; Temp2 = Temp.substr(0,Temp.find("/")); if(Temp2.find(" ") != string::npos){ //Separamos en 2 Temp3 = Temp2.substr(0,Temp2.find(" ")); Numeros.push_back(Temp3); Temp2.erase(0,Temp2.find(" ")+1); } if(Temp2 == ""){Temp2 = "0";} Numeros.push_back(Temp2); Temp.erase(0,Temp.find("/")+1); } // Con todos los datos, hacemos la MAGIA // std::atof(std::string) _Face Face_temp; // Vertices for(int j=0; j<Numeros.size(); j+=3){ Vec3d Vec3d_temp; string vert_temp = Vertices[atof(Numeros[j].c_str())-1]; // Quitamos el "v " del principio vert_temp.erase(0,2); Vec3d_temp.x = atof(vert_temp.substr(0,vert_temp.find(" ")).c_str()); vert_temp.erase(0,vert_temp.find(" ")+1); Vec3d_temp.y = atof(vert_temp.substr(0,vert_temp.find(" ")).c_str()); vert_temp.erase(0,vert_temp.find(" ")+1); Vec3d_temp.z = atof(vert_temp.c_str()); if(Vec3d_temp.x<AABB.Min.x) AABB.Min.x = Vec3d_temp.x; if(Vec3d_temp.y<AABB.Min.y) AABB.Min.y = Vec3d_temp.y; if(Vec3d_temp.z<AABB.Min.z) AABB.Min.z = Vec3d_temp.z; if(Vec3d_temp.x>AABB.Max.x) AABB.Max.x = Vec3d_temp.x; if(Vec3d_temp.y>AABB.Max.y) AABB.Max.y = Vec3d_temp.y; if(Vec3d_temp.z>AABB.Max.z) AABB.Max.z = Vec3d_temp.z; Face_temp.Vertices.push_back(Vec3d_temp); } // PuntosTextura if(Cantidad_Numeros < 2) Face_temp.PuntosTextura.push_back(Vec2d(0,0)); else for(int j=1; j<Numeros.size(); j+=3){ Vec2d Vec2d_temp; string ptex_temp = PuntosTextura[atof(Numeros[j].c_str())-1]; // Quitamos el "vt " del principio ptex_temp.erase(0,3); Vec2d_temp.x = atof(ptex_temp.substr(0,ptex_temp.find(" ")).c_str()); ptex_temp.erase(0,ptex_temp.find(" ")+1); Vec2d_temp.y = atof(ptex_temp.c_str()); Face_temp.PuntosTextura.push_back(Vec2d_temp); } // Normales if(Cantidad_Numeros < 3) Face_temp.Normales.push_back(Vec3d(0,0,0)); else for(int j=2; j<Numeros.size(); j+=3){ Vec3d Vec3d_temp; string norm_temp = Normales[atof(Numeros[j].c_str())-1]; // Quitamos el "vn " del principio norm_temp.erase(0,3); Vec3d_temp.x = atof(norm_temp.substr(0,norm_temp.find(" ")).c_str()); norm_temp.erase(0,norm_temp.find(" ")+1); Vec3d_temp.y = atof(norm_temp.substr(0,norm_temp.find(" ")).c_str()); norm_temp.erase(0,norm_temp.find(" ")+1); Vec3d_temp.z = atof(norm_temp.c_str()); Face_temp.Normales.push_back(Vec3d_temp); } // Material Face_temp.Material = CurrentMaterial; Faces.push_back(Face_temp); } } for(auto it = Faces.begin(); it!=Faces.end(); it++) for(auto it2 = it->Vertices.begin(); it2!=it->Vertices.end(); it2++){ it2->x -= (AABB.Max.x+AABB.Min.x)/2; it2->y -= AABB.Min.y; it2->z -= (AABB.Max.z+AABB.Min.z)/2; } AABB.Max.x -= (AABB.Max.x+AABB.Min.x)/2; AABB.Max.y -= AABB.Min.y; AABB.Max.z -= (AABB.Max.z+AABB.Min.z)/2; AABB.Max = (AABB.Max-AABB.Min)/2; AABB.Max.y *= 2; AABB.Min = -AABB.Max; AABB.Min.y = 0;*/ //DebugFaces(); } void OBJ_Model::parseV(string line, vector<Vec3d> &v){ v.push_back(Vec3d()); sscanf(line.c_str(), "v %lf %lf %lf %lf", &v.back().x, &v.back().y, &v.back().z); if(!_isAABBStarted){ _isAABBStarted = true; AABB.Min = AABB.Max = v.back(); return; } if(v.back().x<AABB.Min.x) AABB.Min.x = v.back().x; if(v.back().y<AABB.Min.y) AABB.Min.y = v.back().y; if(v.back().z<AABB.Min.z) AABB.Min.z = v.back().z; if(v.back().x>AABB.Max.x) AABB.Max.x = v.back().x; if(v.back().y>AABB.Max.y) AABB.Max.y = v.back().y; if(v.back().z>AABB.Max.z) AABB.Max.z = v.back().z; } void OBJ_Model::parseVT(string line, vector<Vec2d> &vt){ vt.push_back(Vec2d()); sscanf(line.c_str(), "vt %lf %lf %lf", &vt.back().x, &vt.back().y); } void OBJ_Model::parseVN(string line, vector<Vec3d> &vn){ vn.push_back(Vec3d()); sscanf(line.c_str(), "vn %lf %lf %lf %lf", &vn.back().x, &vn.back().y, &vn.back().z); } void OBJ_Model::parseFace(string line, _Material Material, vector<Vec3d> &v, vector<Vec2d> &vt, vector<Vec3d> &vn, vector<_Face> &f){ // Quitamos "f " del principio line.erase(0,2); // Creamos un vector cortando por los " " vector<string> Bloque; while(line.find(" ") != string::npos){ //cout << line.substr(0,line.find(" ")) << endl; Bloque.push_back(line.substr(0,line.find(" "))); line.erase(0, line.find(" ")+1); } //cout << line << endl; Bloque.push_back(line); //cout << endl; /*for(int i = 0; i < Bloque.size(); i++){ cout << Bloque[i] << endl; } cout << endl;*/ int Estilo = 0; /* Miramos que Estilo tiene 1 - v 2 - v/vt 3 - v//vn 4 - v/vt/vn */ float Basura = 0; int Resultado = 0; Resultado = sscanf(Bloque[0].c_str(), "%f/%f/%f", &Basura, &Basura, &Basura); if(Resultado == 3) Estilo = 4; // v/vt/vn if(Resultado == 2) Estilo = 2; // v/vt if(Resultado == 1){ // Puede ser o "v" o "v//vn" Resultado = sscanf(Bloque[0].c_str(), "%f//%f", &Basura, &Basura); if(Resultado == 2) Estilo = 3; // v//vn if(Resultado == 1) Estilo = 1; // v } /*cout << "Tipo: " << Estilo << endl; cout << endl << endl;*/ // Hasta aqui funciona perfecto vector<int> Numeros; switch(Estilo){ case 1: for(int i = 0; i < Bloque.size(); i++){ Numeros.push_back(atoi(Bloque[i].c_str())); } break; case 2: for(int i = 0; i < Bloque.size(); i++){ int temp[2]; sscanf(Bloque[i].c_str(),"%i/%i",&temp[0], &temp[1]); Numeros.push_back(temp[0]); Numeros.push_back(temp[1]); } break; case 3: for(int i = 0; i < Bloque.size(); i++){ int temp[2]; sscanf(Bloque[i].c_str(),"%i//%i",&temp[0], &temp[1]); Numeros.push_back(temp[0]); Numeros.push_back(temp[1]); } break; case 4: for(int i = 0; i < Bloque.size(); i++){ int temp[3]; sscanf(Bloque[i].c_str(),"%i/%i/%i",&temp[0], &temp[1], &temp[2]); Numeros.push_back(temp[0]); Numeros.push_back(temp[1]); Numeros.push_back(temp[2]); } break; default: break; } /* Comprobamos los numeros for(int i = 0; i < Numeros.size(); i++){ cout << Numeros[i] << " "; } cout << endl;*/ // Hasta aqui va perfecto // Ahora tenemos los id de los Vertices a juntar // Rellenamos la Face_Temp _Face Face_Temp; Face_Temp.Estilo = Estilo; switch(Estilo){ case 1: for(int i = 0; i < Numeros.size(); i++) Face_Temp.Vertices.push_back(v[Numeros[i]-1]); break; case 2: for(int i = 0; i < Numeros.size(); i+=2){ Face_Temp.Vertices.push_back(v[Numeros[i]-1]); Face_Temp.PuntosTextura.push_back(vt[Numeros[i+1]-1]); } break; case 3: for(int i = 0; i < Numeros.size(); i+=2){ Face_Temp.Vertices.push_back(v[Numeros[i]-1]); Face_Temp.Normales.push_back(vn[Numeros[i+1]-1]); } break; case 4: for(int i = 0; i < Numeros.size(); i+=3){ //cout << "V[" << v[Numeros[i]-1].x << ", " << v[Numeros[i]-1].y << ", " << v[Numeros[i]-1].z << "]" << endl; Face_Temp.Vertices.push_back(v[Numeros[i]-1]); Face_Temp.PuntosTextura.push_back(vt[Numeros[i+1]-1]); Face_Temp.Normales.push_back(vn[Numeros[i+2]-1]); } break; default: break; } //cout << endl; Face_Temp.Material = Material; f.push_back(Face_Temp); } void OBJ_Model::LoadMTLFromFile(std::string filename, vector<_Material> &Materiales){ // Rellenar esta struct /* struct _Textura{ string Ruta; GLuint Textura; }; struct _Material{ string Name; _Textura *Textura; GLfloat Ambiente[4]; GLfloat Difusa[4]; GLfloat Especular[4]; };*/ // Name = Nombre del material // Textura.Ruta = RUta de la textura del material // Ambiente[4] = (x), (y), (z), (1.0) // Difusa[4] = (x), (y), (z), (1.0) // Especular[4] = (x), (y), (z), (1.0) // Cuando leemos un nuevo nombre de textura, lo aadimos al vector<_Textura> Texturas // Pero antes de aadirlo, comprobamos que no haya otra textura con la misma ruta // Una vez tengamos todos los materiales apuntando a _Textura del vector, las cargamos // Se podr acceder a la textura usando _Face._Material._Textura.Textura // Suerte, que hoy tengo musica hasta las 19:00 ifstream file; file.open(filename); string linea; _Material Mat_Temp; // Inicializamos los Boolean Mat_Temp.HayAmbiente = false; Mat_Temp.HayDifusa = false; Mat_Temp.HayEspecular = false; Mat_Temp.HayTextura = false; if(!file.is_open()) return; while(!file.eof()){ getline(file,linea); // Trimeamos espacios por delante while((linea[0] == ' ' || linea[0] == '\t') && linea.size() > 0){ linea.erase(0,1); } // Trimeamos espacios por detras while((linea[linea.size()-1] == ' ' || linea[linea.size()-1] == '\t') && linea.size() > 0){ linea.erase(linea.size()-1,1); } if(linea.substr(0,3) == "Ka "){ // Ambiente linea.erase(0,3); Mat_Temp.Ambiente[0] = (float)atof(linea.substr(0,linea.find(" ")).c_str()); linea.erase(0,linea.find(" ")+1); Mat_Temp.Ambiente[1] = (float)atof(linea.substr(0,linea.find(" ")).c_str()); linea.erase(0,linea.find(" ")+1); Mat_Temp.Ambiente[2] = (float)atof(linea.c_str()); Mat_Temp.Ambiente[3] = 1.0; Mat_Temp.HayAmbiente = true; } if(linea.substr(0,3) == "Kd "){ // Difusa linea.erase(0,3); Mat_Temp.Difusa[0] = (float)atof(linea.substr(0,linea.find(" ")).c_str()); linea.erase(0,linea.find(" ")+1); Mat_Temp.Difusa[1] = (float)atof(linea.substr(0,linea.find(" ")).c_str()); linea.erase(0,linea.find(" ")+1); Mat_Temp.Difusa[2] = (float)atof(linea.c_str()); Mat_Temp.Difusa[3] = 1.0; Mat_Temp.HayDifusa = true; } if(linea.substr(0,3) == "Ks "){ // Especular linea.erase(0,3); Mat_Temp.Especular[0] = (float)atof(linea.substr(0,linea.find(" ")).c_str()); linea.erase(0,linea.find(" ")+1); Mat_Temp.Especular[1] = (float)atof(linea.substr(0,linea.find(" ")).c_str()); linea.erase(0,linea.find(" ")+1); Mat_Temp.Especular[2] = (float)atof(linea.c_str()); Mat_Temp.Especular[3] = 1.0; Mat_Temp.HayEspecular = true; } if(linea.substr(0,7) == "map_Kd "){ // Textura linea.erase(0,7); string ruta = filename; while(ruta[ruta.size()-1] != '/' && ruta.size() > 0){ ruta.erase(ruta.size()-1,1); } ruta += linea; Mat_Temp.Textura = _LoadTexture(ruta); Mat_Temp.HayTextura = true; } if(linea.substr(0,7) == "newmtl "){ // Nuevo Material // Si habia un material anterior, lo guardamos if(Mat_Temp.Name != "") Materiales.push_back(Mat_Temp); // Reseteamos el Mat_Temp for(int i=0; i<4; i++){ Mat_Temp.Ambiente[i] = 0; Mat_Temp.Difusa[i] = 0; Mat_Temp.Especular[i] = 0; } Mat_Temp.HayAmbiente = false; Mat_Temp.HayDifusa = false; Mat_Temp.HayEspecular = false; Mat_Temp.HayTextura = false; // Aplicamos el nombre al material linea.erase(0,7); Mat_Temp.Name = linea; } } // Aadimos el ultimo material Materiales.push_back(Mat_Temp); /*for(int i=0; i<Materiales.size(); i++){ cout << "-----------------------------------" << endl; cout << " Material: " << Materiales[i].Name << endl; cout << " Ka "; for(int i=0; i<4; i++) cout << Materiales[i].Ambiente[i] << " , "; cout << endl; cout << " Kd "; for(int i=0; i<4; i++) cout << Materiales[i].Difusa[i] << " , "; cout << endl; cout << " Ks "; for(int i=0; i<4; i++) cout << Materiales[i].Especular[i] << " , "; cout << endl; cout << " Ruta: " << Materiales[i].Textura.Ruta << endl; }*/ } void OBJ_Model::DebugFaces()const{ cout << "-----------------------------------" << endl; cout << " Cantidad de Caras: " << Faces.size() << endl; for(int i=0; i<Faces.size(); i++){ cout << "-----------------------------------" << endl; cout << " Cara " << i << endl; cout << "-----------------------------------" << endl; for(int j=0; j<Faces[i].Vertices.size(); j++){ cout << " v" << j << " >> "; cout << Faces[i].Vertices[j].x << " , "; cout << Faces[i].Vertices[j].y << " , "; cout << Faces[i].Vertices[j].z << endl; } cout << "-----------------------------------" << endl; for(int j=0; j<Faces[i].PuntosTextura.size(); j++){ cout << " vt" << j << " >> "; cout << Faces[i].PuntosTextura[j].x << " , "; cout << Faces[i].PuntosTextura[j].y << endl; } cout << "-----------------------------------" << endl; for(int j=0; j<Faces[i].Normales.size(); j++){ cout << " vn" << j << " >> "; cout << Faces[i].Normales[j].x << " , "; cout << Faces[i].Normales[j].y << " , "; cout << Faces[i].Normales[j].z << endl; } cout << "-----------------------------------" << endl; cout << " Material: " << Faces[i].Material.Name << endl; cout << " Ka "; for(int j=0; j<4; j++) cout << Faces[i].Material.Ambiente[j] << " , "; cout << endl; cout << " Kd "; for(int j=0; j<4; j++) cout << Faces[i].Material.Difusa[j] << " , "; cout << endl; cout << " Ks "; for(int j=0; j<4; j++) cout << Faces[i].Material.Especular[j] << " , "; cout << endl; } } void OBJ_Model::Render()const{ //srand(time(NULL)); for(int i=0; i<Faces.size(); i++){ //glEnable(GL_LIGHTING); glColor3f(255,255,255); //glEnable(GL_LIGHTING); if(Faces[i].Material.HayAmbiente) glMaterialfv(GL_FRONT, GL_AMBIENT, Faces[i].Material.Ambiente); if(Faces[i].Material.HayDifusa) glMaterialfv(GL_FRONT, GL_DIFFUSE, Faces[i].Material.Difusa); if(Faces[i].Material.HayEspecular) glMaterialfv(GL_FRONT, GL_SPECULAR, Faces[i].Material.Especular); // El brillo especular pequeo (0 - 255). glMaterialf(GL_FRONT, GL_SHININESS, 20); if(Faces[i].Material.HayTextura){ glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, Faces[i].Material.Textura); }else{ glColor3f(Faces[i].Material.Difusa[0], Faces[i].Material.Difusa[1], Faces[i].Material.Difusa[2]); } glBegin(GL_POLYGON); for(int j=0; j<Faces[i].Vertices.size(); j++){ // Texturas if(Faces[i].Estilo == 2 || Faces[i].Estilo == 4) glTexCoord2f(Faces[i].PuntosTextura[j].x, Faces[i].PuntosTextura[j].y); // Normales if(Faces[i].Estilo == 3 || Faces[i].Estilo == 4) glNormal3d(Faces[i].Normales[j].x, Faces[i].Normales[j].y, Faces[i].Normales[j].z); // Vertices glVertex3d(Faces[i].Vertices[j].x, Faces[i].Vertices[j].y, Faces[i].Vertices[j].z); } glEnd(); glDisable(GL_TEXTURE_2D); //glDisable(GL_LIGHTING); /*glColor3f(0,255,0); glLineWidth(3); glBegin(GL_LINE_LOOP); for(int j=0; j<Faces[i].Vertices.size(); j++){ // Texturas if(Faces[i].Estilo == 2 || Faces[i].Estilo == 4) glTexCoord2f(Faces[i].PuntosTextura[j].x, Faces[i].PuntosTextura[j].y); // Normales if(Faces[i].Estilo == 3 || Faces[i].Estilo == 4) glNormal3d(Faces[i].Normales[j].x, Faces[i].Normales[j].y, Faces[i].Normales[j].z); // Vertices glVertex3d(Faces[i].Vertices[j].x, Faces[i].Vertices[j].y, Faces[i].Vertices[j].z); } glEnd(); glLineWidth(1);*/ } } GLuint OBJ_Model::_LoadTexture(std::string TextureName){ if(TextureName != ""){ if(Texturas.find(TextureName) == Texturas.end()){ // No encontrado Texturas[TextureName] = LoadTexture(TextureName.c_str()); } //cout << Texturas[TextureName] << endl; return Texturas[TextureName]; }else{ return -1; } } void OBJ_Model::InvertirX(){ double t = AABB.GetCenter().x; for(auto it0=Faces.begin(); it0!=Faces.end(); it0++) for(auto it=it0->Vertices.begin(); it!=it0->Vertices.end(); it++) it->x = 2*t - it->x; } void OBJ_Model::InvertirY(){ double t = AABB.GetCenter().y; for(auto it0=Faces.begin(); it0!=Faces.end(); it0++) for(auto it=it0->Vertices.begin(); it!=it0->Vertices.end(); it++) it->y = 2*t - it->y; } void OBJ_Model::InvertirZ(){ double t = AABB.GetCenter().z; for(auto it0=Faces.begin(); it0!=Faces.end(); it0++) for(auto it=it0->Vertices.begin(); it!=it0->Vertices.end(); it++) it->z = 2*t - it->z; } void OBJ_Model::SetEscala(double esc){ double t = esc/Escala; for(auto it0=Faces.begin(); it0!=Faces.end(); it0++) for(auto it=it0->Vertices.begin(); it!=it0->Vertices.end(); it++) *it *=t; Escala = esc; AABB.Max *=t; AABB.Min *=t; } Vec3d OBJ_Model::GetCenter()const{ Vec3d t = (AABB.Max+AABB.Min)/2; t.y = GetAABB().Min.y; return t; } bool OBJ_Model::isAABBStarted()const{ return _isAABBStarted; }
Java
UTF-8
3,855
2.59375
3
[]
no_license
import java.awt.Color; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Scanner; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.JPanel; public class Main extends JPanel implements MouseListener{ private BufferedImage base; private int[][] correct = new int[4][4]; private int[][] board = new int[4][4]; private int[][] hints = new int[4][4]; private int[][] places1 = new int[][]{{106,210},{212,210},{318,210},{426,210}, {106,318},{212,318},{318,318},{426,318}, {106,426},{212,426},{318,426},{426,426}, {106,530},{212,530},{318,530},{426,530}}; private int[][] places2 = new int[][]{{106,106},{212,106},{318,106},{424,106}, {530,210},{530,318},{530,426},{530,530}, {426,640},{318,640},{212,640},{106,640}, {0,530},{0,426},{0,318},{0,210}}; Font font = new Font("Times New Roman", 0, 126); Font wonF = new Font("Times New Roman", 0, 126); private boolean won = false; public static void main(String[] args) { JFrame j = new JFrame(); Main main = new Main(); j.setResizable(false); j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); j.add(main); j.pack(); j.setLocationRelativeTo(null); j.setTitle("Towers Alpha vs. 0.0.143"); j.setVisible(true); } public Main(){ setPreferredSize(new Dimension(640,640)); setFocusable(true); addMouseListener(this); try { base = ImageIO.read(ImageIO.class.getResourceAsStream("/Base.png")); System.out.println("images loaded"); } catch (IOException e) { System.err.println("could not load images"); e.printStackTrace(); } loadMap("Level1"); for(int x = 0; x < 4; x++){ for(int y = 0; y < 4; y++){ board[x][y] = 1; } } } public void paintComponent(Graphics g){ super.paintComponent(g); if(!won){ g.setFont(font); g.drawImage(base, 0, 0, null); g.setColor(Color.red); for(int x = 0; x < 4;x++){ for(int y = 0; y < 4; y++){ g.drawString(String.valueOf(board[x][y]), places1[x+y*4][0] + 22, places1[x+y*4][1]-2); } } g.setColor(Color.blue); for(int x = 0; x < 4;x++){ for(int y = 0; y < 4; y++){ g.drawString(String.valueOf(hints[x][y]), places2[x+y*4][0] + 22, places2[x+y*4][1]-2); } } }else{ g.setFont(wonF); g.setColor(Color.black); g.drawString("You Won", 60, 300); } } public void loadMap(String fileName){ Scanner in = new Scanner(getClass().getResourceAsStream("Level1")); String fir = in.nextLine(); String sec = in.nextLine(); in.close(); String[] firC = fir.split(""); String[] secC = sec.split(""); for(int x = 0; x < 4; x++){ for(int y = 0; y < 4; y++){ correct[x][y] = Integer.parseInt(firC[x + y*4]); hints[x][y] = Integer.parseInt(secC[x + y*4]); } } } public void mouseClicked(MouseEvent e) { int x = (int)(e.getX()/106)-1; int y = (int)(e.getY()/106)-1; if(!(x >= 0 && x <= 3 && y >= 0 && y <= 3))return; board[x][y]++; if(board[x][y] > 4)board[x][y] = 1; boolean w = true; for(int xc = 0; xc < 4; xc++){ for(int yc = 0; yc < 4;yc++){ if(board[xc][yc] != correct[xc][yc])w = false; } } if(w)won = true; repaint(); } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } }
Shell
UTF-8
6,120
3.90625
4
[ "MIT" ]
permissive
#!/usr/bin/env bash # # Minimalistic SSH deployment. # # Author: Artem Sapegin, sapegin.me # License: MIT # # Inspired by: # https://github.com/visionmedia/deploy # http://gleero.com/all/remote-ssh/ # PROGRAM=$(basename "$0") VERSION="0.4.0" CONFIG_DIR=$(pwd) CONFIG_NAME=.shipit CONFIG= TARGET=deploy SSH_HOST= SSH_PATH= VERBOSE= # Common stuff RED="$(tput setaf 1)" GREEN="$(tput setaf 2)" WHITE="$(tput setaf 7)" CYAN="$(tput setaf 6)" UNDERLINE="$(tput sgr 0 1)" BOLD="$(tput bold)" NOCOLOR="$(tput sgr0)" function header() { echo -e "$UNDERLINE$CYAN$1$NOCOLOR\n"; } function error() { echo -e "$UNDERLINE$RED$1$NOCOLOR\n"; } # Print usage information usage() { version echo echo "Usage: $PROGRAM [option] <command>" echo echo "Commands:" echo echo " <target> Execute <target> target on remote host" echo " list ls Print list of available targets" echo " console shell, ssh Open an SSH session on the remote host" echo " exec <cmd> run Execute <cmd> on the remote host" echo " copy <file> cp Copy <files> to the remote host" echo " --version -V Print program version" echo " --help -h Print help (this screen)" echo echo "Options:" echo echo " -c, --config Config file name (default: .shipit)" echo " -r, --remote Override remote host" echo " -v, --verbose Enable verbose mode for SSH" echo } # Print error message and exit abort() { echo error "$@" exit 1 } # Print version number version() { echo echo "$PROGRAM v$VERSION" } # Enable verbose mode set_verbose() { VERBOSE="1" } # Set config file name set_config_file() { test -z "$1" && abort 'File name is required for --config/-c option.' CONFIG_NAME="$1" } # Set remote host set_remote_host() { test -z "$1" && abort 'Hostname is required for --remote/-r option.' SSH_HOST="$1" } # Print squirrel squirrel() { echo "$WHITE" echo " __ (\\_ ⎧ ⎻⎻⎻⎻⎻⎻⎻⎻⎫" echo " (_ \\ ( $GREEN$BOLD'$NOCOLOR$WHITE> 〈 SHIP IT!⎟" echo " ) \\/_)= ⎩ ⎽⎽⎽⎽⎽⎽⎽⎽⎭" echo " (_(_ )_" echo "$NOCOLOR" } # Traverse upwards until we find the config file find_config() { while [ ! -f "$CONFIG_DIR/$CONFIG_NAME" ]; do if [ "$CONFIG_DIR" == "/" ]; then break; fi CONFIG_DIR=$(dirname "$CONFIG_DIR") done if [ -f "$CONFIG_DIR/$CONFIG_NAME" ]; then CONFIG="$CONFIG_DIR/$CONFIG_NAME" fi } # Read and validate config file read_config() { local config find_config # Check config file existance test -f "$CONFIG" || abort "Config file $CONFIG_NAME not found." # Read and eval first section config=$(awk '/^/ {print; exit}' RS= $CONFIG) eval $config # Check required params test -z "$host" && incomplete_config 'host' test -z "$path" && incomplete_config 'path' test -z "$host" || test -z "$path" && exit 1 # Expose params SSH_HOST="${SSH_HOST:-$host}" SSH_PATH=$path } # Print message about missing config param incomplete_config() { error "Incomplete config: '$1' not defined." } # Deploy specified target deploy() { local local_script local remote_script read_config # Check target existance target_exists $TARGET || abort "Target $TARGET not found in config file." # Ship it! header "Shipping $TARGET..." # Read local script local_script=$(awk "/^\[$TARGET:local\]/ {print; exit}" RS= $CONFIG | sed 1d) if [ -n "$local_script" ]; then header "Running local script..." run_local "$local_script" if [ $? -ne 0 ]; then abort "Deploy wasn’t successful: local script failed." fi fi # Read remote script remote_script=$(awk "/^\[$TARGET\]/ {print; exit}" RS= $CONFIG | sed 1d) if [ -n "$remote_script" ]; then header "Running remote script at $SSH_HOST..." run_remote "$remote_script" if [ $? -ne 0 ]; then abort "Deploy wasn’t successful: remote script failed." fi fi # Shipped? if [ $? -eq 0 ]; then squirrel fi } # Check if config <section> exists target_exists() { grep "^\[$1\(:local\)\?\]" $CONFIG &> /dev/null } # Run script or command via SSH with cd to remote path run_remote() { # 1. Connect to remote host (-A enables forwarding of the authentication agent connection). # 2. Configure shell to exit on first erorr (set -e). # 3. Check destination directory. # 4. Open destination directory. # 5. Run script. local script=""" set -e test -d \"$SSH_PATH\" || { echo \"${RED}Remote directory $SSH_PATH doesn’t exist.$NOCOLOR\"; exit 1; } cd \"$SSH_PATH\" $1 """ local verbose= if [ -n "$VERBOSE" ]; then verbose="-v" fi ssh $verbose -A $2 "$SSH_HOST" "$script" } # Run local script # Stop script execution and return 0 on first error run_local() { trap "{ return 0; trap - ERR; }" ERR eval "$1" trap - ERR } # Print available targets list_targets() { read_config header "Available shipit targets:" awk '/^\[/ {gsub(":local", "", $1); print "• " $1}' $CONFIG | tr -d '][' | sort | uniq } # Open remote terminal open_console() { read_config header "Opening terminal on $SSH_HOST..." run_remote "\$SHELL --login" "-t" } # Execute command via SSH exec_command() { read_config header "Executing $* on $SSH_HOST..." run_remote "$*" } # Copy local file to remote host copy_to_remote() { read_config test -f "$1" || abort "Local file $1 not found." header "Copying $1 to $SSH_HOST..." scp "$1" "$SSH_HOST:$SSH_PATH/$1" } ######################################################################################################################## # Parse CLI arguments # Options for arg in "$@"; do case "$arg" in -v|--verbose) set_verbose; shift ;; -c|--config) set_config_file "$2"; shift; shift ;; -r|--remote) set_remote_host "$2"; shift; shift ;; esac done # Commands arg=$1; shift if [ -n "$arg" ]; then case $arg in -h|--help) usage; exit ;; -V|--version) version; exit ;; list|ls) list_targets; exit ;; console|shell|ssh) open_console; exit ;; exec|run) exec_command "$@"; exit ;; copy|cp) copy_to_remote "$@"; exit ;; *) TARGET="$arg" ;; esac fi # Run specified target deploy
Python
UTF-8
3,592
2.515625
3
[]
no_license
""" Daniel Maidment [email protected] """ import os import numpy as np import matplotlib.pyplot as plt import matplotlib.ticker as ticker import matplotlib import time import pandas as pd import scipy.io import scipy.signal as signal import scipy.linalg as linalg import warnings from numpy import pi from numpy import cos from numpy import sin from numpy import log10 from numpy import log from numpy import real from numpy import imag from numpy import sqrt from numpy import e from numpy import abs from numpy import angle from numpy.fft import fft from numpy.fft import ifft from numpy.fft import fftshift from numpy import min from numpy import max from numpy import sum from numpy.linalg import norm from numpy import dot from sklearn.preprocessing import normalize from latex_envs.latex_envs import figcaption """#########################################################################""" # $\renewcommand{\vec}{\mathbf}$ # $\newcommand{\x}{\vec{x}}$ # $\newcommand{\s}{\vec{s}}$ # $\renewcommand{\phi}{\varphi}$ # $\newcommand{\R}{\mathbb{R}}$ # $\newcommand{\y}{\vec{y}}$ # $\newcommand{\v}{\vec{v}}$ # $\newcommand{\A}{\vec{A}}$ # $\newcommand{\w}{\;\!}$ # \begin{equation} # \x,\R, \s, \phi, \Phi, \y, \Psi, \v, \A # \end{equation} #for Jupyter Notebook inline plots # %matplotlib inline """#########################################################################""" #C:\Users\Purco\Anaconda3\Lib\site-packages\matplotlib\mpl-data\stylelib #plt.style.use('report_2_color') # plt.style.use('report_2_grey') # plt.style.use('jupyter_grey') # plt.style.use('jupyter_color') # plt.style.use('dark_background')# for dark Themes #plt.style.use('fast') #turns off automatic plt.plot display, use plt.show() to re-enable plt.ioff() #Turn off pesky from Future Warnings warnings.simplefilter(action='ignore', category=FutureWarning) def config_axis(ax = None, x_lim = None, y_lim = None, X_0 = None, Y_0 = None, grd = True, minorgrd = False, mult_x = 0.2, mult_y = 0.2, Eng = True): if(X_0 != None): ax.xaxis.set_major_locator(ticker.MultipleLocator(mult_x*X_0)) ax.xaxis.set_minor_locator(ticker.MultipleLocator((mult_x/5)*X_0)) if(Eng): ax.xaxis.set_major_formatter(ticker.EngFormatter()) ax.yaxis.set_major_formatter(ticker.EngFormatter()) if(Y_0 != None): ax.yaxis.set_major_locator(ticker.MultipleLocator(mult_y*Y_0)) ax.yaxis.set_minor_locator(ticker.MultipleLocator(mult_y/5*Y_0)) if(grd == True): ax.grid(b = True, which = 'major', axis = 'both') else: ax.grid(b = False, which = 'major', axis = 'both') if(minorgrd == True): ax.grid(b = True, which = 'minor', axis = 'both') else: ax.grid(b = False, which = 'minor', axis = 'both') if(x_lim != None): ax.set_xlim(x_lim) if(y_lim != None): ax.set_ylim(y_lim) return ax """#########################################################################""" def decimate(x_arr, factor = 1): N = len(x_arr) M = int(N/factor) y_arr = [] for i in np.arange(0, N, factor): y_arr.append(x_arr[i]) return y_arr def apply_window(arr, win = 'None', beta = 8.6): M = len(arr) if(win == 'bartlett'): window = np.bartlett(M) elif(win == 'hamming'): window = np.hamming(M) elif(win == 'hanning'): window = np.hanning(M) elif(win == 'kaiser'): window = np.kaiser(M, beta = beta) elif(win == 'blackman'): window = np.blackman(M) elif(win == 'None'): window = np.ones(M) else: window = np.ones(M) ret_arr = np.multiply(arr, window) return ret_arr
Python
UTF-8
4,506
2.859375
3
[]
no_license
import pandas as pd import os class StartFunction(dict): def __init__(self, value, family="S"): self[0] = value self.family = family def __hash__(self): return hash(self.family) #Dados experimentais alfa = 8.414499908 beta = 0.1969820003 gama = -15.31551146 mort = 0.823/100 #livre para variar R0 = 2.79 #livre para variar S0 = 210000000 #Constantes M0 = alfa + gama kc = (beta * R0)/(S0*(R0 - 1)) fat = mort * (beta/(R0 - 1)) kr = (1 - mort) * (beta/(R0 - 1)) I0 = alfa*beta/fat #Estado Inicial S, I, R, M = {},{},{},{} I = StartFunction(I0, "I") R = StartFunction(((1-mort)/mort) * M0, "R") M = StartFunction(M0, "M") S = StartFunction(S0 - I[0] - R[0] - M[0], "S") #Realidade dos leitos brasileiros taxa_de_hospitalização = 2.67/100 total_de_leitos = 42630 #Diferenciais def d_dt(f): if f == S: return lambda s, i, r, m, t: -kc*s*i elif f == I: return lambda s, i, r, m, t: (kc*s - kr - fat)*i elif f == R: return lambda s, i, r, m, t: kr*i else: return lambda s, i, r, m, t: fat * i #Condições da simulação leitos_limitados = True lockdown_vertical = False steps = 10 dt = 1/steps dias = 15 #Variáveis da iteração total_de_mortos_sem_leito = 0 table = [] d = -1 while I[d + 1] > 1: d += 1 # Joga os valores na tabela print("dia {}\n" "S:{:.3f}\n" "I:{:.3f}\n" "R:{:.3f}\n" "M:{:.3f}\n" "Soma: {:.3f}" "\n".format(d, S[d], I[d], R[d], M[d], S[d] + I[d] + R[d] + M[d])) table.append([f[d] for f in (S, I, R, M)]) #Salvando número de recuperados no dia anterior R_ant = R[d] #Implementação do algoritmo Runge-Kutta for i in range(0, steps): t = 10000*i + d k = dict() #Determinação dos k1s for f in (S, I, R, M): k[(f, 1)] = dt*(d_dt(f)(S[t], I[t], R[t], M[t], t)) #Determinação dos k2s for f in (S, I, R, M): k[(f, 2)] = dt*(d_dt(f)(S[t] + k[(S, 1)]/2, I[t] + k[(I, 1)]/2, R[t] + k[(R, 1)]/2, M[t] + k[(M, 1)]/2, t + dt/2)) #Determinação dos k3s for f in (S, I, R, M): k[(f, 3)] = dt*(d_dt(f)(S[t] + k[(S, 2)]/2, I[t] + k[(I, 2)]/2, R[t] + k[(R, 2)]/2, M[t] + k[(M, 2)]/2, t + dt/2)) #Determinação dos k4s for f in (S, I, R, M): k[(f, 4)] = dt * (d_dt(f)(S[t] + k[(S, 3)], I[t] + k[(I, 3)], R[t] + k[(R, 3)], M[t] + k[(M, 3)], t + dt)) #Atualização dos valores das funções for f in (S, I, R, M): f[t + 10000] = f.pop(t) + (k.pop((f, 1)) + 2*k.pop((f, 2)) + 2*k.pop((f, 3)) + k.pop((f, 4)))/6 for f in (S, I, R, M): f[d + 1] = f.pop(t + 10000) #condição de leitos limitados if I[d + 1] * taxa_de_hospitalização > total_de_leitos and leitos_limitados: # Roda se leitos não forem suficientes R[d] = R_ant Recuperariam = R[d + 1] - R[d] # Número de pessoas que se recuperariam se houvessem leitos suficientes if Recuperariam > total_de_leitos / taxa_de_hospitalização: # Limita o número de recuperados dentre os que precisariam ser internados ao número de internações possíveis Recuperam = (1 - taxa_de_hospitalização) * Recuperariam + total_de_leitos M_semleito = Recuperariam - Recuperam total_de_mortos_sem_leito += M_semleito print("No dia {}, morreram {:.0f} pessoas sem leito".format(d + 1, M_semleito)) R[d + 1] = Recuperam + R[d] M[d + 1] += M_semleito #condição de lockdown vertical no dia 1 de Abril if d == 18 and lockdown_vertical: kc = kc * 1.5 print("{} pessoas morreram sem leito".format(total_de_mortos_sem_leito)) #Exporta os dados como um arquivo .csv sufixo = "RK_R{}_mort{}_{}leitos".format(*["{:.2f}".format(n).replace(".", "-") for n in (R0, 100*mort)],total_de_leitos) data = pd.DataFrame(table, index=list(range(d+1)), columns=list("SIRM")) data.to_csv(os.getcwd() + "\\output" + sufixo + ".csv")
C#
UTF-8
1,020
4.15625
4
[]
no_license
using System; namespace Task2 { class Program { static void Main(string[] args) { // Make a console application called SumOfEven. // Inside it create an array of 6 integers. // Get numbers from the input, find and print the sum of the even numbers // from the array: int[] givenArray = new int[6]; int sumOfEvenNo = 0; int i = 0; while(i<=5) { Console.WriteLine("Please enter a number!"); bool parsedOK = int.TryParse(Console.ReadLine(), out int userInputNo); if(parsedOK) { if(userInputNo%2==0) { sumOfEvenNo += userInputNo; } givenArray[i] = userInputNo; i++; } } Console.WriteLine("The sum of the entered numbers is " + sumOfEvenNo); } } }
Python
UTF-8
8,741
3.140625
3
[]
no_license
r"""Language model with RNN layers. Usage: import lmp model = lmp.model.BaseRNNModel(...) logits = model(...) pred = model.predict(...) """ # built-in modules from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals # 3rd-party modules import torch import torch.nn class BaseRNNModel(torch.nn.Module): r"""Language model with pure RNN layers. Each input token will first be embedded into vectors, then project to hidden dimension. We then sequentially feed vectors into RNN layer(s). Output vectors of RNN layer(s) then go through fully-connected layer(s) and project back to embedding dimension in order to perform vocabulary prediction. In the comment below, we use following symbols to denote the size of each tensors: B: Batch size. S: Sequence length. E: Embedding dimension. V: Vocabulary size. H: Hidden dimension. Args: d_emb: Embedding matrix vector dimension. Must be bigger than or equal to `1`. d_hid: RNN layers hidden dimension. Must be bigger than or equal to `1`. dropout: Dropout probability on all layers output (except output layer). Must range from `0.0` to `1.0`. num_linear_layers: Number of Linear layers to use. Must be bigger than or equal to `1`. num_rnn_layers: Number of RNN layers to use. Must be bigger than or equal to `1`. pad_token_id: Padding token's id. Embedding layer will initialize padding token's vector with zeros. Must be bigger than or equal to `0`, and must be smaller than `vocab_size`. vocab_size: Embedding matrix vocabulary dimension. Must be bigger than or equal to `1`. Raises: TypeError: When one of the arguments are not an instance of their type annotation respectively. ValueError: When one of the arguments do not follow their constraints. See docstring for arguments constraints. """ def __init__( self, d_emb: int, d_hid: int, dropout: float, num_linear_layers: int, num_rnn_layers: int, pad_token_id: int, vocab_size: int ): super().__init__() # Type check. if not isinstance(d_emb, int): raise TypeError('`d_emb` must be an instance of `int`.') if not isinstance(d_hid, int): raise TypeError('`d_hid` must be an instance of `int`.') if not isinstance(dropout, float): raise TypeError('`dropout` must be an instance of `float`.') if not isinstance(num_linear_layers, int): raise TypeError( '`num_linear_layers` must be an instance of `int`.' ) if not isinstance(num_rnn_layers, int): raise TypeError('`num_rnn_layers` must be an instance of `int`.') if not isinstance(pad_token_id, int): raise TypeError('`pad_token_id` must be an instance of `int`.') if not isinstance(vocab_size, int): raise TypeError('`vocab_size` must be an instance of `int`.') # Value Check. if d_emb < 1: raise ValueError('`d_emb` must be bigger than or equal to `1`.') if d_hid < 1: raise ValueError('`d_hid` must be bigger than or equal to `1`.') if not 0 <= dropout <= 1: raise ValueError('`dropout` must range from `0.0` to `1.0`.') if num_linear_layers < 1: raise ValueError( '`num_linear_layers` must be bigger than or equal to `1`.' ) if num_rnn_layers < 1: raise ValueError( '`num_rnn_layers` must be bigger than or equal to `1`.' ) if pad_token_id < 0: raise ValueError( '`pad_token_id` must be bigger than or equal to `0`.' ) if vocab_size < 1: raise ValueError( '`vocab_size` must be bigger than or equal to `1`.' ) if vocab_size <= pad_token_id: raise ValueError( '`pad_token_id` must be smaller than `vocab_size`.' ) # Token embedding layer. # Dimension: (V, E). self.emb_layer = torch.nn.Embedding( num_embeddings=vocab_size, embedding_dim=d_emb, padding_idx=pad_token_id ) self.emb_dropout = torch.nn.Dropout(dropout) # Project from `d_emb` into `d_hid`. # Dimension: (E, H). self.proj_emb_to_hid = torch.nn.Sequential( torch.nn.Linear( in_features=d_emb, out_features=d_hid ), torch.nn.ReLU(), torch.nn.Dropout(dropout) ) # Sequential RNN layer(s). # Dimension: (H, H). if num_rnn_layers == 1: self.rnn_layer = torch.nn.RNN( input_size=d_hid, hidden_size=d_hid, batch_first=True ) else: self.rnn_layer = torch.nn.RNN( input_size=d_hid, hidden_size=d_hid, num_layers=num_rnn_layers, dropout=dropout, batch_first=True ) # Sequential linear layer(s). # Dimension: (H, H). proj_hid_to_emb = [] for _ in range(num_linear_layers - 1): proj_hid_to_emb.append(torch.nn.Dropout(dropout)) proj_hid_to_emb.append( torch.nn.Linear( in_features=d_hid, out_features=d_hid ) ) proj_hid_to_emb.append(torch.nn.ReLU()) # Sequential linear layer(s)' last layer. # Dimension: (H, E). proj_hid_to_emb.append(torch.nn.Dropout(dropout)) proj_hid_to_emb.append( torch.nn.Linear( in_features=d_hid, out_features=d_emb ) ) proj_hid_to_emb.append(torch.nn.ReLU()) proj_hid_to_emb.append(torch.nn.Dropout(dropout)) self.proj_hid_to_emb = torch.nn.Sequential(*proj_hid_to_emb) def forward(self, batch_sequences: torch.Tensor) -> torch.Tensor: r"""Perform forward pass. Args: batch_sequences: Batch of sequences which have been encoded by `lmp.tokenizer.BaseTokenizer` with numeric type `torch.int64`. Returns: Logits for each token in sequences with numeric type `torch.float32`. """ # 將 batch_sequences 中的所有 token_id 經過 embedding matrix # 轉換成 embedding vectors (共有 (B, S) 個維度為 E 的向量) # embedding 前的 batch_sequences 維度: (B, S) # embedding 後的 batch_sequences 維度: (B, S, E) batch_sequences = self.emb_dropout(self.emb_layer(batch_sequences)) # 將每個 embedding vectors 經由 linear 轉換得到輸出 hidden vectors # ht 維度: (B, S, H) ht = self.proj_emb_to_hid(batch_sequences) # 將每個 embedding vectors 依序輸入 RNN 得到輸出 hidden vectors # ht 維度: (B, S, H) ht, _ = self.rnn_layer(ht) # 將每個 hidden vectors 轉換維度至 embedding dimension # ht 維度: (B, S, E) ht = self.proj_hid_to_emb(ht) # 與轉置後的 embedding matrix 進行矩陣乘法取得預測文字 # 重複使用 embedding matrix 的目的為節省參數數量 # return 維度: (B, S, V) return ht.matmul(self.emb_layer.weight.transpose(0, 1)) def predict(self, batch_sequences: torch.Tensor) -> torch.Tensor: r"""Convert model output logits into prediction. Args: batch_sequences: Batch of sequences which have been encoded by `lmp.tokenizer.BaseTokenizer` with numeric type `torch.int64`. Raises: TypeError: When `batch_sequences` is not an instance of `Tensor`. Returns: Predicition using softmax on model output logits with numeric type `torch.float32`. """ # Type check if not isinstance(batch_sequences, torch.Tensor): raise TypeError( '`batch_sequences` must be an instance of `Tensor`.' ) return torch.nn.functional.softmax(self(batch_sequences), dim=-1)
Python
UTF-8
2,338
2.578125
3
[]
no_license
import sys import os from defcon import Font, Component from fontTools.misc.py23 import * from fontTools.feaLib.parser import Parser def parse(features): subs = {} featurefile = UnicodeIO(tounicode(features)) fea = Parser(featurefile, []).parse() for statement in fea.statements: if getattr(statement, "name", None) in ("isol", "ccmp"): for substatement in statement.statements: if hasattr(substatement, "glyphs"): # Single originals = substatement.glyphs[0].glyphSet() replacements = substatement.replacements[0].glyphSet() subs.update(dict(zip(originals, replacements))) elif hasattr(substatement, "glyph"): # Multiple subs[substatement.glyph] = substatement.replacement return subs def addComponent(glyph, name, xoff=0, yoff=0): component = glyph.instantiateComponent() component.baseGlyph = name component.move((xoff, yoff)) glyph.appendComponent(component) def build(font): subs = parse(font.features.text) for name, names in subs.items(): if isinstance(names, (str, unicode)): names = [names] baseGlyph = font[names[0]] glyph = font.newGlyph(name) glyph.unicode = int(name.lstrip('uni'), 16) glyph.width = baseGlyph.width glyph.leftMargin = baseGlyph.leftMargin glyph.rightMargin = baseGlyph.rightMargin addComponent(glyph, baseGlyph.name) for partName in names[1:]: partGlyph = font[partName] partAnchors = [a.name.replace("_", "", 1) for a in partGlyph.anchors if a.name.startswith("_")] baseAnchors = [a.name for a in baseGlyph.anchors if not a.name.startswith("_")] anchorName = set(baseAnchors).intersection(partAnchors) assert len(anchorName) > 0, (names[0], partName, partAnchors, baseAnchors) anchorName = list(anchorName)[0] partAnchor = [a for a in partGlyph.anchors if a.name == "_" + anchorName][0] baseAnchor = [a for a in baseGlyph.anchors if a.name == anchorName][0] xoff = baseAnchor.x - partAnchor.x yoff = baseAnchor.y - partAnchor.y addComponent(glyph, partName, xoff, yoff)
Python
UTF-8
712
4.09375
4
[]
no_license
# 클래스 : 상속(다형성), 포함 등의 기법 구사 print('어쩌구 저쩌구 하다가.........') class TestClass: aa = 1 # 멤버 변수(클래스 내 전역변수) def __init__(self): print('생성자') def __del__(self): print('소멸자') # 메소드 def printMsg(self): name = '홍길동' print(name) print(self.aa) test = TestClass() # 생성자 호출 print(test.aa) # print(type(test)) # a = 1 # print(type(a)) print(TestClass.aa) print('메소드 호출---------') test.printMsg() # Bound method call TestClass.printMsg(test) # UnBound method call print(id(test), id(TestClass))
PHP
UTF-8
2,177
2.8125
3
[]
no_license
<?php class App_Service_User { const E_WRONG_CREDENTIALS = 'wrong-credentials'; /** * @var string */ protected $_lastError = null; /** * @return string */ public function getLastError() { return $this->_lastError; } /** * @param string $lastError */ public function setLastError($lastError) { $this->_lastError = $lastError; } /** * @param string $email * @param string $password * * @return App_Model_User|false */ public function auth($email, $password) { if (!empty($email) && !empty($password)) { $user = App_Model_User::fetchOne([ 'email' => $email, 'password' => md5($password) ]); } if (!empty($user)) { $tokens = (empty($user->tokens))?[]:$user->tokens; $tokens[] = md5(microtime()); $user->tokens = $tokens; $user->save(); return $user; } $this->setLastError(self::E_WRONG_CREDENTIALS); return false; } /** * @param App_Model_User $user */ public function logout(App_Model_User $user) { $user->tokens = []; $user->save(); } /** * @param string $token * @return App_Model_User|bool */ public function identify($token) { if (!empty($token)) { $user = App_Model_User::fetchOne([ 'tokens' => $token ]); if ($user) { return $user; } } return false; } /** * @param string $token * * @return App_Model_User|null * @throws Exception */ public function identifyMD($token) { if (empty($token)) { throw new Exception('token-invalid', 400); } $mdtoken = App_Model_MDToken::fetchOne([ 'tokens' => $token ]); if (!$mdtoken) { throw new Exception('token-invalid', 403); } return App_Model_User::fetchOne([ 'id' => $mdtoken->userId ]); } }
Java
UTF-8
2,588
2.328125
2
[]
no_license
package com.qa.ninja.tests; import java.util.Map; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import com.qa.ninja.base.BaseTest; public class ProductInfoTest extends BaseTest{ @BeforeClass public void productInfoPageSetUp() { accountsPage = loginPage.doLogin(prop.getProperty("username"), prop.getProperty("password")); } @Test(enabled = false) public void productInforPageTitleTest_iMac() { accountsPage.doSearch("iMac"); productInfoPage = accountsPage.selectProductFromSearchResults("iMac"); Assert.assertEquals(productInfoPage.getProductInfoPageTitle("iMac"),"iMac"); } @Test(enabled = false) public void verifyProductInfoTest_MacBook() { String productName = "MacBook"; Assert.assertTrue(accountsPage.doSearch(productName)); productInfoPage = accountsPage.selectProductFromSearchResults("MacBook Pro"); Assert.assertTrue(productInfoPage.totalProductImages() == 4); Map<String, String> productInforMap = productInfoPage.getProductInformation(); System.out.println(productInforMap); //{Brand=Apple, Availability=Out Of Stock, price=$2,000.00, name=MacBook Pro, Product Code=Product 18, Reward Points=800, exTaxPrice=$2,000.00} Assert.assertEquals(productInforMap.get("name"), "MacBook Pro"); Assert.assertEquals(productInforMap.get("Brand"), "Apple"); Assert.assertEquals(productInforMap.get("price"), "$2,000.00"); Assert.assertEquals(productInforMap.get("Product Code"), "Product 18"); Assert.assertEquals(productInforMap.get("Reward Points"), "800"); } @Test(priority = 1) public void verifyProductInfoTest_iMac() { String productName = "iMac"; Assert.assertTrue(accountsPage.doSearch(productName)); productInfoPage = accountsPage.selectProductFromSearchResults("iMac"); Assert.assertTrue(productInfoPage.totalProductImages() == 3); Map<String, String> productInforMap = productInfoPage.getProductInformation(); System.out.println(productInforMap); //{Brand=Apple, Availability=Out Of Stock, price=$100.00, name=iMac, Product Code=Product 14, exTaxPrice=$100.00} Assert.assertEquals(productInforMap.get("name"), "iMac"); Assert.assertEquals(productInforMap.get("Brand"), "Apple"); Assert.assertEquals(productInforMap.get("Availability"), "Out Of Stock"); Assert.assertEquals(productInforMap.get("price"), "$100.00"); Assert.assertEquals(productInforMap.get("exTaxPrice"), "$100.00"); } @Test(priority = 3) public void addToCartTest() { productInfoPage.selectQuantity("2"); productInfoPage.addToCart(); } }
Java
UTF-8
18,364
1.84375
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2015 Key Bridge LLC. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package us.gov.dod.standard.ssrf._3_1.metadata; import java.math.BigInteger; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import javax.xml.bind.annotation.*; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import us.gov.dod.standard.ssrf._3_1.adapter.types.XmlAdapterMEMO; import us.gov.dod.standard.ssrf._3_1.adapter.types.XmlAdapterS10; import us.gov.dod.standard.ssrf._3_1.adapter.types.XmlAdapterS255; import us.gov.dod.standard.ssrf._3_1.adapter.types.XmlAdapterS30; import us.gov.dod.standard.ssrf._3_1.metadata.lists.ListCCL; /** * Abstract class representing the SSRF Standard Metadata Attributes complement. * <p> * Metadata fields are defined in the SSRF XSD as the "metadata" attribute * group. These attributes apply to all data items, to all leaf elements * wihthout sub-elements (but with content), and to the Common element. All SSRF * field types extend this abstract class to support these optional metadata * fields. * <p> * Example: (Dummy classification for demonstration only). In this case, the * power value is Unclassified, but the associated remarks (index 12) is * Confidential releasable to three nations only. * <pre> * &lt;Transmitter cls="C"&gt; * &lt;Serial cls="U"&gt;USA::TX:2011-00001&lt;/Serial&gt; * &lt;ExtReferenceRef cls="U" idx="1"&gt;USA::EX:12&lt;/ExtReferenceRef&gt; * &lt;ExtReferenceRef cls="U" idx="2"&gt;FRA::EX:34&lt;/ExtReferenceRef&gt; * &lt;Remarks cls="U" idx="1"&gt;This is a JTIDS Class 2H terminal&lt;/Remarks&gt; * &lt;...Ten Other Remarks...&gt; * &lt;Remarks cls="C" release="USA GBR CAN" idx="12"&gt;All modes are limited to 200W&lt;/Remarks&gt; * &lt;Other_Transmitter_Elements/&gt; * &lt;Power cls="U" <strong>extReferences="1 2"</strong> <strong>remarksarkReferences="1 12"</strong>&gt;23&lt;/Power&gt; * &lt;/Transmitter&gt;</pre> * <p> * This abstract class is extended by classes in the SSRF * <em>metadata</em> attribute group. * <p> * Developer note: This abstract class is not part of the SSRF specification and * therefore must be annotated as XmlTransient to successfully marshal SSRF * instances. * <p> * @author Jesse Caulfield * @version SSRF 3.1.0, 09/29/2014 * @param <T> The class type implementation */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "AMetadata", propOrder = {"cls"}) @SuppressWarnings("unchecked") public abstract class AMetadata<T> { /** * cls - Classification (Required) * <p> * The classification of the current data item. This attribute is REQUIRED on * each data item, even if the classification is "U". * <p> * Format is L:CCL */ @XmlAttribute(name = "cls", required = true) protected ListCCL cls; /** * remark References - Links to Data Item Remarks (Optional) * <p> * A list of Common/Remarks idx values applicable to the current data item. * <p> * Format is List of UN6 */ @XmlList @XmlAttribute(name = "remarks") protected Set<BigInteger> remarkRef; /** * extReferences - Links to External References (Optional) * <p> * A list of Common/ExtReferenceRef idx values applicable to the current data * item. * <p> * Format is List of UN6 */ @XmlList @XmlAttribute(name = "extReferences") protected Set<BigInteger> extReferences; /** * US:legacyReleasability - Legacy Releasability (Optional) * <p> * One or more special handling instructions in sentence format, not code * format. For example, "Approved for public release; distribution is * unlimited". Multiple special handling instructions are separated by "|” * (i.e., ASCII character #124). * <p> * Format is Memo */ @XmlAttribute(name = "legacyReleasability") @XmlJavaTypeAdapter(value = XmlAdapterMEMO.class) protected String legacyReleasability; /** * US:quality - Data Quality (Optional) * <p> * One or more data quality indicator(s), separated by "|” (i.e., ASCII * character #124), for the contents of the associated Data Item For example, * "Outlier" | "Non-CodeList". * <p> * Format is S255 */ @XmlAttribute(name = "quality") @XmlJavaTypeAdapter(value = XmlAdapterS255.class) protected String quality; /** * US:recommendedValue - Recommended Value (Optional) * <p> * A value that is most probably correct. * <p> * Format is Memo */ @XmlAttribute(name = "recommendedValue") @XmlJavaTypeAdapter(value = XmlAdapterMEMO.class) protected String recommendedValue; /** * idref - Data Item ID (Optional) * <p> * A unique identifier for each Data Item in the Dataset. Within each Dataset, * the idref value must be unique for every occurrence. If a received Dataset * uses idrefs and it is expected that the Dataset will be exchanged, the * idrefs should be considered required. If the receiving system is the * permanent end of the line for the Dataset, the idrefs may be considered * optional. * <p> * Format is S10 */ @XmlAttribute(name = "idref") @XmlJavaTypeAdapter(value = XmlAdapterS10.class) protected String idref; /** * US:availability - data supporting legacy equipment certification business * practice. * <p> * Values should be selected from one of "Unknown", "N/A", "Not Available" or * "Not Applicable", when data is not available. */ @XmlAttribute(name = "availability") @XmlJavaTypeAdapter(value = XmlAdapterS30.class) protected String availability; /** * Metadata types require a zero argument constructor. */ public AMetadata() { } /** * Get the classification of the current data item. This attribute is REQUIRED * on each data item, even if the classification is "U". * <p> * @return a {@link ListCCL} instance */ public ListCCL getCls() { return cls; } /** * Set the classification of the current data item. This attribute is REQUIRED * on each data item, even if the classification is "U". * <p> * @param value a {@link ListCCL} instance */ public void setCls(ListCCL value) { this.cls = value; } /** * Get a list of Common/Remarks idx values applicable to the current data * item. * <p> * @return a non-null list of {@link BigInteger} instances */ public Set<BigInteger> getRemarkRef() { if (remarkRef == null) { remarkRef = new HashSet<>(); } return this.remarkRef; } /** * Get a list of Common/Remarks idx values applicable to the current data * item. * <p> * @return a non-null list of {@link BigInteger} instances */ public boolean isSetRemarkRef() { return ((this.remarkRef != null) && (!this.remarkRef.isEmpty())); } /** * Clear the RemarkIndex field. This sets the field to null. */ public void unsetRemarkRef() { this.remarkRef = null; } /** * Determine if the Cls is configured. * <p> * @return TRUE if the field is set, FALSE if the field is null */ public boolean isSetCls() { return (this.cls != null); } /** * Get a unique identifier for each Data Item in the Dataset. Within each * Dataset, the idref value must be unique for every occurrence. If a received * Dataset uses idrefs and it is expected that the Dataset will be exchanged, * the idrefs should be considered required. If the receiving system is the * permanent end of the line for the Dataset, the idrefs may be considered * optional. * <p> * @return a {@link String} instance */ public String getIdref() { return idref; } /** * Set a unique identifier for each Data Item in the Dataset. Within each * Dataset, the idref value must be unique for every occurrence. If a received * Dataset uses idrefs and it is expected that the Dataset will be exchanged, * the idrefs should be considered required. If the receiving system is the * permanent end of the line for the Dataset, the idrefs may be considered * optional. * <p> * @param value a {@link String} instance */ public void setIdref(String value) { this.idref = value; } /** * Determine if the Idref is configured. * <p> * @return TRUE if the field is set, FALSE if the field is null */ public boolean isSetIdref() { return (this.idref != null); } /** * Get In attribute availability (US), enter data supporting legacy equipment * certification business practice of entering "Unknown", "N/A", "Not * Available" or "Not Applicable", when data is not available. * <p> * @return a {@link String} instance */ public String getAvailability() { return availability; } /** * Set In attribute availability (US), enter data supporting legacy equipment * certification business practice of entering "Unknown", "N/A", "Not * Available" or "Not Applicable", when data is not available. * <p> * @param value a {@link String} instance */ public void setAvailability(String value) { this.availability = value; } /** * Determine if the Availability is configured. * <p> * @return TRUE if the field is set, FALSE if the field is null */ public boolean isSetAvailability() { return (this.availability != null); } /** * Get a list of Common/ExtReferenceRef idx values applicable to the current * data item. * <p> * @return a non-null list of {@link BigInteger} instances */ public Set<BigInteger> getExtReferences() { if (extReferences == null) { extReferences = new HashSet<>(); } return this.extReferences; } /** * Determine if the ExtReferences is configured. * <p> * @return TRUE if the field is set, FALSE if the field is null */ public boolean isSetExtReferences() { return ((this.extReferences != null) && (!this.extReferences.isEmpty())); } /** * Clear the ExtReferences field. This sets the field to null. */ public void unsetExtReferences() { this.extReferences = null; } /** * Get one or more special handling instructions in sentence format, not code * format. For example, "Approved for public release; distribution is * unlimited". Multiple special handling instructions are separated by "|” * (i.e., ASCII character #124). * <p> * @return a {@link String} instance */ public String getLegacyReleasability() { return legacyReleasability; } /** * Set one or more special handling instructions in sentence format, not code * format. For example, "Approved for public release; distribution is * unlimited". Multiple special handling instructions are separated by "|” * (i.e., ASCII character #124). * <p> * @param value a {@link String} instance */ public void setLegacyReleasability(String value) { this.legacyReleasability = value; } /** * Determine if the LegacyReleasability is configured. * <p> * @return TRUE if the field is set, FALSE if the field is null */ public boolean isSetLegacyReleasability() { return (this.legacyReleasability != null); } /** * Get one or more data quality indicator(s), separated by "|” (i.e., ASCII * character #124), for the contents of the associated Data Item For example, * "Outlier" | "Non-CodeList". * <p> * @return a {@link String} instance */ public String getQuality() { return quality; } /** * Set one or more data quality indicator(s), separated by "|” (i.e., ASCII * character #124), for the contents of the associated Data Item For example, * "Outlier" | "Non-CodeList". * <p> * @param value a {@link String} instance */ public void setQuality(String value) { this.quality = value; } /** * Determine if the Quality is configured. * <p> * @return TRUE if the field is set, FALSE if the field is null */ public boolean isSetQuality() { return (this.quality != null); } /** * Get a value that is most probably correct. * <p> * @return a {@link String} instance */ public String getRecommendedValue() { return recommendedValue; } /** * Set a value that is most probably correct. * <p> * @param value a {@link String} instance */ public void setRecommendedValue(String value) { this.recommendedValue = value; } /** * Determine if the RecommendedValue is configured. * <p> * @return TRUE if the field is set, FALSE if the field is null */ public boolean isSetRecommendedValue() { return (this.recommendedValue != null); } /** * Get a string representation of this Common instance configuration. * <p> * @return The current object instance configuration as a non-null String */ @Override public String toString() { return (cls != null ? " cls [" + cls + "]" : "") + (extReferences != null ? " extReferences [" + extReferences + "]" : "") + (legacyReleasability != null ? " legacyReleasability [" + legacyReleasability + "]" : "") + (quality != null ? " quality [" + quality + "]" : "") + (recommendedValue != null ? " recommendedValue [" + recommendedValue + "]" : "") + (remarkRef != null ? " rem [" + remarkRef + "]" : ""); } /** * Set the classification of the current data item. This attribute is REQUIRED * on each data item, even if the classification is "U". * <p> * @param value An instances of type {@link ListCCL} * @return The current Common object instance */ public T withCls(ListCCL value) { setCls(value); return (T) this; } /** * Set a list of Common/ExtReferenceRef idx values applicable to the current * data item. * <p> * @param values One or more instances of type {@link BigInteger} * @return The current Common object instance */ public T withExtReferences(BigInteger... values) { if (values != null) { getExtReferences().addAll(new HashSet<>(Arrays.asList(values))); } return (T) this; } /** * Set a list of Common/ExtReferenceRef idx values applicable to the current * data item. * <p> * @param values A collection of {@link BigInteger} instances * @return The current Common object instance */ public T withExtReferences(Set<BigInteger> values) { if (values != null) { getExtReferences().addAll(values); } return (T) this; } /** * Set one or more special handling instructions in sentence format, not code * format. For example, "Approved for public release; distribution is * unlimited". Multiple special handling instructions are separated by "|” * (i.e., ASCII character #124). * <p> * @param value An instances of type {@link String} * @return The current Common object instance */ public T withLegacyReleasability(String value) { setLegacyReleasability(value); return (T) this; } /** * Set one or more data quality indicator(s), separated by "|” (i.e., ASCII * character #124), for the contents of the associated Data Item For example, * "Outlier" | "Non-CodeList". * <p> * @param value An instances of type {@link String} * @return The current Common object instance */ public T withQuality(String value) { setQuality(value); return (T) this; } /** * Set a value that is most probably correct. * <p> * @param value An instances of type {@link String} * @return The current Common object instance */ public T withRecommendedValue(String value) { setRecommendedValue(value); return (T) this; } /** * Set a list of Common/Remarks idx values applicable to the current data * item. * <p> * @param values One or more instances of type {@link BigInteger} * @return The current Common object instance */ public T withRemarkRef(BigInteger... values) { if (values != null) { getRemarkRef().addAll(new HashSet<>(Arrays.asList(values))); } return (T) this; } /** * Set a list of Common/Remarks idx values applicable to the current data * item. * <p> * @param values A collection of {@link BigInteger} instances * @return The current Common object instance */ public T withRemarkRef(Set<BigInteger> values) { if (values != null) { getRemarkRef().addAll(values); } return (T) this; } /** * Set a unique identifier for each Data Item in the Dataset. Within each * Dataset, the idref value must be unique for every occurrence. If a received * Dataset uses idrefs and it is expected that the Dataset will be exchanged, * the idrefs should be considered required. If the receiving system is the * permanent end of the line for the Dataset, the idrefs may be considered * optional. * <p> * @param value An instances of type {@link String} * @return The current DCSTrunk object instance */ public T withIdref(String value) { setIdref(value); return (T) this; } /** * Set the availability (US) data supporting legacy equipment certification * business practice of entering "Unknown", "N/A", "Not Available" or "Not * Applicable", when data is not available. * <p> * @param value An instances of type {@link ListAvailability} * @return The current DCSTrunk object instance */ public T withAvailability(ListAvailability value) { setAvailability(value.name()); return (T) this; } /** * Determine if the required fields in this SSRF data type instance are set. * <p> * {@link AMetadata} requires {@link ListCCL cls} * <p> * Note that this method only checks for the presence of required information; * this method does not validate the information format. * <p> * @return TRUE if required fields are set, otherwise FALSE */ public boolean isSet() { return isSetCls(); } }
Markdown
UTF-8
3,589
3.640625
4
[ "MIT" ]
permissive
# 堆和栈 - from https://blog.csdn.net/weixin_49738644/article/details/127994071 堆和栈是程序员必须面对的两个概念,在理解这两个概念的时候,需要放到具体的场景中,在不同的场景中堆和栈表示的含义是不同的: 程序内存布局场景下,堆和栈表示的是两种内存管理方式; 数据结构场景下,堆和栈表示两种常用的数据结构。 堆和栈其实是操作系统管理进程占用的内存空间的两种管理方式。主要的区别如下: 管理方式不同:堆和栈是由操作系统自动分配和释放的,无需我们手动操作,堆的申请和释放是由程序员控制,容易出现内存泄漏。 成长方向不同。堆的增长方向是向上的,内存的地址是从低到高的;栈的增长方向是向下的,内存地址是从高到底的。 空间的大小不同。每个进程拥有的栈的大小远小于堆的大小。理论上程序员可以申请堆的大小是虚拟内存的大小,进程栈的大小对于64位的windows默认是1MB,对于64位Linux默认位10MB。 分配的方式不同。堆都是动态分配的,没有静态分配的堆。栈由两种分配方式:静态分配和动态分配,静态分配是由操作系统完成的,例如局部变量的分配。动态分配是通过alloca函数分配的,但是栈的动态分配和堆不同,栈的动态分配是操作系统释放的,不需要手动释放。 分配效率不同。栈是操作系统自动分配的,在硬件层面支持栈:分配一个专门的寄存器来存放栈的地址,并且由专门的压栈和出栈的指令,决定了高效率的堆栈,堆是由C/C++提供的库函数或运算符应用和管理。实现机制比较复杂,频繁的内存申请容易出现内存碎片,显然堆的效率远低于栈。 存储内容不同。栈的内容,函数的返回地址,相关参数,局部变量和寄存器内容等。当主函数调用另一个函数时,要保存当前函数的执行断点,需要使用堆栈来实现,首先将main函数的下一条语句的地址压入栈中,即扩展指针寄存器(EIP)的内容,然后是当前栈帧的底部地址,即的内容扩展基指针寄存器(EBP),然后是被调用函数的实参等,一般情况下是从右向左压入堆栈,然后是被调用函数的局部部分。变量,注意静态变量存储在数据段或BSS段中,不会压入堆栈。出栈的顺序正好相反。最后,栈顶指向主函数下一条语句的地址,主程序从这个地址开始执行。堆,一般来说,堆的顶部使用一个字节的空间来存储堆的大小,而堆中的具体存储内容由程序员来填充。 从上面可以看出,与栈相比,由于使用了大量的malloc()/free()或者new/delete,很容易造成大量的内存碎片,并且可能造成切换用户模式和内核模式之间,效率较低。与堆相比,栈在程序中的应用更为广泛。最常见的是函数的调用过程是通过栈来实现的,函数返回地址、EBP、实参和局部变量都存放在栈中。栈虽然有很多优点,但是因为和堆相比没有那么灵活,所以有时候会分配大量的内存空间,主要是使用堆。 无论是堆还是栈,在使用内存时都要防止非法越界。越界导致的非法内存访问可能会破坏程序的堆和栈数据,或者导致程序运行在一个不确定的状态,无法得到预期的结果。导致程序异常崩溃,这些都是我们在编程时处理内存时要注意的问题。
C#
UTF-8
916
2.78125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Tarun.Data; using Tarun.Models; using Tarun.Services; namespace Tarun.Repository { public class ContactRepository : IContact { private ApplicationDbContext db; public ContactRepository(ApplicationDbContext _db) { db = _db; } public IEnumerable<Contact> GetContacts => db.Contacts; public void Add(Contact _Contact) { db.Contacts.Add(_Contact); db.SaveChanges(); } public void Remove(int? ID) { Contact dbEntity = db.Contacts.Find(ID); db.Contacts.Remove(dbEntity); db.SaveChanges(); } public Contact GetContact(int? ID) { Contact dbEntity = db.Contacts.Find(ID); return dbEntity; } } }
Java
UTF-8
1,370
2.5
2
[]
no_license
package org.firstinspires.ftc.teamcode.proto_new; import com.qualcomm.robotcore.eventloop.opmode.LinearOpMode; import com.qualcomm.robotcore.eventloop.opmode.TeleOp; import com.qualcomm.robotcore.hardware.Servo; /** * Created by Alin on 27.01.2018,m */ @TeleOp(name = "ExtensonTest", group = "TeleOp") //@Disabled public class ExtensionTest extends LinearOpMode { //Servos private Servo servoExtension = null; //Constants private static final double EXTENSION_UP = 0.0; private static final double EXTENSION_MID = 0.5; private static final double EXTENSION_DOWN = 1.0; //@Override public void runOpMode() throws InterruptedException { // Map the servos servoExtension = hardwareMap.servo.get("extension"); // Set servo directions servoExtension.setDirection(Servo.Direction.FORWARD); waitForStart(); while (opModeIsActive()) { //Servo Extension Mechanism if (gamepad1.a) { servoExtension.setPosition(EXTENSION_DOWN); // Servo Extension DOWN position } else if (gamepad1.b) { servoExtension.setPosition(EXTENSION_MID); // Servo Extension MID position } else { servoExtension.setPosition(EXTENSION_UP); } } } }
Java
UTF-8
6,016
2.9375
3
[ "MIT" ]
permissive
package be.unamur.info.b314.compiler.main.symboltable.symbols; import be.unamur.info.b314.compiler.main.symboltable.Helpers.Errors; import be.unamur.info.b314.compiler.main.symboltable.contracts.Type; /** * @overview La classe MapSymbol représente le symbole de la Map de jeu constitué d'un tableau à deux dimensions * représentant la carte de jeu ainsi que les coordonnées initial de Cody * * @specfiled carte: char[][] * @specfiled initX: int * @specfiled initY: int * @specfiled errors: Errors */ public class MapSymbol extends Symbol { private char[][] carte; private int initX; private int initY; private Errors errors; /** * Constructeur * * @effects initialise une MapSymbol avec le name, un type et un errors * * @param name * le nom de la map (map:) * @param type * de la map * @param errors * represente les erreurs mapErrors qu'on peut avoir * */ public MapSymbol(String name, Type type, Errors errors) { super(name, type); this.errors = errors; } /** * @return un tableau à deux dimensions representant la carte */ public char[][] getCarte() { return carte; } /** * @return initX retourne la coordonée X */ public int getInitX() { return initX; } /** * @return initY retourne la coordonée Y */ public int getInitY() { return initY; } /** * @param mapX * Coordonnée X du tableau * @param mapY * Coordonnée Y du tableau * @param line * tous les elements à mettre dans le tableau * @return un boolean un true si les coordonnées de la Map sont valides */ private boolean isvalidParamMap(String mapX, String mapY, String line) { int x = 0; int y = 0; if (mapX == null || mapY == null) { errors.mapError.add("[null] Les coordonées du tableau sont invalides X=" + x + "ou Y= " + y); return false; } try { x = Integer.parseInt(mapX); y = Integer.parseInt(mapY); } catch (Exception e) { errors.mapError.add("[negatif] Les coordonées du tableau sont invalides X=" + x + "ou Y= " + y); return false; } if (x <= 0 || y <= 0) { errors.mapError.add("Les coordonées du tableau sont invalides avec X= " + x + " ou Y= " + y); return false; } else if ((x * y) != line.length()) { errors.mapError.add("Les coordonées ne correspondent pas à la taille du tableauX:" + x + " et Y:" + y); return false; } return true; } /** * Création d'un tableau à deux dimensions représentant la carte de jeu * * @effects initialise carte * @modifies carte * @param mapX * Coordonnées X du tableau * @param mapY * Coordonnées Y du tableau * @param line * tous les éléments à mettre dans le tableau * @return true si la carte a été créer et qu'elle est correct sinon retourne false */ public boolean createCarte(String mapX, String mapY, String line) { boolean isValid = isvalidParamMap(mapX, mapY, line); if (isValid) { int x = Integer.parseInt(mapX); int y = Integer.parseInt(mapY); // carte = new char[x][y]; ok carte = new char[x][y]; int z = 0; for (int i = 0; i < x; i++) { // original x for (int j = 0; j < y; j++) { // original y carte[i][j] = line.charAt(z); z++; } System.out.println(""); } isValid = isMapConfigCorrect(); } return isValid; } /** * Vérifie si la configuration de la carte est correct, si il y a 0 ou plusieurs Cody et 0 ou plusieurs trésors on * renvoi false * * @return true si la Config est correct */ private boolean isMapConfigCorrect() { boolean isCorrect = true; int nbCody = 0; int nbTresor = 0; if (carte == null) { errors.mapError.add("La configuration de la carte est incorrect : Carte non construite "); return false; } else { // 1 - Check Un seul cody et un seul tresor for (int i = carte.length - 1; i >= 0; i--) { for (int j = 0; j < carte[i].length; j++) { if (carte[i][j] == '@') { nbCody++; initX = j; initY = i; } if (carte[i][j] == 'X') { nbTresor++; } } } if (nbCody != 1) { isCorrect = false; errors.mapError.add("La configuration de la carte est incorrect : Plusieurs Cody "); } if (nbTresor != 1) { isCorrect = false; errors.mapError.add("La configuration de la carte est incorrect : Plusieurs Tresor "); } } return isCorrect; } /** * @return String contenant la carte à afficher */ private String afficheCarte() { String maps = "\n\t"; if (carte != null) { for (int i = 0; i < carte.length; i++) { for (int j = 0; j < carte[i].length; j++) { maps = maps + " " + carte[i][j]; } maps = maps + "\n\t"; } } return maps; } @Override public String toString() { return "MapSymbol" + " {" + "\n\t\tname = '" + super.getName() + '\'' + ", \n\t\tcarte = " + afficheCarte() + ", \n\t\tinitX = " + initX + ", \n\t\tinitY = " + initX + "\n\t}"; } }
Java
WINDOWS-1251
1,955
3.5
4
[]
no_license
package ua.khpi.oop.Hrianyk03; /** * \brief L3-Help * \author Heorhii Hrianyk * \version 1.0 * \date septemer 2020 * \warning main * * : * */ public class Helper { //static functions public static boolean onditionalheck(char text)/// { return ( text>64&&text<91)||( text>96&&text<=123)||text==32||text==44; } public static void PrintLine(StringBuilder text)/// { System.out.println("\n\n (): "+text); } public static void PrintNewLine(StringBuilder text)/// { System.out.println("\n\n (³): "+text); } public static StringBuilder Task6 (StringBuilder s)////// { String temp=new String(); boolean spaise=false; for (int i=0;i<s.length();i++) { if (Helper.onditionalheck(s.charAt(i))) { if (s.charAt(i)==32) spaise=true;// else { if(s.charAt(i)==44)/// { temp=temp+s.charAt(i) ; spaise=true; } else if(spaise==true)/// { temp =temp+" "+s.charAt(i); spaise=false; } else temp =temp+s.charAt(i);/// } } } s=new StringBuilder(temp); return s; } }
Java
UTF-8
589
1.570313
2
[]
no_license
package com.jx.product; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; /** * @Description: * @Author: zhangjx * @Date: 2021-01-28 **/ @EnableDiscoveryClient @SpringBootApplication @MapperScan("com.jx.product.dao") public class CloudProductServerApplication { public static void main(String[] args) { SpringApplication.run(CloudProductServerApplication.class, args); } }
Python
UTF-8
4,946
2.84375
3
[]
no_license
''' Get a face, and then draw points of interest Created on Aug 1, 2011 @author: davk ''' import sys, math, platform import cv import pygame from pygame import image, display, event, draw from pygame.locals import * CAMWIDTH = 640 CAMHEIGHT = 480 def get_pygame_image(img_cv): img_cv_rgb = cv.CreateMat(img_cv.height, img_cv.width, cv.CV_8UC3) cv.CvtColor(img_cv, img_cv_rgb, cv.CV_BGR2RGB) img_pg = image.frombuffer(img_cv_rgb.tostring(), cv.GetSize(img_cv_rgb), "RGB") return img_pg def crop(image, roi): cv.SetImageROI(image, roi) cropped = cv.CreateImage(roi[2:], image.depth, image.nChannels) cv.Copy(image, cropped) cv.ResetImageROI(image) return cropped def get_points_of_interest(cv_image, numpoints=10, roi=None): cropped = crop(cv_image, roi) g_img = get_grayscale(cropped) eig_image = cv.CreateMat(g_img.rows, g_img.cols, cv.CV_32FC1) temp_image = cv.CreateMat(g_img.rows, g_img.cols, cv.CV_32FC1) ret = cv.GoodFeaturesToTrack(g_img, eig_image, temp_image, numpoints, 0.001, # quality level -- lower is better 0.01, useHarris = True) offset = [(x + roi[0], y + roi[1]) for x, y in ret] return offset def get_grayscale(rgb_image): g_img = cv.CreateMat(rgb_image.height, rgb_image.width, cv.CV_8U) cv.CvtColor(rgb_image, g_img, cv.CV_RGB2GRAY) return g_img def draw_points_of_interest(img, dest, roi=None): points = get_points_of_interest(img, 25, roi) indexes = nearest_indexes(points, roi) ordered_points = [] for i in indexes: pt = quantize_point(points[i], roi) ordered_points.append(pt) draw.lines(dest, pygame.Color("green"), 0, # filled ordered_points, 2) def quantize_point(pt, roi, grain=5.0): """ There has got to be a more elegant way to quantize a point """ pointx = pt[0] - roi[0] pointy = pt[1] - roi[1] stepx = roi[2] / grain stepy = roi[3] / grain quantx = 0 quanty = 0 while abs(quantx - pointx) > (stepx / 2.0): quantx += stepx while abs(quanty - pointy) > (stepy / 2.0): quanty += stepy return (quantx + roi[0], quanty + roi[1]) def nearest_indexes(points, roi): indexes = [] for pt in points: indexes.append(nearest_index(pt, points, indexes, roi)) return indexes # taken from display.py, adapted from its use in a class there def nearest_index(loc, pts, exclude=[], roi=None): min = get_distance((0, 0), roi[2:]) lind = 0 for ind in range(len(pts)): distance = get_distance(loc, pts[ind]) if (distance < min) and (distance > 0) and (not ind in exclude): min = distance lind = ind return lind def get_distance(start, end): a = abs(end[0] - start[0]) b = abs(end[1] - start[1]) return math.sqrt(pow(a,2) + pow(b, 2)) # taken from display.py ^^^ def detect_faces(img, cascade): g_img = get_grayscale(img) storage = cv.CreateMemStorage(0) cv.EqualizeHist(g_img, g_img) faces = cv.HaarDetectObjects(g_img, cascade, storage) return faces def draw_faces(src_img, dest_img, cascade): faces = detect_faces(src_img, cascade) for (x,y,w,h),n in faces: draw_points_of_interest(src_img, dest_img, (x,y,w,h)) def get_frame(capture, cascade): """ MAIN DRAW LOOP FUNCTION Return the captured and manipulated pygame image to draw on the main window.""" cam_capture = cv.QueryFrame(capture) pygame_image = get_pygame_image(cam_capture) draw_faces(cam_capture, pygame_image, cascade) return pygame_image def main(): pygame.init() screen = display.set_mode((CAMWIDTH, CAMHEIGHT)) display.set_caption("monkey fever") capture = cv.CaptureFromCAM(0); if platform.system() == 'Windows': haar_cascade = cv.Load("G:\\Developer\\OpenCV2.3\\opencv\\data\\haarcascades\\haarcascade_frontalface_default.xml") else: haar_cascade = cv.Load("/opt/local/var/macports/build/_opt_local_var_macports_sources_rsync.macports.org_release_ports_graphics_opencv/opencv/work/OpenCV-2.2.0/data/haarcascades/haarcascade_frontalface_default.xml") if not capture: print "could not get cam. exiting..." sys.exit(1) while 1: for ev in event.get(): if ev.type == QUIT: return img = get_frame(capture, haar_cascade) screen.blit(img, (0, 0)) display.flip() if __name__ == "__main__": main()
C++
UTF-8
733
2.890625
3
[]
no_license
#include "CellChoose.h" CellChoose::CellChoose(QTreeWidgetItem * rowid,QWidget *parent) : QWidget(parent), rowid(rowid) { ui.setupUi(this); connect(ui.checkBox, SIGNAL(stateChanged(int)), this, SLOT(onCheckboxChanged())); } CellChoose::~CellChoose() { } void CellChoose::setChecked(bool state){ if(state == true) ui.checkBox->setCheckState(Qt::Checked); else ui.checkBox->setCheckState(Qt::Unchecked); } bool CellChoose::getChecked(){ if(ui.checkBox->checkState() == Qt::Checked) return true; else return false; } int CellChoose::onCheckboxChanged() { if (ui.checkBox->isChecked()) { emit choosingCourse(rowid); } else { emit discardingCourse(rowid); } return 0; }
Markdown
UTF-8
981
3.078125
3
[ "MIT" ]
permissive
--- layout: post title: "Remembering" date: 2013-03-22 08:12 external-url: --- I was talking with a friend yesterday about sentimentality. She told me about a Journey concert t-shirt she's kept from years ago because it reminds her of a fun night. I don't share this mindset at all and it reminded my of a [great post by Jack Shedd written almost three years ago](http://www.bigcontrarian.com/2010/07/06/pictures/) about photographs: > I don’t want to stare at some photo of me at 21 when I’m 50 and contemplate everything I was, or could have been. I don’t want to have to drown in partial truths, grasping at a falling memory to paint in details. I’d rather either remember, or not. Rather know, or forget. This is how I feel. There is no value in reminding yourself of something you would have otherwise naturally forgot if not for an artifact you've kept for that purpose alone. The truly defining moments of your life you will remember; photographs, t-shirts or not.
C#
UTF-8
2,115
2.953125
3
[ "MIT" ]
permissive
using System.Text; namespace Plugin.NFC { /// <summary> /// NFC tools /// </summary> public static class NFCUtils { /// <summary> /// Returns the content size of an array of <see cref="NFCNdefRecord"/> /// </summary> /// <param name="records">array of <see cref="NFCNdefRecord"/></param> /// <returns>Content size</returns> internal static int GetSize(NFCNdefRecord[] records) { var size = 0; if (records != null && records.Length > 0) { for (var i = 0; i < records.Length; i++) size += records[i].Payload.Length; } return size; } /// <summary> /// Returns the string formatted payload /// </summary> /// <param name="type">type of <see cref="NFCNdefTypeFormat"/></param> /// <param name="payload">record payload</param> /// <param name="uri">record uri</param> /// <returns>String formatted payload</returns> internal static string GetMessage(NFCNdefTypeFormat type, byte[] payload, string uri) { var message = string.Empty; if (!string.IsNullOrWhiteSpace(uri)) message = uri; else { if (type == NFCNdefTypeFormat.WellKnown) { // NDEF_WELLKNOWN Text record var languageCodeLength = payload[0] & 0x63; message = Encoding.UTF8.GetString(payload, languageCodeLength + 1, payload.Length - languageCodeLength - 1); } else { // Other NDEF types message = Encoding.UTF8.GetString(payload, 0, payload.Length); } } return message; } /// <summary> /// Transforms a string message into an array of bytes /// </summary> /// <param name="text">text message</param> /// <returns>Array of bytes</returns> public static byte[] EncodeToByteArray(string text) => Encoding.UTF8.GetBytes(text); /// <summary> /// Returns the string formatted payload /// </summary> /// <param name="record">Object <see cref="NFCNdefRecord"/></param> /// <returns>String formatted payload</returns> public static string GetMessage(NFCNdefRecord record) { if (record == null) return string.Empty; return GetMessage(record.TypeFormat, record.Payload, record.Uri); } } }
SQL
UTF-8
178
2.625
3
[]
no_license
SELECT timeStamp, temperature FROM ThermometerOBSERVATION o WHERE timestamp>'2017-11-18T09:06:00Z' AND timestamp<'2017-11-19T09:06:00Z' AND temperature>=47 AND temperature<=58
Java
UTF-8
953
1.742188
2
[]
no_license
package com.facebook.android.maps; import android.os.Looper; import com.facebook.android.maps.a.aa; import com.facebook.android.maps.a.ad; import com.facebook.android.maps.model.k; import com.facebook.android.maps.model.n; final class ah extends aa { ah(ai paramai, int paramInt1, int paramInt2, int paramInt3, int paramInt4, k paramk) {} public final void a() { k localk = e; if (Looper.getMainLooper() == Looper.myLooper()) { localk.c(); return; } ad.d(n); } public final void run() { k localk = f.a(a, b, c); if (localk != n.e) {} for (boolean bool = false;; bool = true) { if (localk != null) { localk.a(a, b, c); } ad.d(new ag(this, localk, bool)); return; localk = k.a(c, b); localk.a(k.a); } } } /* Location: * Qualified Name: com.facebook.android.maps.ah * Java Class Version: 6 (50.0) * JD-Core Version: 0.7.1 */
JavaScript
UTF-8
4,222
2.609375
3
[]
no_license
var makeAndModelData = null; var optionSets = null; $(document).ready(function () { $.ajax({ type: "POST", url: "/getMakeAndModel", success: function (data) { handleMakeAndModel(data); showModel($("#select-make").val()); showInf($("#select-make").val(), $("#select-model").val()); }, error: function (data) { if (data.readyState == 0) { alert("Connection failure!"); return; } }, async: true }); $("#select-make").change('shown.bs.select', function (e) { showModel($("#select-make").val()); showInf($("#select-make").val(), $("#select-model").val()); }); $("#select-model").change('shown.bs.select', function (e) { showInf($("#select-make").val(), $("#select-model").val()); }); $("#select-make").change('shown.bs.select', function (e) { showModel($("#select-make").val()); }); $("#done-button").click(function () { window.location.href = `/showSelected?data=${encodeURIComponent(JSON.stringify(convertChoice()))}`; }); function convertChoice() { var choices = []; for (var i = 0; i < optionSets.length; i++) { var choice = { "optionSetName": optionSets[i].name, "choiceName": $(`#select-optionset-${i}`).val() }; choices.push(choice); } return { "makeName": $("#select-make").val(), "modelName": $("#select-model").val(), "choices": choices }; } function showModel(makeName) { var selectOptions = ""; for (var i = 0; i < makeAndModelData.length; i++) { if (makeAndModelData[i].make == makeName) { selectOptions += `<option>${makeAndModelData[i].model}</option>`; } } $("#select-model").html(selectOptions); } function handleMakeAndModel(data) { makeAndModelData = data; var selectOptions = ""; var makes = []; for (var i = 0; i < makeAndModelData.length; i++) { var isFound = false; var makeNow = makeAndModelData[i].make; for (var j = 0; j < makes.length; j++) { if (makes[j] == makeNow) { isFound = true; break; } } if (isFound == false) { selectOptions += `<option>${makeNow}</option>`; makes.push(makeNow); } } $("#select-make").html(selectOptions); } function showInf(makeName, modelName) { $.ajax({ type: "POST", url: "/getChoicesInf", data: `make=${makeName}&model=${modelName}`, success: function (data) { engineTable(data); }, error: function (data) { if (data.readyState == 0) { alert("Connection failure!"); return; } }, async: true }); } function engineTable(data) { optionSets = data.optionSets; var html = ""; html += '<table class="table table-bordered table-hover">'; for (var i = 0; i < optionSets.length; i++) { var opSet = optionSets[i]; html += "<tr>"; { html += `<td class="text-center"><b>${opSet.name}</b></td>`; html += "<td>"; { html += `<select class="form-control" id="select-optionset-${i}">`; var options = opSet.options; for (var j = 0; j < options.length; j++) { html += `<option>${options[j]}</option>`; } html += `</select>`; } html += "</td>"; } html += "</tr>"; } html += '</table>'; $('#choice-tabel').html(html); } });
Shell
UTF-8
4,089
2.921875
3
[]
no_license
# Maintainer: Michael Lass <[email protected]> # Contributor: Szymon Jakubczak <szym-at-mit-dot-edu> # This PKGBUILD is maintained on github: # https://github.com/michaellass/AUR pkgname=openafs pkgver=1.8.10 pkgrel=1 pkgdesc="Open source implementation of the AFS distributed file system" arch=('i686' 'x86_64' 'armv7h') url="http://www.openafs.org" license=('custom:"IBM Public License Version 1.0"') depends=('krb5' 'libxcrypt') optdepends=('openafs-modules: Kernel module for OpenAFS' 'openafs-modules-dkms: Kernel module for OpenAFS, built automatically using dkms') conflicts=('openafs-features') backup=(etc/conf.d/openafs etc/openafs/ThisCell etc/openafs/cacheinfo etc/openafs/CellServDB) options=(!emptydirs) install=openafs.install source=(http://openafs.org/dl/openafs/${pkgver}/${pkgname}-${pkgver}-src.tar.bz2 http://openafs.org/dl/openafs/${pkgver}/${pkgname}-${pkgver}-doc.tar.bz2 tmpfiles.d-openafs.conf 0001-Adjust-RedHat-config-and-service-files.patch) sha256sums=('9fec11364623549e8db7374072f5c8f01b841f6bfe7e85673cbce35ff43ffb07' '9c3809e8afea017d8af2528f60cf0e0f9fa8454fac86533a3e67221f2eb5fb5d' '18d7b0173bbffbdc212f4e58c5b3ce369adf868452aabc3485f2a6a2ddb35d68' 'c67d55cf9899610d3c43389861c61ebb88d196ba8503547911dfa821b54ccd29') # If you need the kauth tools set this to 1. But be aware that these tools # are considered insecure since 2003! This also affects the PAM libs. ENABLE_KAUTH=0 prepare() { cd "${srcdir}/${pkgname}-${pkgver}" # Adjust RedHat config and service files to our needs patch -p1 < "${srcdir}"/0001-Adjust-RedHat-config-and-service-files.patch # Only needed when changes to configure were made #./regen.sh -q } build() { cd "${srcdir}/${pkgname}-${pkgver}" case "$CARCH" in "i686") sysname=i386_linux26 ;; "x86_64") sysname=amd64_linux26 ;; "armv7h") sysname=arm_linux26 ;; *) error "Unknown architecture '$CARCH'" && false esac if [ $ENABLE_KAUTH -eq 1 ]; then kauth="enable-kauth" else kauth="disable-kauth" fi ./configure --prefix=/usr \ --sysconfdir=/etc \ --sbindir=/usr/bin \ --libexecdir=/usr/lib \ --disable-fuse-client \ --disable-kernel-module \ --without-swig \ --with-afs-sysname=$sysname \ --$kauth make all_nolibafs } package() { cd "${srcdir}/${pkgname}-${pkgver}" make DESTDIR="${pkgdir}" install_nolibafs # install systemd service files install -Dm644 "${srcdir}/${pkgname}-${pkgver}/src/packaging/RedHat/openafs-client.service" "${pkgdir}/usr/lib/systemd/system/openafs-client.service" install -Dm644 "${srcdir}/${pkgname}-${pkgver}/src/packaging/RedHat/openafs-server.service" "${pkgdir}/usr/lib/systemd/system/openafs-server.service" # install default configs install -Dm644 "${srcdir}/${pkgname}-${pkgver}/src/afsd/CellServDB" "${pkgdir}/etc/${pkgname}/CellServDB" install -Dm644 "${srcdir}/${pkgname}-${pkgver}/src/packaging/RedHat/openafs.sysconfig" "${pkgdir}/etc/conf.d/openafs" install -Dm644 "${srcdir}/${pkgname}-${pkgver}/src/packaging/RedHat/openafs-ThisCell" "${pkgdir}/etc/${pkgname}/ThisCell" install -Dm644 "${srcdir}/${pkgname}-${pkgver}/src/packaging/RedHat/openafs-cacheinfo" "${pkgdir}/etc/${pkgname}/cacheinfo" # install license install -Dm644 "${srcdir}/${pkgname}-${pkgver}/LICENSE" "${pkgdir}/usr/share/licenses/${pkgname}/LICENSE" # install tmpfiles.d entry for /afs install -Dm644 "${srcdir}/tmpfiles.d-openafs.conf" "${pkgdir}/usr/lib/tmpfiles.d/openafs.conf" # if kauth was installed rename kpasswd which is already provided by krb5 and move PAM libs if [ $ENABLE_KAUTH -eq 1 ]; then install -dm755 "${pkgdir}/usr/lib/security" mv "${pkgdir}/usr/lib/pam_afs.krb.so" "${pkgdir}/usr/lib/pam_afs.so" "${pkgdir}/usr/lib/security/" mv "${pkgdir}/usr/bin/kpasswd" "${pkgdir}/usr/bin/kpasswd-openafs" mv "${pkgdir}/usr/share/man/man1/kpasswd.1" "${pkgdir}/usr/share/man/man1/kpasswd-openafs.1" fi }
C++
UTF-8
851
3.796875
4
[]
no_license
//Implementing operator(+ and <<) overloading on template class point to represent coordinates (x,y) #include<iostream> using namespace std; template<class T> class point { T x,y; //Variables public: friend ostream& operator<<(ostream& out,point<double> p); //Prototypes and friend funtion explicit operator double(); point operator+(point p) { return point(x+p.x,y+p.y); } point():x(0.0),y(0.0){} //Constructors point(T u):x(static_cast<double>(u)),y(0.0){} point(T u,T v):x(static_cast<double>(u)),y(static_cast<double>(v)){} }; ostream& operator<<(ostream& out,point<double> p) { out<<"("<<p.x<<","<<p.y<<")"; return out; } template<> point<double>::operator double() { return x*x+y*y; } int main() { point<double> p,p2(1,2.0); double d=3.5; p=d; cout<<p<<"+"<<p2<<"="; cout<<p+p2<<endl; return 0; }
Python
UTF-8
3,338
2.515625
3
[]
no_license
import pygame import cv2 import numpy as np import os import time os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (0,0) BLACK = (0,0,0) WHITE = (255, 255, 255) BLUE = ( 0, 0, 255) GREEN = ( 0, 255, 0) RED = (255, 0, 0) TEXTCOLOR = ( 0, 0, 0) (width, height) = (1920, 1000) running = True #up down left right #directions = {'l':0,'lu':0,'u':0,'ru':0,'r':0,'rd':0,'d':0,'ld':0,'c':0} directions = [0,0,0,0,0,0,0,0,0] lewayPercent = 33/2 def main(): delayTime = 0.01 nextTime = time.time() global running, screen cv2.namedWindow("preview") vc = cv2.VideoCapture(0) rval, frame = vc.read() faceCascade = cv2.CascadeClassifier("./haarcascade_frontalface_default.xml") pygame.init() screen = pygame.display.set_mode((width, height)) pygame.display.set_caption("eye tracking") screen.fill(BLACK) pygame.display.update() offset = 20 curr=0 dest = 1 step = 0 maxStep = 50 pos = [0,0] locks=np.array([[0+offset,0+offset],[width-offset,0+offset],[width-offset,height-offset],[0+offset,height-offset]],np.float32) path, dirs, files = os.walk("./Images/").__next__() counter = len(files) while running: ev = pygame.event.get() for event in ev: if event.type == pygame.QUIT: running = False if event.type == pygame.MOUSEBUTTONDOWN: running = False screen.fill(BLACK) cv2.imshow("preview", frame) rval, frame = vc.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale(gray,scaleFactor=1.1,minNeighbors=5,minSize=(30, 30)) if len(faces)==1 and time.time() >= nextTime: nextTime = time.time() + delayTime step= step+1 if step == maxStep: step = 0 curr = dest dest = (dest+1)%len(locks) for (x, y, w, h) in faces: cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2) gray = gray[y+10:y+h-10, x+10:x+w-10] gray = cv2.resize(gray,(100,100)) directions = [0,0,0,0,0,0,0,0,0] if pos[0] <width/2-width*(1/lewayPercent): #left if pos[1] <height/2-height*(1/lewayPercent): #up directions[1] = 1 elif pos[0] >height/2+height*(1/lewayPercent): #down directions[7] = 1 else: #none directions[0] = 1 elif pos[0] >width/2+width*(1/lewayPercent): #right if pos[1] <height/2-height*(1/lewayPercent): #up directions[3] = 1 elif pos[0] >height/2+height*(1/lewayPercent): #down directions[5] = 1 else: #none directions[4] = 1 else: #none if pos[1] <height/2-height*(1/lewayPercent): #up directions[2] = 1 elif pos[0] >height/2+height*(1/lewayPercent): #down directions[6] = 1 else: #none directions[8] = 1 filename = "./Images/" for index in range(len(directions)): filename = filename + str(directions[index]) + "_" filename += str(counter) cv2.imwrite(filename + ".jpg",gray) counter = counter +1 pos = (locks[dest]-locks[curr])/maxStep*step+locks[curr] pygame.draw.circle(screen, BLUE, pos, 20) pygame.display.update() vc.release() cv2.destroyAllWindows() #release is not actually stoping vc.stop() if __name__ == '__main__': main()
JavaScript
UTF-8
270
3.84375
4
[]
no_license
#!/usr/bin/node // Prints 3 lines: (like 1-multi_languages.js) // but by using an array of string and a loop. const arrayStrings = ['C is fun', 'Python is cool', 'Javascript is amazing']; for (let step = 0; step < 3; step++) { console.log(arrayStrings[step]); }
Markdown
UTF-8
3,650
2.546875
3
[]
no_license
# 数据结构例程——最小生成树的普里姆算法 - 迂者-贺利坚的专栏 - CSDN博客 2015年11月07日 10:29:37[迂者-贺利坚](https://me.csdn.net/sxhelijian)阅读数:4224 本文是[[数据结构基础系列(7):图](http://edu.csdn.net/course/detail/1595)]中第11课时[[最小生成树的普里姆算法](http://edu.csdn.net/course/detail/1595/24601)]的例程。 (程序中graph.h是图存储结构的“算法库”中的头文件,详情请[单击链接…](http://blog.csdn.net/sxhelijian/article/details/49591419)) ```python #include <stdio.h> ``` ```python #include <malloc.h> ``` ```python #include "graph.h" ``` ```python void ``` ```python Prim(MGraph g, ``` ```python int ``` ```python v) { ``` ```python int ``` ```python lowcost[MAXV]; ``` ```python //顶点i是否在U中 ``` ```python int ``` ```python min; ``` ```python int ``` ```python closest[MAXV],i,j,k; ``` ```python for ``` ```python (i= ``` ```python 0 ``` ```python ; i<g.n; i++) ``` ```python //给lowcost[]和closest[]置初值 ``` ```python { lowcost[i]=g.edges[v][i]; closest[i]=v; } ``` ```python for ``` ```python (i= ``` ```python 1 ``` ```python ; i<g.n; i++) ``` ```python //找出n-1个顶点 ``` ```python { min=INF; ``` ```python for ``` ```python (j= ``` ```python 0 ``` ```python ; j<g.n; j++) ``` ```python //在(V-U)中找出离U最近的顶点k ``` ```python if ``` ```python (lowcost[j]!= ``` ```python 0 ``` ```python && lowcost[j]<min) { min=lowcost[j]; k=j; ``` ```python //k记录最近顶点的编号 ``` ```python } ``` ```python printf ``` ```python ( ``` ```python " 边(%d,%d)权为:%d\n" ``` ```python ,closest[k],k,min); lowcost[k]= ``` ```python 0 ``` ```python ; ``` ```python //标记k已经加入U ``` ```python for ``` ```python (j= ``` ```python 0 ``` ```python ; j<g.n; j++) ``` ```python //修改数组lowcost和closest ``` ```python if ``` ```python (g.edges[k][j]!= ``` ```python 0 ``` ```python && g.edges[k][j]<lowcost[j]) { lowcost[j]=g.edges[k][j]; closest[j]=k; } } } ``` ```python int ``` ```python main() { MGraph g; ``` ```python int ``` ```python A[ ``` ```python 6 ``` ```python ][ ``` ```python 6 ``` ```python ]= { { ``` ```python 0 ``` ```python , ``` ```python 6 ``` ```python , ``` ```python 1 ``` ```python , ``` ```python 5 ``` ```python ,INF,INF}, { ``` ```python 6 ``` ```python , ``` ```python 0 ``` ```python , ``` ```python 5 ``` ```python ,INF, ``` ```python 3 ``` ```python ,INF}, { ``` ```python 1 ``` ```python , ``` ```python 5 ``` ```python , ``` ```python 0 ``` ```python , ``` ```python 5 ``` ```python , ``` ```python 6 ``` ```python , ``` ```python 4 ``` ```python }, { ``` ```python 5 ``` ```python ,INF, ``` ```python 5 ``` ```python , ``` ```python 0 ``` ```python ,INF, ``` ```python 2 ``` ```python }, {INF, ``` ```python 3 ``` ```python , ``` ```python 6 ``` ```python ,INF, ``` ```python 0 ``` ```python , ``` ```python 6 ``` ```python }, {INF,INF, ``` ```python 4 ``` ```python , ``` ```python 2 ``` ```python , ``` ```python 6 ``` ```python , ``` ```python 0 ``` ```python } }; ArrayToMat(A[ ``` ```python 0 ``` ```python ], ``` ```python 6 ``` ```python , g); ``` ```python printf ``` ```python ( ``` ```python "最小生成树构成:\n" ``` ```python ); Prim(g, ``` ```python 0 ``` ```python ); ``` ```python return ``` ```python 0 ``` ```python ; } ``` 附:测试用图结构 ![这里写图片描述](https://img-blog.csdn.net/20151107102859637)
Markdown
UTF-8
4,328
2.671875
3
[ "MIT" ]
permissive
# Nextjs-symblai-demo ## Introduction Symbl is a comprehensive suite of APIs for analyzing natural human conversations - both for your team’s internal conversations and of course the conversations you are having with your customers. Built on our Contextual Conversation Intelligence (C2I) technology, the APIs enable you to rapidly incorporate human-level understanding that goes beyond simple natural language processing of voice and text conversations. This app is using [ReactJS](https://reactjs.org/), [Typescript](https://www.typescriptlang.org/) and [NextJS](https://nextjs.org/). Let's take a look at folder structure - `pages` In Next.js, a page is a React Component exported from a `.js`, `.jsx`, `.ts`, or `.tsx` file in the pages directory. Each page is associated with a route based on its file name. You can read more about how NextJS works with pages [here](https://nextjs.org/docs/basic-features/pages) - `pages/api` here reside NextJS API routes. Here we have `call` and `subscribeToPhoneEvents` routes that will be translated to `/api/call` and `/api/subscribeToPhoneEvents` paths in the browser. In this routes we showcase how you can use Symbl Node SDK to get realtime data from API. You can read more about NodeSDK [here](https://docs.symbl.ai/#symbl-sdk-node-js) or read a how to guide [here](https://docs.symbl.ai/#get-live-transcription-phone-call-node-js-telephony) ### Index page On the first page of the app we showcase how you can call to your phone number (or meeting number) by providing the phone and multiple parameters. You will get conversational insights, transcriptions, messages, which `Symbl.ai` gets from this call. Architecture looks similar to this: ![](https://docs.symbl.ai/images/tutorial_phone_integration-f54ba415.png) ### REST API Symbl has REST API to do majority of things like getting insights, processing audio, video and text, get conversation data and much more. Rest of the pages of the app are focused on this API and showcase different use cases of Symbl from getting tasks and questions from existing conversation to uploading and processing video and audio files. You can even get transcriptions from the video and by clicking on these transcriptions, navigate to specific parts of the video. You can see this behavior on `/video` page. ## Pre-requisites To get started, you’ll need your account credentials and Node.js installed (> v8.x) on your machine.Your credentials include your appId and appSecret. You can find them on the home page of the Symbl.ai platform. ![App ID](https://docs.symbl.ai/images/credentials-faf6f434.png) ### Environment variables After you sign up on the Symbl.ai platform you copy your APP_ID and APP_SECRET, you need to set them up under `.env` file in this repo ``` APP_ID= APP_SECRET= ``` ## Deploying To run app locally , add credentials to `next-config.js` file filling in `APP_ID` and `APP_SECRET` variables. ```javascript module.exports = { env: { APP_ID: '', APP_SECRET: '', }, } ``` run `yarn` or `npm install`. To run the app, use `yarn dev` App will start running at http://localhost:3000 ![](https://symbltestdata.s3.us-east-2.amazonaws.com/NeerajTest/Nextjs-Symbl-demo+Images/Nextjsphonecall.png) ## Conclusion In this app we have represented the following capabilities of Symbl.ai - Symbl Node SDK (Check out `api/call` file) - REST Telephony API (`/phone` page) - Conversational API (`/conversations` page) - Async Audio API (`/audio` page) - Async Video API (`/video` page) - Async Text API (`/text` page) - Coming soon - Symbl react elements package available [here](https://www.npmjs.com/package/@symblai/react-elements) Relevant docs section: - [Getting started with Symbl](https://docs.symbl.ai/#getting-started) - [API overview using Postman](https://docs.symbl.ai/#postman) - [Authentication](https://docs.symbl.ai/#authentication) How Tos are available [here](https://docs.symbl.ai/#how-tos) ### Community If you liked our integration guide, please star our repo! If you have any questions, feel free to reach out to us at [email protected] or through our Community Slack at [https://developer.symbl.ai/community/slack](https://developer.symbl.ai/community/slack) This library is released under the [MIT License][license] [Signup for free](https://platform.symbl.ai)
C
UTF-8
2,100
3.34375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> #define N 30 typedef struct list { char c_node[N]; char courses[N]; struct list *sonraki; } liste; liste *ilk = NULL, *son = NULL, *yeni, *gecici; const char *c[N]; const char *d[N]; /*struct Node { char c_node[N]; char courses[N]; struct Node *next; }*/ void insert_front(int c_select) { yeni = (liste *) malloc(sizeof (liste)); strcpy(yeni->c_node,c[c_select-1]); strcpy(yeni->courses,d[c_select-1]); yeni->sonraki = NULL; if (ilk == NULL) { ilk = yeni; son = ilk; } else { son->sonraki = yeni; son = son->sonraki; } } void insert_rear(int c_select) { yeni = (liste *) malloc(sizeof (liste)); strcpy(yeni->c_node,c[c_select-1]); strcpy(yeni->courses,d[c_select-1]); yeni->sonraki = NULL; if (son == NULL) { son = yeni; ilk = son; } else { ilk->sonraki = yeni; ilk = ilk->sonraki; } } void print_cl() { gecici = ilk; while (gecici != NULL) { printf("%s\n", gecici->sonraki); gecici = gecici->sonraki; } } int main(){ c[0]="EE311"; d[0]="Digital Electronics"; c[1]="EE411"; d[1]="Fundamentals of Photonics"; c[2]="EE425"; d[2]="Microwave Engineering"; c[3]="EE443"; d[3]="Embedded Systems"; c[4]="EE455"; d[4]="Mobile Communication"; c[5]="EE461"; d[5]="Nonlinear Control Systems"; int i; int oSel, CSel; while(1){ printf("\nChoose operation:\n"); printf("1. Add a course at the front of the CourseList\n"); printf("2. Add a course at the end of the CourseList\n"); scanf("%d",&oSel); printf("Select a course:\n"); for(i=0; i<6; i++){ printf("%d. %s-%s\n", i+1, c[i], d[i]); } scanf("%d", &CSel); switch(oSel){ case 1: insert_front(CSel-1); break; case 2: insert_rear(CSel-1); break; default: printf("Please select either insert_front or insert_rear option (1 or 2)"); break; } printf("\nThe updated CourseList is:\n"); print_cl(); } return 0; }
SQL
UTF-8
2,680
3.1875
3
[]
no_license
-- MySQL dump 10.13 Distrib 8.0.21, for Win64 (x86_64) -- -- Host: localhost Database: apteka -- ------------------------------------------------------ -- Server version 8.0.21 /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!50503 SET NAMES utf8 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `storehouse` -- DROP TABLE IF EXISTS `storehouse`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!50503 SET character_set_client = utf8mb4 */; CREATE TABLE `storehouse` ( `idstorehouse` int NOT NULL AUTO_INCREMENT, `Name` varchar(45) NOT NULL, `type` enum('main','further') NOT NULL COMMENT 'Main - основной склад доставка до любой аптеки один день\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\nFuther - дополнительный склад время доставки до любой аптеки 2 дня ', `Delivery Time` tinyint unsigned NOT NULL, PRIMARY KEY (`idstorehouse`) ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='Склад'; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Dumping data for table `storehouse` -- LOCK TABLES `storehouse` WRITE; /*!40000 ALTER TABLE `storehouse` DISABLE KEYS */; INSERT INTO `storehouse` VALUES (1,'Альтаир','main',1),(2,'Альтаир','further',3),(3,'Склад Санфарм','further',4),(4,'Склад Санфарм','main',2),(5,'Склад Санфарм','further',3),(6,'Склад 1','main',2),(7,'Склад 2','main',2),(8,'Склад 3','main',4),(9,'Склад 4','main',1),(10,'Склад 5','main',3); /*!40000 ALTER TABLE `storehouse` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2020-12-23 17:45:49
Python
UTF-8
2,253
2.96875
3
[ "MIT" ]
permissive
import torch import torch.nn as nn class GlobalAverage(nn.Module): def __init__(self, rank=2, keepdims=False): """ :param rank: dimension of image :param keepdims: whether to preserve shape after averaging """ super().__init__() self.axes = list(range(2, 2 + rank)) self.keepdims = keepdims def forward(self, x): return torch.mean(x, dim=self.axes, keepdim=self.keepdims) def extra_repr(self): return f"axes={self.axes}, keepdims={self.keepdims}" class Reshape(nn.Module): def __init__(self, *shape): """ final tensor forward result (B, *shape) :param shape: shape to resize to except batch dimension """ super().__init__() self.shape = shape def forward(self, x): return x.reshape([x.shape[0], *self.shape]) def extra_repr(self): return f"shape={self.shape}" class Identity(nn.Module): def forward(self, x): return x class ImagenetNorm(nn.Module): def __init__(self, from_raw=True): """ :param from_raw: whether the input image lies in the range of [0, 255] """ super().__init__() self.from_raw = from_raw self.mean = nn.Parameter(torch.tensor([0.485, 0.456, 0.406]), requires_grad=False) self.std = nn.Parameter(torch.tensor([0.229, 0.224, 0.225]), requires_grad=False) def forward(self, x: torch.Tensor): if x.dtype != torch.float: x = x.float() x = x / 255 if self.from_raw else x mean = self.mean.view(1, 3, 1, 1) std = self.std.view(1, 3, 1, 1) return (x - mean) / std def extra_repr(self): return f"from_raw={self.from_raw}" class Normalization(nn.Module): def __init__(self, from_raw=True): """ :param from_raw: whether the input image lies in the range of [0, 255] """ super().__init__() self.from_raw = from_raw def forward(self, x): if x.dtype != torch.float: x = x.float() if self.from_raw: return x / 127.5 - 1 else: return x * 2 - 1 def extra_repr(self): return f"from_raw={self.from_raw}"
Python
UTF-8
21,715
2.734375
3
[]
no_license
import sys import tkinter as tk import tkinter.ttk as ttk class State: def __init__(self, sname, stype, sparamlist): self.stname = sname self.sttype = stype self.stparamlist = sparamlist def __str__(self): return "<State> "+self.stname class Screen: def __init__(self, name, data=""): self.scname = name self.scdata = data def appendData(self, data): self.scdata += data def __str__(self): return "<Screen> "+self.scname class SType: def __init__(self, name, paramcount, paramlist): self.name = name self.paramcount = paramcount self.paramlist = paramlist def __str__(self): return "<SType> " + self.name class StateTable: def __init__(self): self.ptype = ('number', 'screen', 'state') self.stype = dict() #Add only <State> to the list self.stateList = dict() #Add only <Screen> to the list self.screenList = list() def addScreenToList(self, scr): self.screenList.append(scr) def addTypeToList(self, styp): self.stype[styp.name] = styp def addStateToList(self, state): self.stateList[state.stname] = state class ScreenGUI: FWIDTH = 20 FHEIGHT = 20 LabelArray = [[None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None], \ [None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None], \ [None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None], \ [None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None], \ [None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None], \ [None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None], \ [None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None], \ [None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None], \ [None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None], \ [None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None], \ [None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None], \ [None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None], \ [None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None], \ [None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None], \ [None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None], \ [None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None,None], \ ] def __init__(self, screen): self.name = screen.scname self.data = screen.scdata self.clearScreen() self.cursor = [ 0, 0] def __init__(self, name, data): self.name = name self.data = data self.clearScreen() self.cursor = [0,0] def clearScreen(self): self.screenbuf = [['','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','',''], \ ['','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','',''], \ ['','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','',''], \ ['','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','',''], \ ['','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','',''], \ ['','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','',''], \ ['','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','',''], \ ['','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','',''], \ ['','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','',''], \ ['','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','',''], \ ['','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','',''], \ ['','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','',''], \ ['','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','',''], \ ['','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','',''], \ ['','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','',''], \ ['','','','','','','','','','','','','','','','','','','','','','','','','','','','','','','',''], \ ] def addText(self, text, row, col): for s in text: if row < 16 and col < 32 : self.screenbuf[row][col] = s col+=1 """def addText(self, text): self.addText(self.cursor[0], self.cursor[1], text)""" def setCursor(self, row, col): self.cursor = [row, col] def DisplayText(self,parent, buf): for i in range(16): for j in range(32): temp = tk.Label(parent, fg='white', width=1, text=buf[i][j],bg='black') temp.place(x = (j * self.FWIDTH), y = (i * self.FHEIGHT), width = self.FWIDTH, height = self.FHEIGHT) #temp.pack() self.LabelArray[i][j] = temp def showScreen(self): view = tk.Tk() view.title(self.name) self.DisplayText(view, self.screenbuf) view.geometry(str(self.FWIDTH*32)+"x"+str(self.FHEIGHT*16)) view.mainloop() def processData(self): print('Generating Screen:', self.name) #print('Screen Data:', self.data) d = self.data head = 0 length = len(d) command = "" while head < length: if d[head] == "@": head += 1 command = d[head:head+2] head += 2 else: #head += 1 if head < length: s = d[head] text = '' while s != '@': text += s head += 1 if head >= length: break else: s = d[head] self.addText(text, self.cursor[0], self.cursor[1]) continue #print("Command :", command) if command == "FF": self.clearScreen() elif command == "SI": #print("unparsed:", d[head:]) #print("Row:", d[head:head+2]) row = int(d[head:head+2]) head += 2 col = int(d[head:head+2]) head += 2 self.setCursor(row, col) elif command == "CS": head += 1 if head < length: s = d[head] text = '' while s != '@': text += s head += 1 if head >= length: break else: s = d[head] self.addText(text, self.cursor[0], self.cursor[1]) else: s = d[head] while s != '@': head += 1 if head >= length: break else: s = d[head] #head += 1 """if head < length: s = d[head] text = '' while s != '@': text += s head += 1 if head >= length: break else: s = d[head] self.addText(text, self.cursor[0], self.cursor[1])""" self.showScreen() filestack = [] curfd = None curSegment = None statetable = None terminatorList = {'config' : 'end', 'timer_def' : 'end', \ 'misc_config_data' : 'end', 'enhanced_params_def' : 'end', \ 'screen_def' : 'end_screen_def', 'state_def' : 'end', \ 'state_table' : 'end', 'host_state_def' : 'end', \ 'oar_def' : 'end' } segmentList = ('config', 'timer_def', 'misc_config_data', 'enhanced_params_def', 'screen_def', 'state_def', 'state_table', 'host_state_def', 'oar_def') curScreen = None stateCount = 0 stypeCount = 0 screenCount = 0 printed = None RED = "\033[0;31m" BLUE = "\033[0;34m" CYAN = "\033[0;36m" GREEN = "\033[0;32m" RESET = "\033[0;0m" def filestackTest(): global filestack for a in filestack: print(str(a)) def openFile(filename): fd = open(filename, 'r') #filestack.append(fd) return fd def popFile(): global filestack fd = filestack[-1] if fd != None: close(fd) """ def getLine(): global filestack, curfd line = curfd.readline() if filestack[-1] != None: fd = filestack[-1] else: return -1 line = getLine """ def setSegment(line): global curSegment, segmentList for seg in segmentList: if seg == line.lower(): curSegment = seg def isTerminator(line): global terminatorList, curSegment if terminatorList[curSegment] == line.lower(): return True return False def newScreen(name): global curScreen scr = Screen(name) curScreen = scr #print('Added Screen [' + name + ']') def addScreen(): global curScreen, statetable, screenCount if curScreen is not None: statetable.addScreenToList(curScreen) screenCount += 1 curScreen = None else: print("Error: Current screen is none. Cannot Add.") def addScreenData(data): global curScreen if curScreen is not None: curScreen.appendData(data) else: print("Error: Current screen is none. Cannot Add data.") def processScreen(line): global curScreen temp = line.lower() if temp.find('screen:') == 0: temp = temp.replace('screen:','').strip() newScreen(temp) elif temp == 'end': addScreen() else: addScreenData(line) def processType(line): #line = processLine(line) global statetable, stypeCount #print('processing: [' + line + ']') line = line.split() styp = SType(line[0], line[1], line[2:]) statetable.addTypeToList(styp) stypeCount += 1 #print("Added StateType[", styp.name, "].") def processState(line): global statetable, stateCount line = line.split() state = State(line[0], line[1], line[2:]) statetable.addStateToList(state) #print("Added State[", state.stname, "].") stateCount += 1 def process(line): global curSegment if curSegment == None: setSegment(line) elif isTerminator(line): curSegment = None return else: if curSegment == 'screen_def': processScreen(line) elif curSegment == 'state_def': processType(line) elif curSegment == 'state_table': processState(line) """ elif curSegment == 'host_state_def': processScreen(line) elif curSegment == 'config': processScreen(line) elif curSegment == 'oar_def': processScreen(line) elif curSegment == 'timer_def': processScreen(line) elif curSegment == 'enhanced_params_def': processScreen(line)""" def __main__(): global filestack, curfd, curSegment, statetable f = "state.tbl" curfd = openFile(f) statetable = StateTable() #statetable. #while line = getLine() != -1: for line in curfd: line = line.strip() if line != '': if line[0] != '#': if line[-1] == '\\': while line[-1] == '\\': line = line.replace('\\', '') line += curfd.readline().strip() #process line here #print(line) process(line) curfd.close() print("Parsing sucessful!") #print(statetable.stateList.values()) def writeToCSV(name): global statetable fd = open(name, "w") fd.write("State Type List\n") for stype in statetable.stype.values(): fd.write(stype.name + ',' + stype.paramcount ) for p in stype.paramlist: fd.write(',' + p) fd.write('\n\n\n') fd.write("Screens list\n\n") for scr in statetable.screenList: fd.write(scr.scname + ',' + scr.scdata + '\n\n\n') fd.write("States List\n\n") for state in statetable.stateList.values(): fd.write(state.stname + ',' + state.sttype) for p in state.stparamlist: fd.write(',' + p) fd.write('\n') fd.close() __main__() #filestackTest() #writeToCSV("statetable.csv") print("Screen Count :", screenCount) print("SType Count :", stypeCount) print("States Count :", stateCount) def getRootState(): global statetable for state in statetable.stateList: if statetable.stateList[state].sttype == "A": return statetable.stateList[state] return None def createViewer(name, data): s = ScreenGUI(name, data) #s = ScreenGUI("scr","@SO670@ES[060z@SO671@ES[060z@SO672@ES[060z@SO679@ES[020z@SO674@ES[060z@SO675@ES[060z@SO679@ES[020z@SO676@ES[060z@SO677@ES[060z@SO678@ES[060z@SO679@ES[020z") s.processData() class Begueradj(tk.Frame): ''' classdocs ''' global statetable def __init__(self, parent): ''' Constructor ''' tk.Frame.__init__(self, parent) self.parent = parent self.initialize_user_interface() def initialize_user_interface(self): """Draw a user interface allowing the user to type items and insert them into the treeview """ self.parent.title("Canvas Test") self.parent.grid_rowconfigure(1,weight=1) self.parent.grid_columnconfigure(1,weight=1) self.parent.config(background="lavender") # Define the different GUI widgets #self.dose_label = tk.Label(self.parent, text = "Dose:") #self.dose_entry = tk.Entry(self.parent) #self.dose_label.grid(row = 0, column = 0, sticky = tk.W) #self.dose_entry.grid(row = 0, column = 1) #self.modified_label = tk.Label(self.parent, text = "Date Modified:") #self.modified_entry = tk.Entry(self.parent) #self.modified_label.grid(row = 1, column = 0, sticky = tk.W) #self.modified_entry.grid(row = 1, column = 1) #self.submit_button = tk.Button(self.parent, text = "Insert", command = self.insert_data) #self.submit_button.grid(row = 2, column = 1, sticky = tk.W) #self.exit_button = tk.Button(self.parent, text = "Exit", command = self.parent.quit) #self.exit_button.grid(row = 0, column = 3) # Set the treeview self.tree = ttk.Treeview( self.parent) self.tree.pack(expand=tk.YES, fill=tk.BOTH) self.tree.heading('#0', text='State Table Tree View') #self.tree.heading('#1', text='Dose') #self.tree.heading('#2', text='Modification Date') #self.tree.column('#1', stretch=tk.YES) #self.tree.column('#2', stretch=tk.YES) self.tree.column('#0', stretch=tk.YES, minwidth=500, width=700) #self.tree.grid(row=1, sticky='nsew') self.treeview = self.tree self.tree.tag_configure('number', foreground='brown') self.tree.tag_configure('screen', foreground='green') self.tree.tag_configure('state', foreground='blue') self.tree.tag_configure('undefined', foreground='red') self.tree.bind("<Double-1>", self.OnDoubleClick) # Initialize the counter self.i = 0 def insert_data(self, parent, name, level, tag): """ Insertion method. """ #print("inserting " + name + " to " + str(parent)) if parent == 'root': id1 = self.treeview.insert(parent='', index=0, text=str(name), tags=('state')) #print(id1) else: id1 = self.treeview.insert(parent=parent, index='end',text=str(name), tags=(tag)) # Increment counter self.i = self.i + 1 return id1 """def doubleClick_Screen(self, event): self.tree""" def OnDoubleClick(self, event): item = self.tree.selection()[0] if self.tree.item(item, "tags")[0] == "screen": scr_name = self.tree.item(item,"text") for scr in statetable.screenList: if scr.scname == scr_name: createViewer(scr_name, scr.scdata) #print("you clicked on", self.tree.item(item,"tags")) def printLevel(level): temp = '' for i in range(level - 1): temp += '| ' if level != 0: temp += '|___' return temp def printBlue(app, parent, text, level): global BLUE,RESET #print(printLevel(level) + BLUE + text + RESET) #print(printLevel(level) + text) return app.insert_data(parent, text,level, 'state') def printRed(app, parent, text, level): global RED,RESET #print(printLevel(level) + RED + text + RESET) #print(printLevel(level) + text) return app.insert_data(parent, text,level, 'undefined') def printYellow(app, parent, text,level): global CYAN,RESET #print(printLevel(level) + CYAN + text + RESET) #print(printLevel(level) + text) return app.insert_data(parent, text,level, 'number') def printGreen(app, parent, text, level): global GREEN, RESET #print(printLevel(level) + GREEN + text + RESET) #print(printLevel(level) + text) return app.insert_data(parent, text, level, 'screen') def printRoot(app, text, level): global GREEN, RESET #print(printLevel(level) + GREEN + text + RESET) #print(printLevel(level) + text) return app.insert_data('root', text, level, 'state') def markPrinted(name): global printed printed[name] = 1 def printState(app, parent, state, level): global statetable, printed temp = None types = None params = None try: types = statetable.stype[state.sttype].paramlist i = 0 for p in state.stparamlist: printed[state.stname] = True if types[i] == 'state': try: temp = printed[p] #for "state_name (state type)" tp = p + " (" + statetable.stateList[p].sttype + ")" pid = printBlue(app, parent, tp, level + 1) if str(state).lower != "null": if not printed[p]: printState(app, pid, statetable.stateList[p], level + 1) except KeyError: #printLevel(level + 1) printRed(app, parent, p, level + 1) #printBlue(p) elif types[i] == 'number': #printLevel(level + 1) printYellow(app, parent, p, level + 1) elif types[i] == 'screen': #printLevel(level + 1) printGreen(app, parent, p, level + 1) i += 1 except: printRed(app, parent, 'Exception', 0) raise return def printStateTable(app): global statetable, printed level=0 printed = dict() for s in statetable.stateList: printed[s] = False root = getRootState() parent = printRoot(app, root.stname + " (" + root.sttype + ")", level) #parent = printRoot(app, root.stname, level) if root is not None: printState(app, parent, root, level) #printLevel(level) print("Generating CSV...") writeToCSV("statetable.csv") print("Invoking GUI...") root = tk.Tk() d = Begueradj(root) #d=0 printStateTable(d) root.mainloop()
C++
UTF-8
17,852
2.546875
3
[ "Apache-2.0" ]
permissive
#ifndef CONCEPTS_H #define CONCEPTS_H #include <vlog/support.h> #include <vlog/consts.h> #include <vlog/graph.h> #include <kognac/logs.h> #include <string> #include <inttypes.h> #include <stdlib.h> #include <vector> #include <set> #include <map> #include <unordered_map> /*** PREDICATES ***/ #define EDB 0 #define IDB 1 #define MAX_NPREDS (2048*1024) typedef uint32_t PredId_t; typedef uint32_t Var_t; class EDBLayer; inline std::string fields2str(const std::vector<uint8_t> &fields) { std::ostringstream os; os << "[" << fields.size() << "]{"; for (auto f : fields) { os << (int)f << ","; } os << "}"; return os.str(); } /*** TERMS ***/ class VTerm { private: Var_t id; //ID != 0 => variable. ID==0 => const value uint64_t value; public: VTerm() : id(0), value(0) {} VTerm(const Var_t id, const uint64_t value) : id(id), value(value) {} Var_t getId() const { return id; } uint64_t getValue() const { return value; } void setId(const Var_t i) { id = i; } void setValue(const uint64_t v) { value = v; } bool isVariable() const { return id > 0; } bool operator==(const VTerm& rhs) const { return id == rhs.getId() && value == rhs.getValue(); } bool operator!=(const VTerm& rhs) const { return id != rhs.getId() || value != rhs.getValue(); } }; /*** TUPLES ***/ class VTuple { private: const uint8_t sizetuple; VTerm *terms; public: VTuple(const uint8_t sizetuple) : sizetuple(sizetuple) { terms = new VTerm[sizetuple]; } VTuple(const VTuple &v) : sizetuple(v.sizetuple) { terms = new VTerm[sizetuple]; for (int i = 0; i < sizetuple; i++) { terms[i] = v.terms[i]; } } size_t getSize() const { return sizetuple; } VTerm get(const int pos) const { return terms[pos]; } void set(const VTerm term, const int pos) { terms[pos] = term; } void replaceAll(const VTerm termA, const VTerm termB) { for (int i = 0; i < sizetuple; i++) { if (terms[i] == termA) { terms[i] = termB; } } } std::vector<std::pair<uint8_t, uint8_t>> getRepeatedVars() const { std::vector<std::pair<uint8_t, uint8_t>> output; for (int i = 0; i < sizetuple; ++i) { VTerm t1 = get(i); if (t1.isVariable()) { for (int j = i + 1; j < sizetuple; ++j) { VTerm t2 = get(j); if (t2.getId() == t1.getId()) { output.push_back(std::make_pair(i, j)); } } } } return output; } bool operator==(const VTuple &other) const { if (sizetuple == other.sizetuple) { if (terms == other.terms) { return true; } for (int i = 0; i < sizetuple; i++) { if (terms[i].getId() != other.terms[i].getId()) { return false; } if (terms[i].getId() == 0) { if (terms[i].getValue() != other.terms[i].getValue()) { return false; } } } return true; } return false; } /* VTuple & operator=(const VTuple &v) { if (this == &v) { return *this; } if (terms != NULL) { delete[] terms; } sizetuple = v.sizetuple; terms = new VTerm[sizetuple]; for (int i = 0; i < sizetuple; i++) { terms[i] = v.terms[i]; } return *this; } */ //L. Can I create an iterator on it? begin, end etc? ~VTuple() { delete[] terms; } }; struct hash_VTuple { size_t operator()(const VTuple &v) const { size_t hash = 0; int sz = v.getSize(); for (int i = 0; i < sz; i++) { VTerm term = v.get(i); if (term.isVariable()) { hash = (hash + (324723947 + term.getId())) ^93485734985; } else { hash = (hash + (324723947 + term.getValue())) ^93485734985; } } return hash; } }; class Predicate { private: const PredId_t id; const uint8_t type; const uint8_t adornment; const uint8_t card; public: Predicate(const Predicate &pred) : id(pred.id), type(pred.type), adornment(pred.adornment), card(pred.card) { } Predicate(const Predicate p, const uint8_t adornment) : id(p.id), type(p.type), adornment(adornment), card(p.card) { } Predicate(const PredId_t id, const uint8_t adornment, const uint8_t type, const uint8_t card) : id(id), type(type), adornment(adornment), card(card) { } PredId_t getId() const { return id; } uint8_t getType() const { return type & 1; } bool isMagic() const { return (type >> 1) != 0; } uint8_t getAdornment() const { return adornment; } uint8_t getCardinality() const { return card; } /*static bool isEDB(std::string pred) { return pred.at(pred.size() - 1) == 'E'; }*/ static uint8_t calculateAdornment(VTuple &t) { uint8_t adornment = 0; for (size_t i = 0; i < t.getSize(); ++i) { if (!t.get(i).isVariable()) { adornment += 1 << i; } } return adornment; } static uint8_t changeVarToConstInAdornment(const uint8_t adornment, const uint8_t pos) { uint8_t shiftedValue = (uint8_t) (1 << pos); return adornment | shiftedValue; } static uint8_t getNFields(uint8_t adornment) { uint8_t n = 0; for (int i = 0; i < 8; ++i) { if (adornment & 1) n++; adornment >>= 1; } return n; } }; /*** SUBSTITUTIONS ***/ struct Substitution { Var_t origin; VTerm destination; Substitution() {} Substitution(Var_t origin, VTerm destination) : origin(origin), destination(destination) {} }; VLIBEXP std::vector<Substitution> concat(std::vector<Substitution>&, std::vector<Substitution>&); VLIBEXP std::vector<Substitution> inverse_concat(std::vector<Substitution>&, std::vector<Substitution>&); VLIBEXP std::string extractFileName(std::string& filePath); /*** LITERALS ***/ class Program; class Literal { private: const Predicate pred; const VTuple tuple; const bool negated; public: Literal(const Predicate pred, const VTuple tuple) : pred(pred), tuple(tuple), negated(false) {} Literal(const Predicate pred, const VTuple tuple, bool negated) : pred(pred), tuple(tuple), negated(negated) {} Predicate getPredicate() const { return pred; } bool isMagic() const { return pred.isMagic(); } VTerm getTermAtPos(const int pos) const { return tuple.get(pos); } size_t getTupleSize() const { return tuple.getSize(); } VTuple getTuple() const { return tuple; } size_t getNBoundVariables() const { return pred.getNFields(pred.getAdornment()); } bool isNegated() const { return negated; } //L. do we need this function? //static int mgu(Substitution *substitutions, const Literal &l, const Literal &m); static int subsumes(std::vector<Substitution> &substitutions, const Literal &from, const Literal &to); static int getSubstitutionsA2B( std::vector<Substitution> &substitutions, const Literal &a, const Literal &b); Literal substitutes(std::vector<Substitution> &substitions, int *nsubs = NULL) const; bool sameVarSequenceAs(const Literal &l) const; VLIBEXP uint8_t getNVars() const; VLIBEXP uint8_t getNConstants() const; uint8_t getNUniqueVars() const; bool hasRepeatedVars() const; // Returns for each variable the position in the tuple. std::vector<uint8_t> getPosVars() const; // Returns for each position in the tuple the variable number. If the position in the tuple // contains a constant, it gives -1. std::vector<int> getVarnumInLiteral() const; std::vector<uint8_t> getVarCount() const; std::vector<std::pair<uint8_t, uint8_t>> getRepeatedVars() const; std::vector<Var_t> getSharedVars(const std::vector<Var_t> &vars) const; std::vector<Var_t> getNewVars(std::vector<Var_t> &vars) const; std::vector<Var_t> getAllVars() const; bool containsVariable(Var_t variableId) const; std::string tostring(const Program *program, const EDBLayer *db) const; std::string toprettystring(const Program *program, const EDBLayer *db, bool replaceConstants = false) const; std::string tostring() const; bool operator ==(const Literal &other) const; }; class Rule { private: const uint32_t ruleId; const std::vector<Literal> heads; const std::vector<Literal> body; const bool _isRecursive; const bool existential; const bool egd; static bool checkRecursion(const std::vector<Literal> &head, const std::vector<Literal> &body); public: bool doesVarAppearsInFollowingPatterns(int startingPattern, Var_t value) const; Rule(uint32_t ruleId, const std::vector<Literal> heads, std::vector<Literal> body, bool egd) : ruleId(ruleId), heads(heads), body(body), _isRecursive(checkRecursion(heads, body)), existential(!getExistentialVariables().empty()), egd(egd) { checkRule(); } Rule(uint32_t ruleId, Rule &r) : ruleId(ruleId), heads(r.heads), body(r.body), _isRecursive(r._isRecursive), existential(r.existential), egd(r.egd) { } Rule createAdornment(uint8_t headAdornment) const; bool isRecursive() const { return this->_isRecursive; } uint32_t getId() const { return ruleId; } bool isEGD() const { return egd; } const std::vector<Literal> &getHeads() const { return heads; } Literal getFirstHead() const { // if (heads.size() > 1) // LOG(WARNL) << "This method should be called only if we handle multiple heads properly..."; return heads[0]; } Literal getHead(unsigned pos) const { return heads[pos]; } bool isExistential() const; std::vector<Var_t> getVarsInHead(PredId_t ignore = -1) const; std::vector<Var_t> getVarsInBody() const; std::vector<Var_t> getExistentialVariables() const; std::vector<Var_t> getFrontierVariables(PredId_t ignore = -1) const; std::map<Var_t, std::vector<Var_t>> calculateDependencies() const; const std::vector<Literal> &getBody() const { return body; } unsigned getNIDBPredicates() const { unsigned i = 0; for (std::vector<Literal>::const_iterator itr = body.begin(); itr != body.end(); ++itr) { if (itr->getPredicate().getType() == IDB) { i++; } } return i; } unsigned getNIDBNotMagicPredicates() const { unsigned i = 0; for (std::vector<Literal>::const_iterator itr = body.begin(); itr != body.end(); ++itr) { if (itr->getPredicate().getType() == IDB && !itr->getPredicate().isMagic()) { i++; } } return i; } unsigned getNEDBPredicates() const { unsigned i = 0; for (std::vector<Literal>::const_iterator itr = body.begin(); itr != body.end(); ++itr) { if (itr->getPredicate().getType() == EDB) { i++; } } return i; } unsigned numberOfNegatedLiteralsInBody() { unsigned result = 0; for (std::vector<Literal>::const_iterator itr = getBody().begin(); itr != getBody().end(); ++itr) { if (itr->isNegated()){ ++result; } } return result; } void checkRule() const; Rule normalizeVars() const; std::string tostring() const; std::string tostring(Program *program, EDBLayer *db) const; std::string toprettystring(Program *program, EDBLayer *db, bool replaceConstants = false) const; ~Rule() { } }; class Program { private: EDBLayer *kb; std::vector<std::vector<uint32_t>> rules; // [head_predicate_id (idx) : [rule_ids]] std::vector<Rule> allrules; int rewriteCounter; Dictionary dictPredicates; std::unordered_map<PredId_t, uint8_t> cardPredicates; void rewriteRule(std::vector<Literal> &heads, std::vector<Literal> &body); void addRule(Rule &rule); public: VLIBEXP Program(EDBLayer *kb); VLIBEXP Program(Program *p, EDBLayer *kb); EDBLayer *getKB() const { return kb; } VLIBEXP void setKB(EDBLayer *e) { kb = e; } uint64_t getMaxPredicateId() { return dictPredicates.getCounter(); } static std::string prettifyName(std::string name); std::string parseRule(std::string rule, bool rewriteMultihead); VLIBEXP std::vector<PredId_t> getAllPredicateIDs() const; VLIBEXP Literal parseLiteral(std::string literal, Dictionary &dictVariables); VLIBEXP std::string readFromFile(std::string pathFile, bool rewriteMultihead = false); VLIBEXP std::string readFromString(std::string rules, bool rewriteMultihead = false); // Adds predicate if it doesn't exist yet PredId_t getPredicateID(const std::string &p, const uint8_t card); VLIBEXP std::string getPredicateName(const PredId_t id) const; // Adds predicate if it doesn't exist yet VLIBEXP Predicate getPredicate(const std::string &p); // Adds predicate if it doesn't exist yet VLIBEXP Predicate getPredicate(const std::string &p, uint8_t adornment); VLIBEXP Predicate getPredicate(const PredId_t id) const; VLIBEXP int64_t getOrAddPredicate(const std::string &p, uint8_t cardinality); VLIBEXP bool doesPredicateExist(const PredId_t id) const; std::vector<Rule> getAllRulesByPredicate(PredId_t predid) const; const std::vector<uint32_t> &getRulesIDsByPredicate(PredId_t predid) const; size_t getNRulesByPredicate(PredId_t predid) const; const Rule &getRule(uint32_t ruleid) const; VLIBEXP void sortRulesByIDBPredicates(); VLIBEXP std::vector<Rule> getAllRules() const; VLIBEXP int getNRules() const; Program clone() const; std::shared_ptr<Program> cloneNew() const; void cleanAllRules(); VLIBEXP void addRule(std::vector<Literal> heads, std::vector<Literal> body) { addRule(heads, body, false, false); } VLIBEXP void addRule(std::vector<Literal> heads, std::vector<Literal> body, bool rewriteMultihead, bool isEGD); void addAllRules(std::vector<Rule> &rules); VLIBEXP bool isPredicateIDB(const PredId_t id) const; std::string getAllPredicates() const; std::vector<std::string> getAllPredicateStrings() const; int getNEDBPredicates() const; int getNIDBPredicates() const; std::string tostring() const; VLIBEXP bool areExistentialRules() const; int getNPredicates() { return rules.size(); } static std::string rewriteRDFOWLConstants(std::string input); static std::string compressRDFOWLConstants(std::string input); // Should be const VLIBEXP std::vector<PredId_t> getAllEDBPredicateIds(); uint8_t getPredicateCard(PredId_t pred) { return cardPredicates[pred]; } VLIBEXP std::vector<PredId_t> getAllIDBPredicateIds(); // // Returns true if stratification succeeded, and then stores the // stratification in the parameter. // The result vector is indexed by predicate id, and then gives the // stratification class. // The number of stratification classes is also returned. bool stratify(std::vector<int> &stratification, int &nStatificationClasses); VLIBEXP void axiomatizeEquality(); VLIBEXP void singulariseEquality(); ~Program() { } }; #endif
Markdown
UTF-8
5,295
3.40625
3
[ "Apache-2.0" ]
permissive
# GPIO Device Service ## Overview GPIO Micro Service - device service for connecting GPIO devices to EdgeX. - Function: - This device service use sysfs to control GPIO devices. For a just connected GPIO device, export the needed pin number, set correct GPIO direction, and then start to read or write data from GPIO device. - Physical interface: system gpio (/sys/class/gpio) - Driver protocol: IO ## Usage - This Device Service have to run with other EdgeX Core Services, such as Core Metadata, Core Data, and Core Command. - After the service started, we can use "exportgpio" command to export your GPIO device, then set direction with "gpiodirection" command, and use "gpiovalue" to read or write data. ## Guidance Here we give two step by step guidance examples of using this device service. In these examples, we use RESTful API to interact with EdgeX. Before we actually operate GPIO devices, we need to find out RESTful urls of this running device service. By using `curl http://localhost:48082/api/v1/device/name/gpio` We can find out the each command url you needed in next steps from `crul` response. Other than simply use `curl`, we can also use tool like `Postman`, which will give better experience on sending RESTful requests. Here, we just provide one possible way to interact with this device service, please feel free to use any tool you like. ### Write value to GPIO Assume we have a GPIO device connected to pin 134 on current system. 1. Export GPIO pin number `curl -H "Content-Type: application/json" -X PUT -d '{"export": "134"}' http://localhost:48082/api/v1/device/47eb5168-ec63-4be9-bd9a-81d3b2d3ae75/command/57d5cab7-a869-4a4f-a6b4-7bf98f66932` By replacing `134` to another value, you can set up your GPIO device service. This number is normally depends on your mother board and which pin the device is conneted to. When this command is successfully executed, you can use `ls -l /sys/class/gpio` to verify, you should see a file named with `gpio134` in the result of `ls` command. 2. Set out direction `curl -H "Content-Type: application/json" -X PUT -d '{"direction":"out"}' http://localhost:48082/api/v1/device/47eb5168-ec63-4be9-bd9a-81d3b2d3ae75/command/4c32eb83-e21d-4d09-bcd7-235adc460cba` Since we are going to write some value to a exported GPIO, then we just set the direction to `out`. 3. Write value `curl -H "Content-Type: application/json" -X PUT -d '{"value":"1"}' http://localhost:48082/api/v1/device/47eb5168-ec63-4be9-bd9a-81d3b2d3ae75/command/5c612311-10c0-4659-890c-4199b47ef988` Now if you test pin 134, it is outputing high voltage. ### Read value from GPIO Assume we have another GPIO device connected to pin 134 on current system. 1. Export GPIO pin number `curl -H "Content-Type: application/json" -X PUT -d '{"export": "134"}' http://localhost:48082/api/v1/device/47eb5168-ec63-4be9-bd9a-81d3b2d3ae75/command/57d5cab7-a869-4a4f-a6b4-7bf98f66932` 2. Set in direction `curl -H "Content-Type: application/json" -X PUT -d '{"direction":"in"}' http://localhost:48082/api/v1/device/47eb5168-ec63-4be9-bd9a-81d3b2d3ae75/command/4c32eb83-e21d-4d09-bcd7-235adc460cba` Since we are going to read some data from this device, then we just set the direction to `in`. 3. Read value `curl http://localhost:48082/api/v1/device/47eb5168-ec63-4be9-bd9a-81d3b2d3ae75/command/5c612311-10c0-4659-890c-4199b47ef988` Here, we post some results: ```bash $ curl http://localhost...890c-4199b47ef988 {"device":"gpio","origin":1611752289806843150,"readings":[{"origin":1611752289806307945,"device":"gpio","name":"value","value":"{\"gpio\":134,\"value\":0}","valueType":"String"}],"EncodedEvent":null} $ curl http://localhost...890c-4199b47ef988 {"device":"gpio","origin":1611752309686651113,"readings":[{"origin":1611752309686212741,"device":"gpio","name":"value","value":"{\"gpio\":134,\"value\":1}","valueType":"String"}],"EncodedEvent":null} ``` ## API Reference | Method | Core Command | parameters | Description | Response | | ------ | ------------- | ------------------------- | ------------------------------------------------------------ | ------------------------------------ | | put | exportgpio | {"export":<gpionum>} | Export a gpio from "/sys/class/gpio"<br><gpionum>: int, gpio number | 200 ok | | put | unexportgpio | {"unexport":<gpionum>} | Export a gpio from "/sys/class/gpio"<br/><gpionum>: int, gpio number | 200 ok | | put | gpiodirection | {"direction":<direction>} | Set direction for the exported gpio<br/><direction>: string, "in" or "out" | 200 ok | | get | gpiodirection | | Get direction of the exported gpio | "{\"direction\":\"in\",\"gpio\":65}" | | put | gpiovalue | {"value":<value>} | Set value for the exported gpio<br/><value>: int, 1 or 0 | 200 ok | | get | gpiovalue | | Get value of the exported gpio | "{\"gpio\":65,\"value\":1}" | ## License [Apache-2.0](LICENSE)
Java
UTF-8
8,840
2.4375
2
[]
no_license
package cz.cuni.mff.kocur.world; import java.io.IOException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import cz.cuni.mff.kocur.agent.ControllersManager; import cz.cuni.mff.kocur.configuration.ConfigurationChangeListener; import cz.cuni.mff.kocur.configuration.FrameworkConfiguration; import cz.cuni.mff.kocur.console.CommandResponse; import cz.cuni.mff.kocur.console.ConsoleCommand; import cz.cuni.mff.kocur.console.ConsoleHelp; import cz.cuni.mff.kocur.console.ConsoleManager; import cz.cuni.mff.kocur.console.Controllable; import cz.cuni.mff.kocur.events.FrameworkEvent; import cz.cuni.mff.kocur.events.ListenersManager; import cz.cuni.mff.kocur.interests.Team; import cz.cuni.mff.kocur.server.MapperWrapper; import cz.cuni.mff.kocur.server.RequestArguments; import cz.cuni.mff.kocur.server.RequestHandler.CODE; import cz.cuni.mff.kocur.server.TimeManager; /** * This class manages the world * * World update will take these steps: First the client will use a POST message * to send some data/ The data will be in JSON and they will be addressed to * some agent by his name. Manager should then take the data and parse the * objects that correspond to the World objects. Then we update the world * information by updating/inserting the objects using their ids. * * Manager should allow agents to query for informations that are close to them. * * * @author Banzindun * */ public class WorldManager implements Controllable, ConfigurationChangeListener { /** * WorldManager instance. */ private static WorldManager instance = null; /** * * @return Returns WorldManager instance. The instance should be only one * object, during the whole execution. */ public static WorldManager getInstance() { if (instance == null) instance = new WorldManager(); return instance; } /** * Static reference to current world. */ private static World world = new World(); /** * Our time manager. */ private static TimeManager timeManager = new TimeManager(); /** * * @return Returns the world stored inside this class. */ public static World getWorld() { return world; } /** * Instance of framework configuration. */ private FrameworkConfiguration cfg = FrameworkConfiguration.getInstance(); /** * Private constructor. Registers this to talkers. */ private WorldManager() { logger.info("Creating the WorldManager."); // Register to console manager. ConsoleManager.register(this); setupEntities(); } /** * Logger for this class. */ private Logger logger = LogManager.getLogger(WorldManager.class.getName()); /** * Updates the world information. * * @param arg * Request arguments. * @return Returns true, if the world was updated. */ public boolean update(RequestArguments arg) { try { WorldUpdate u = MapperWrapper.readValue(arg.getMessage(), WorldUpdate.class); // Update the world world.update(u); // Update the bot's contextual information updateAgentContext(arg.getAgentName(), u); } catch (IOException e) { logger.error("Unable to update the world information from supplied json.", e, arg.getAgentName(), arg.getMessage()); e.printStackTrace(); return false; } return true; } /** * Updates the agent's context. * * @param name * Name of the agent. * @param u * WorldUpdate, from which we should update the context. */ private void updateAgentContext(String name, WorldUpdate u) { ControllersManager.getInstance().updateAgentContext(name, u); // Create event for agent's update FrameworkEvent agentUpdateEvent = new FrameworkEvent(); agentUpdateEvent.setSourceName(name); ListenersManager.triggerFrameworkEvent("agent_update", agentUpdateEvent); } /** * Does a big world update. This one comes once a second from both teams. * * @param arg * Request arguments - like the body of the request, its url .. * @return Returns true if the update went ok. */ public synchronized boolean updateBig(RequestArguments arg) { try { WorldUpdate u = MapperWrapper.readValue(arg.getMessage(), WorldUpdate.class); if (u.getTime() != -1) { timeManager.tick(u.getTime()); } // Update the world world.update(u); // Update the team context. updateTeamContext(arg.getMethod(), u); // Do the cleanup world.cleanup(); } catch (IOException e) { logger.error("Unable to perform big update from supplied json.", e); e.printStackTrace(); return false; } catch (Exception e) { e.printStackTrace(); return false; } return true; } /** * Updates team context. * * @param method * Code of the method (UPDATEDIRE, UPDATERADIANT) * @param u * WorldUpdate from which we update the world. */ private void updateTeamContext(CODE method, WorldUpdate u) { // Create a new event. FrameworkEvent teamUpdateEvent = new FrameworkEvent(); if (method == CODE.UPDATERADIANT) { ControllersManager.getInstance().updateTeamContext(Team.RADIANT, u); teamUpdateEvent.setType(Team.RADIANT); } else if (method == CODE.UPDATEDIRE) { ControllersManager.getInstance().updateTeamContext(Team.DIRE, u); teamUpdateEvent.setType(Team.DIRE); } else { logger.warn("Unknown update on team context level."); return; } // Trigger the teamupdate event ListenersManager.triggerFrameworkEvent("team_update", teamUpdateEvent); } /** * Setups the StaticEntity, Hero and BaseNPC static variables to match the * values from configuration. */ private void setupEntities() { try { Float l = Float.parseFloat(cfg.getConfigValue("hero_time_to_live")); if (l != null) Hero.timeToLive = l; } catch (NumberFormatException e) { logger.warn("Could not parse Hero_time_to_live from FrameworkConfiguration."); } try { Float l = Float.parseFloat(cfg.getConfigValue("basenpc_time_to_live")); if (l != null) BaseNPC.timeToLive = l; } catch (NumberFormatException e) { logger.warn("Could not parse BaseNPC_time_to_live from FrameworkConfiguration."); } try { Float l = Float.parseFloat(cfg.getConfigValue("creep_time_to_live")); if (l != null) Creep.timeToLive = l; } catch (NumberFormatException e) { logger.warn("Could not parse Creep_time_to_live from FrameworkConfiguration."); } try { Float l = Float.parseFloat(cfg.getConfigValue("tower_time_to_live")); if (l != null) Tower.timeToLive = l; } catch (NumberFormatException e) { logger.warn("Could not parse Tower_time_to_live from FrameworkConfiguration."); } try { Float l = Float.parseFloat(cfg.getConfigValue("building_time_to_live")); if (l != null) Building.timeToLive = l; } catch (NumberFormatException e) { logger.warn("Could not parse Building_time_to_live from FrameworkConfiguration."); } } /** * Resets the world reference. */ public static void reset() { world = new World(); timeManager = new TimeManager(); } @Override public CommandResponse command(ConsoleCommand cmd) { CommandResponse res = new CommandResponse(); if (cmd.size() == 0) return res.fail("Too few arguments."); String first = cmd.getField(); switch (first) { case "print": if (world != null) res.append(world.toString()); res.pass(); break; case "search": res = searchByName(cmd); break; default: return res.fail("Unknown command"); } return res; } /** * Searches the world by name (through the console). Returns the result inside * the CommandResponse. * * @param cmd * The command = contains the name of the entity. * @return Returns a command's response. The response can be negative or it can * fail. */ private CommandResponse searchByName(ConsoleCommand cmd) { CommandResponse res = new CommandResponse(); // I should have just the one argument. if (cmd.size() != 1) { return res.fail("Too few arguments supplied for search."); } res.appendLine("id: " + world.searchIdByName(cmd.getField())); return res.pass(); } @Override public String getHelp() { ConsoleHelp help = new ConsoleHelp(); help.appendLines(new String[] { "World controllable:", "\tprint -> displays the current world", "\tinterests -> displays interests in the current world", "\tbuildings -> displays buildings in the current world", "\ttowers -> displays towers in the current world", "\tcreeps -> displays creeps in the current world", "\theroes -> displays heroes in the current world", "\tsearch [name] -> searches the objects by name, returns the id", }); return help.toString(); } @Override public String getControllableName() { return "world"; } @Override public void configurationChanged() { } }
C#
UTF-8
1,607
2.875
3
[]
no_license
using AgendaTelefonica.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AgendaTelefonica.Repositorio { public class ContatoRepositirio { private List<Contato> Contatos; private void CriaDados() { Contatos = new List<Contato>(); Contatos.Add(new Contato( 1, "Thamy", "123456789", "[email protected]")); Contatos.Add(new Contato( 2, "Ale", "987654321", "[email protected]", apelido: "irmão da Aléxia")); Contatos.Add(new Contato( 3, "Sei lá", "123456543", "[email protected]")); } public ContatoRepositirio() { CriaDados(); } public List<Contato> SelecionarTodos() { return Contatos.OrderBy(t => t.Nome).ToList(); } public Contato BuscarContato(int id) { return Contatos.FirstOrDefault(t => t.Id == id); } public void IncluirContato(Contato contato) { Contatos.Add(contato); } public void EditarContato(Contato contato) { var meuContato = BuscarContato(contato.Id); int indice = Contatos.IndexOf(meuContato); Contatos[indice] = contato; } public void ExcluirContato(int id) { Contatos.Remove(BuscarContato(id)); } } }
Rust
UTF-8
10,338
2.875
3
[ "LLVM-exception", "Apache-2.0" ]
permissive
use rayon::iter::{IntoParallelIterator, ParallelExtend, ParallelIterator}; use std::convert::TryFrom; use wasmtime::{AsContext, AsContextMut}; const WASM_PAGE_SIZE: u32 = 65_536; /// The maximum number of data segments that most engines support. const MAX_DATA_SEGMENTS: usize = 100_000; /// A "snapshot" of Wasm state from its default value after having been initialized. pub struct Snapshot { /// Maps global index to its initialized value. pub globals: Vec<wasmtime::Val>, /// A new minimum size for each memory (in units of pages). pub memory_mins: Vec<u32>, /// Segments of non-zero memory. pub data_segments: Vec<DataSegment>, /// Snapshots for each nested instantiation. pub instantiations: Vec<Snapshot>, } /// A data segment initializer for a memory. #[derive(Clone, Copy)] pub struct DataSegment { /// The index of this data segment's memory. pub memory_index: u32, /// This data segment's initialized memory that it originated from. pub memory: wasmtime::Memory, /// The offset within the memory that `data` should be copied to. pub offset: u32, /// This segment's length. pub len: u32, } impl DataSegment { pub fn data<'a>(&self, ctx: &'a impl AsContext) -> &'a [u8] { let start = usize::try_from(self.offset).unwrap(); let end = start + usize::try_from(self.len).unwrap(); &self.memory.data(ctx)[start..end] } } impl DataSegment { /// What is the gap between two consecutive data segments? /// /// `self` must be in front of `other` and they must not overlap with each /// other. fn gap(&self, other: &Self) -> u32 { debug_assert_eq!(self.memory_index, other.memory_index); debug_assert!(self.offset + self.len <= other.offset); other.offset - (self.offset + self.len) } /// Merge two consecutive data segments. /// /// `self` must be in front of `other` and they must not overlap with each /// other. fn merge(&self, other: &Self) -> DataSegment { let gap = self.gap(other); DataSegment { offset: self.offset, len: self.len + gap + other.len, ..*self } } } /// Snapshot the given instance's globals, memories, and instances from the Wasm /// defaults. // // TODO: when we support reference types, we will have to snapshot tables. pub fn snapshot(ctx: &mut impl AsContextMut, instance: &wasmtime::Instance) -> Snapshot { log::debug!("Snapshotting the initialized state"); let globals = snapshot_globals(&mut *ctx, instance); let (memory_mins, data_segments) = snapshot_memories(&mut *ctx, instance); let instantiations = snapshot_instantiations(&mut *ctx, instance); Snapshot { globals, memory_mins, data_segments, instantiations, } } /// Get the initialized values of all globals. fn snapshot_globals( ctx: &mut impl AsContextMut, instance: &wasmtime::Instance, ) -> Vec<wasmtime::Val> { log::debug!("Snapshotting global values"); let mut globals = vec![]; let mut index = 0; loop { let name = format!("__wizer_global_{}", index); match instance.get_global(&mut *ctx, &name) { None => break, Some(global) => { globals.push(global.get(&mut *ctx)); index += 1; } } } globals } /// Find the initialized minimum page size of each memory, as well as all /// regions of non-zero memory. fn snapshot_memories( ctx: &mut impl AsContextMut, instance: &wasmtime::Instance, ) -> (Vec<u32>, Vec<DataSegment>) { log::debug!("Snapshotting memories"); // Find and record non-zero regions of memory (in parallel). let mut memory_mins = vec![]; let mut data_segments = vec![]; let mut memory_index = 0; loop { let name = format!("__wizer_memory_{}", memory_index); let memory = match instance.get_memory(&mut *ctx, &name) { None => break, Some(memory) => memory, }; memory_mins.push(memory.size(&*ctx)); let num_wasm_pages = memory.size(&*ctx); let memory_data = memory.data(&*ctx); // Consider each Wasm page in parallel. Create data segments for each // region of non-zero memory. data_segments.par_extend((0..num_wasm_pages).into_par_iter().flat_map(|i| { let page_end = ((i + 1) * WASM_PAGE_SIZE) as usize; let mut start = (i * WASM_PAGE_SIZE) as usize; let mut segments = vec![]; while start < page_end { let nonzero = match memory_data[start..page_end] .iter() .position(|byte| *byte != 0) { None => break, Some(i) => i, }; start += nonzero; let end = memory_data[start..page_end] .iter() .position(|byte| *byte == 0) .map_or(page_end, |zero| start + zero); segments.push(DataSegment { memory_index, memory, offset: u32::try_from(start).unwrap(), len: u32::try_from(end - start).unwrap(), }); start = end; } segments })); memory_index += 1; } if data_segments.is_empty() { return (memory_mins, data_segments); } // Sort data segments to enforce determinism in the face of the // parallelism above. data_segments.sort_by_key(|s| (s.memory_index, s.offset)); // Merge any contiguous segments (caused by spanning a Wasm page boundary, // and therefore created in separate logical threads above) or pages that // are within four bytes of each other. Four because this is the minimum // overhead of defining a new active data segment: one for the memory index // LEB, two for the memory offset init expression (one for the `i32.const` // opcode and another for the constant immediate LEB), and finally one for // the data length LEB). const MIN_ACTIVE_SEGMENT_OVERHEAD: u32 = 4; let mut merged_data_segments = Vec::with_capacity(data_segments.len()); merged_data_segments.push(data_segments[0]); for b in &data_segments[1..] { let a = merged_data_segments.last_mut().unwrap(); // Only merge segments for the same memory. if a.memory_index != b.memory_index { merged_data_segments.push(*b); continue; } // Only merge segments if they are contiguous or if it is definitely // more size efficient than leaving them apart. let gap = a.gap(b); if gap > MIN_ACTIVE_SEGMENT_OVERHEAD { merged_data_segments.push(*b); continue; } // Okay, merge them together into `a` (so that the next iteration can // merge it with its predecessor) and then omit `b`! let merged = a.merge(b); *a = merged; } remove_excess_segments(&mut merged_data_segments); (memory_mins, merged_data_segments) } /// Engines apply a limit on how many segments a module may contain, and Wizer /// can run afoul of it. When that happens, we need to merge data segments /// together until our number of data segments fits within the limit. fn remove_excess_segments(merged_data_segments: &mut Vec<DataSegment>) { if merged_data_segments.len() < MAX_DATA_SEGMENTS { return; } // We need to remove `excess` number of data segments. let excess = merged_data_segments.len() - MAX_DATA_SEGMENTS; #[derive(Clone, Copy, PartialEq, Eq)] struct GapIndex { gap: u32, // Use a `u32` instead of `usize` to fit `GapIndex` within a word on // 64-bit systems, using less memory. index: u32, } // Find the gaps between the start of one segment and the next (if they are // both in the same memory). We will merge the `excess` segments with the // smallest gaps together. Because they are the smallest gaps, this will // bloat the size of our data segment the least. let mut smallest_gaps = Vec::with_capacity(merged_data_segments.len() - 1); for (index, w) in merged_data_segments.windows(2).enumerate() { if w[0].memory_index != w[1].memory_index { continue; } let gap = w[0].gap(&w[1]); let index = u32::try_from(index).unwrap(); smallest_gaps.push(GapIndex { gap, index }); } smallest_gaps.sort_unstable_by_key(|g| g.gap); smallest_gaps.truncate(excess); // Now merge the chosen segments together in reverse index order so that // merging two segments doesn't mess up the index of the next segments we // will to merge. smallest_gaps.sort_unstable_by(|a, b| a.index.cmp(&b.index).reverse()); for GapIndex { index, .. } in smallest_gaps { let index = usize::try_from(index).unwrap(); let merged = merged_data_segments[index].merge(&merged_data_segments[index + 1]); merged_data_segments[index] = merged; // Okay to use `swap_remove` here because, even though it makes // `merged_data_segments` unsorted, the segments are still sorted within // the range `0..index` and future iterations will only operate within // that subregion because we are iterating over largest to smallest // indices. merged_data_segments.swap_remove(index + 1); } // Finally, sort the data segments again so that our output is // deterministic. merged_data_segments.sort_by_key(|s| (s.memory_index, s.offset)); } fn snapshot_instantiations( ctx: &mut impl AsContextMut, instance: &wasmtime::Instance, ) -> Vec<Snapshot> { log::debug!("Snapshotting nested instantiations"); let mut instantiations = vec![]; loop { let name = format!("__wizer_instance_{}", instantiations.len()); match instance.get_export(&mut *ctx, &name) { None => break, Some(wasmtime::Extern::Instance(instance)) => { instantiations.push(snapshot(&mut *ctx, &instance)); } Some(_) => unreachable!(), } } instantiations }
Python
UTF-8
2,200
2.8125
3
[]
no_license
import logging import pygame from battle_city.game_objects.game_object import Directions, Movable logger = logging.getLogger(__name__) class Missile(Movable): image = "media/images/missile.png" def __init__(self, position, direction: Directions, *args, **kwargs): super().__init__(position, *args, **kwargs) self.direction = direction self.image = pygame.transform.rotate(self.sprite, direction.get_angle()) self.rect = self.image.get_rect() self.rect.x, self.rect.y = position.x, position.y self.speed = 15 logger.debug( f"Missle was created on position: \ {position} with direction {self.direction}" ) def update(self, event: pygame.event, level, *args): position = self.move(self.direction) tank_index = self.is_collidelist(position, level.tanks) wall_index = self.is_collidelist(position, level.walls) if position.colliderect(level.command_center.rect): level.command_center = None self.kill(level) elif position.colliderect(level.player.rect): if level.player.health > 0: level.player.health -= 1 else: logger.debug("Player killed") level.player = None self.kill(level) elif tank_index >= 0: tank = level.tanks[tank_index] if tank.health > 0: tank.health -= 1 else: level.tanks.remove(tank) self.kill(level) elif wall_index >= 0: logger.debug(f"Hitted in wall {wall_index}") wall = level.walls[wall_index] if wall.health > 0: wall.health -= 1 else: logger.debug(f"Killing wall {wall_index}") level.walls.remove(wall) self.kill(level) elif not self.in_borders(position, level) \ or self.is_collidelist(position, level.blocks) >= 0: self.kill(level) else: self.rect = position def kill(self, level): level.missiles.remove(self)
Markdown
UTF-8
6,074
3.3125
3
[]
no_license
# JS 一些常用的手写方法 ## 判断数据类型 ```js function checkIsDataType(data) { return Object.prototype.toString.call(data).slice(8, -1) } ``` ## 数组去重 ```js function unique(array) { return array.filter((item, index, array) => { return array.indexOf(item) === index }) } ``` ## 数组扁平化 ```js function flatten(array) { let res = [] for (let i = 0; i < array.length; i++) { if (Array.isArray(array[i])) { res.concat(flatten(array[i])) } else { res.push(array[i]) } } } function flatten(array) { while (array.some((item) => Array.isArray(item))) { array.concat(...item) } } ``` ## 浅拷贝 ```js function shadowCopy(obj) { if (typeof obj !== 'object') return let newObj = obj instanceof array ? [] : {} for (let key in obj) { if (obj.hasOwnPrototype(key)) { newObj[key] = obj[key] } } return newObj } ``` ```js function deepCopy(obj) { if (typeof obj !== 'object') return let newObj = obj instanceof array ? [] : {} for (let key in obj) { if (obj.hasOwnPrototype(key)) { newObj[key] = typeof obj[key] === 'object' ? deepCopy(obj) : obj[key] } } } ``` ## forEach 的模拟实现 ```js Array.prototype.myForEach = function(fn, thisArg) { if (this == null) { throw new TypeError('this is null or is not defined') } if (typeof fn !== 'function') { throw new TypeError(`${fn} is not a funciton`) } const len = this.length this = thisArg || window for (let i = 0; i < len; i++) { fn.call(this.value, this[i], i, this) } } ``` ## map 的模拟实现 ```js Array.prototype.myForEach = function(fn, thisArg) { if (this == null) { throw new TypeError('this is null or is not defined') } if (typeof fn !== 'function') { throw new TypeError(`${fn} is not a funciton`) } const len = this.length let res = [] this = thisArg || window for (let i = 0; i < len; i++) { res[i] = fn.call(this.value, this[i], i, this) } return res } ``` ## filter 的模拟实现 ```js Array.prototype.myFilter = function(fn, thisArg) { if (this == null) { throw new TypeError('this is null or is not defined') } if (typeof fn !== 'function') { throw new TypeError(`${fn} is not a funciton`) } const len = this.length let res = [] this = thisArg || window for (let i = 0; i < len; i++) { if (fn.call(this.value, this[i], i, this)) { res[i] = this[i] } } return res } ``` ## some 的模拟实现 ```js Array.prototype.mySome = function(fn, thisArg) { if (this == null) { throw new TypeError('this is null or is not defined') } if (typeof fn !== 'function') { throw new TypeError(`${fn} is not a funciton`) } const len = this.length let res = [] this = thisArg || window for (let i = 0; i < len; i++) { if (fn.call(this.value, this[i], i, this)) { return true } } return false } ``` ## call 的模拟实现 ```js Function.prototype.myCall = function(context) { var context = context || window context.fn = this var args = [] for (let i = 1; i < arguments.length; i++) { args.push(arguments[i]) } context.fn(...args) delete context.fn } ``` ## apply 的模拟实现 ```js Function.prototype.myApply = function(context) { var context = context || window context.fn = this var args = [] for (let i = 1; i < arguments.length; i++) { args.push(arguments[i]) } context.fn(args) delete context.fn } ``` ## new 的模拟实现 ```js function createFactory() { var obj = new Obj() Constructor = [].shift.call(arguments) obj._proto_ = Constructor.prototype let res = Constructor.apply(obj, arguments) return typeof ret === 'object' ? ret : obj } ``` ## Object.assign 模拟实现 ```js Object.assign2 = function(target, ...source) { let obj = target source.forEach((item) => { if (obj !== null) { for (let key in obj) { ret[key] = obj[key] } } }) } ``` ## 节流(throttle)的实现 ```js function throttle(fn, wait) { var timeout var previous = 0 return function() { var now = new Date() context = this args = argument if (!timeout) { timeout = setTimeout(() => { timeout = null fn.call(context, args) }) } } } function throttle(fn, wait) { var context, args var previous = 0 return function() { var now = +new Date() context = this args = arguments if (now - previous > wait) { fn.call(context, args) previous = now } } } ``` ## 防抖(debounce)的实现 ```js function debounce(func, wait) { var timeout return function() { var context = this var args = argument clearTimeout(timeout) timeout = setTimeout(() => { func.apply(context, args) }, wait) } } ``` ## EventBus 的手写实现 ```js class EventBus { private events = {}; on(name, callback) { this.events[name] = this.events[name] || []; this.events.push(callback); } emit(name, data) { (this.events[name] || []).forEach((fn) => { fn(data); }); } off(name, fn) { const index = this.events[name].indexOf(fn); if (index > 0) { this.events[name].splice(index, 1); } } } ```
Java
UTF-8
181
1.90625
2
[]
no_license
package cs413f15team01p4.timer.model.clock; /** * Created by Home on 11/5/2015. */ public interface ClockModel extends OnTickSource { void onStart(); void onStop(); }
C#
UTF-8
1,749
2.71875
3
[]
no_license
namespace DataCollectionAPI.Migrations { using Microsoft.AspNet.Identity.EntityFramework; using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<DataCollectionAPI.Models.ApplicationDbContext> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(DataCollectionAPI.Models.ApplicationDbContext context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. E.g. // // context.People.AddOrUpdate( // p => p.FullName, // new Person { FullName = "Andrew Peters" }, // new Person { FullName = "Brice Lambson" }, // new Person { FullName = "Rowan Miller" } // ); // var sysAdmin= new IdentityRole { Id = "c04e2839-d9f7-42bc-a7e2-9c8bcee1040b", Name = "系统管理员" }; var admin = new IdentityRole { Id = "1614e96a-ce16-45a8-99db-ffbcb1d53718", Name = "普通管理员" }; var manager = new IdentityRole { Id = "b3000fd7-2ac5-409a-b582-d3c2d8457459", Name = "客户经理" }; var apply = new IdentityRole { Id = "d803555e-7801-45ae-b219-ec1cd40dd170", Name = "客户端待授权者" }; context.Roles.AddOrUpdate( r => r.Id, sysAdmin, admin, manager, apply ); } } }
Java
UTF-8
7,040
1.851563
2
[]
no_license
package com.smoothsys.qonsume_pos.FragmentsAndActivities; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.ExpandableListView; import android.widget.ListView; import com.smoothsys.qonsume_pos.Adapters.BadgeUpdateInterface; import com.smoothsys.qonsume_pos.Adapters.OrderCreateScreen.OrderCreateELA; import com.smoothsys.qonsume_pos.Models.ItemClasses.Attribute; import com.smoothsys.qonsume_pos.Models.ItemClasses.Detail; import com.smoothsys.qonsume_pos.Models.ItemClasses.Item; import com.smoothsys.qonsume_pos.Models.ItemClasses.ItemResponseObject; import com.smoothsys.qonsume_pos.Models.RestaurantClasses.Category; import com.smoothsys.qonsume_pos.Models.RestaurantClasses.SubCategory; import com.smoothsys.qonsume_pos.R; import com.smoothsys.qonsume_pos.Retrofit.ISnabbOrderAPI; import com.smoothsys.qonsume_pos.Retrofit.RetrofitManager; import com.smoothsys.qonsume_pos.Utilities.Cache; import com.smoothsys.qonsume_pos.Utilities.Utils; import com.squareup.picasso.Picasso; import java.util.HashMap; import java.util.List; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * Created by Pontus on 2017-06-06. */ public class CategoryFragment extends Fragment { private ExpandableListView listView; private OrderCreateELA listAdapter; private Category mCategory; private List<SubCategory> subCategories; Picasso picasso; SharedPreferences prefs = null; static BadgeUpdateInterface buttonListener; private static SwipeRefreshLayout refreshLayout; public static HashMap<SubCategory,List<Item>> itemsMap; public static CategoryFragment newInstance(Category c, BadgeUpdateInterface badgeUpdateInterface, SwipeRefreshLayout rl) { CategoryFragment fragment = new CategoryFragment(); buttonListener = badgeUpdateInterface; refreshLayout = rl; fragment.setCategory(c); return fragment; } public void setCategory(Category c) { mCategory = c; subCategories = mCategory.getSubCategories(); } @Override public void onCreate(Bundle savedInstanceState) { itemsMap = new HashMap<>(); prefs = PreferenceManager.getDefaultSharedPreferences(getContext()); picasso = new Picasso.Builder(getContext()).build(); setHasOptionsMenu(true); super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_create_items, container, false); final ExpandableListView list = view.findViewById(R.id.itemList); list.setOnTouchListener((v, event) -> { if(listIsAtTop(list)){ refreshLayout.setEnabled(true); } else { refreshLayout.setRefreshing(false); refreshLayout.setEnabled(false); } return false; }); return view; } private boolean listIsAtTop(ListView listView) { if(listView.getChildCount() == 0) return true; return listView.getChildAt(0).getTop() == 0; } @Override public void onStart() { initData(); listAdapter = new OrderCreateELA(getContext(), subCategories,itemsMap, picasso, buttonListener); listView = getView().findViewById(R.id.itemList); if(subCategories != null) { listView.setAdapter(listAdapter); } super.onStart(); getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } List<Item> items; private void initData(){ if (subCategories == null) { return; } for(int i = 0; i<subCategories.size(); i++) { ISnabbOrderAPI snabbpayInterface = RetrofitManager.SetupInterfaceFromCredentials(prefs); int subCatId = Integer.parseInt(subCategories.get(i).getId()); final SubCategory currentSubCat = subCategories.get(i); Call<ItemResponseObject> itemCall = snabbpayInterface.getItems(Cache.mMerchant.getShopID(),subCatId); final int finalI = i; itemCall.enqueue(new Callback<ItemResponseObject>() { @Override public void onResponse(Call<ItemResponseObject> call, Response<ItemResponseObject> response) { if(!isValidResponse(response)) { return; } ItemResponseObject itemResponse = response.body(); items = itemResponse.getData(); setDefaultAttribute(); itemsMap.put(currentSubCat, items); // if this is the last subCategory to be loaded - update adapter. if(finalI == subCategories.size()-1) { listAdapter.notifyDataSetChanged(); } } @Override public void onFailure(Call<ItemResponseObject> call, Throwable t) { Utils.makeToast("Something went wrong when fetching items from the server.",getActivity()); } }); } } private void setDefaultAttribute() { for (Item item: items) { List<Attribute> attributes = item.getAttributes(); if(attributes.size() > 0) { Attribute firstAttribute = item.getAttributes().get(0); List<Detail> details = firstAttribute.getDetails(); if(details.size() > 0) { Detail firstDetail = firstAttribute.getDetails().get(0); } } } } private boolean isValidResponse(Response<ItemResponseObject> response) { if(response.code() != 200) { Utils.makeToast("Failed to load items for one or more subcategories." + response.message(), getActivity()); return false; } ItemResponseObject itemResponse = response.body(); if(itemResponse == null) { return false; } if(itemResponse.getData() == null) { return false; } if(!itemResponse.getStatus().equals("success")) { Utils.makeToast("Something went wrong when fetching items.", getActivity()); return false; } items = itemResponse.getData(); if(items.size() < 1) { return false; } return true; } public void onResume() { ((MainActivity)getActivity()).setTitleBarText(getString(R.string.itemsScreen_name)); super.onResume(); } }
Ruby
UTF-8
729
3.1875
3
[]
no_license
require_relative '../setup' require_relative './exercise_1' require_relative './exercise_2' require_relative './exercise_3' require_relative './exercise_4' require_relative './exercise_5' puts "Exercise 6" puts "----------" # Your code goes here ... # Update store1 name back to Burnaby burnaby = Store.find_by(id: 1) burnaby.name = 'Burnaby' burnaby.save # Add some data into employees @store1.employees.create(first_name: "Khurram", last_name: "Virani", hourly_rate: 60) @store1.employees.create(first_name: "Captain", last_name: "America", hourly_rate: 100) @store2.employees.create(first_name: "Iron", last_name: "Man", hourly_rate: 300) @store2.employees.create(first_name: "Black", last_name: "Widow", hourly_rate: 200)
Java
UTF-8
307
2.515625
3
[]
no_license
package document; public class Author { private String firstname; private String lastname; private String email; private String belongto; public Author(String f, String l, String e, String b) { this.firstname = f; this.lastname = l; this.email = e; this.belongto = b; } }
Python
UTF-8
3,877
3.015625
3
[]
no_license
from manipulate_sequences import * # use this function to get the positions of the coding sequence for each transcript def get_CDS_positions(caeno_gff): ''' (file) -> dict Returns a dictionnary with transcript name as key and list of tuples containing the start and end positions of each coding regions of the given transcript, plus the chromosome, and the orientation of the gene on chromosome ''' # create dictionnary to store positions # {TS1: [chromo, sense, [(s1, end1), (s2, end2)]]} CDS = {} # open gff file for reading gff = open(caeno_gff, 'r') for line in gff: line = line.rstrip() if line != '': line = line.split() if len(line) > 8: if line[2] == 'mRNA': chromo = line[0] orientation = line[6] transcript = line[8][line[8].index('ID=')+3 : line[8].index(';')] CDS[transcript] = [chromo, orientation, []] elif line[2] == 'CDS': start = int(line[3]) end = int(line[4]) name = line[8][line[8].index('ID=') + 3: line[8].index(':')] if name in CDS: CDS[name][2].append((start, end)) # sort the coordinates relative to their order on chromosome for transcript in CDS: CDS[transcript][2].sort() gff.close() return CDS # use this function to generate a fasta file with the transcripts' coding sequences def grab_CDS_sequences(caeno_gff, genome_file, output_file): ''' (file, file) -> file Extracts the positions of the coding sequences for each transcript from the gff file, grab the coding sequences using the coordinates from the genome sequence, and save sequences excluding the terminal stop codon to output_file in fasta format ''' # make a set with stop codons: stop_codons = {'TAA', 'TAG', 'TGA', 'taa', 'tag', 'tga'} # convert the genome sequence into a dictionnary genome = convert_fasta(genome_file) # get the coordinates of the coding sequences for each transcript CDS_coordinates = get_CDS_positions(caeno_gff) # create a dictionnary to store the CDS sequences CDS_sequences = {} # use CDS coordinates to fetch the coding sequences for transcript in CDS_coordinates: chromo = CDS_coordinates[transcript][0] chromo_seq = genome[chromo] transcript_seq = '' # for each CDS cordinate start, end pair, grab the sequence for pair in CDS_coordinates[transcript][2]: start = pair[0] - 1 # indice of seq starts at 0 end = pair[1] # end is not included exon = chromo_seq[start:end] transcript_seq += exon # if the orientation is anti-sense, take the reverse complement if CDS_coordinates[transcript][1] == '-': rev_compl_seq = reverse_complement(transcript_seq) CDS_sequences[transcript] = rev_compl_seq elif CDS_coordinates[transcript][1] == '+': CDS_sequences[transcript] = transcript_seq # make the sequences in upper case for transcript in CDS_sequences: CDS_sequences[transcript] = CDS_sequences[transcript].upper() # exclude terminal codon for transcript in CDS_sequences: if CDS_sequences[transcript][-3:] in stop_codons: CDS_sequences[transcript] = CDS_sequences[transcript][:-3] # open file for writing newfile = open(output_file, 'w') for transcript in CDS_sequences: newfile.write('>' + transcript + '\n') newfile.write(CDS_sequences[transcript] + '\n') newfile.close()
Java
UTF-8
2,195
2.296875
2
[]
no_license
package ee.bmagrupp.aardejaht.server.rest; import java.util.Date; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import ee.bmagrupp.aardejaht.server.domain.Treasure; import ee.bmagrupp.aardejaht.server.domain.Trek; import ee.bmagrupp.aardejaht.server.repository.TrekService; import ee.bmagrupp.aardejaht.server.repository.UserService; @RestController @RequestMapping("/trek") public class TrekController { private static Logger LOG = LoggerFactory.getLogger(TrekController.class); @Autowired TrekService trekServ; @Autowired UserService userServ; @RequestMapping(method = RequestMethod.GET, value = "/{id}") public ResponseEntity<Trek> getById(@PathVariable int id) { Trek trek = trekServ.findById(id); return new ResponseEntity<Trek>(trek, HttpStatus.ACCEPTED); } @RequestMapping(method = RequestMethod.GET) public ResponseEntity<List<Trek>> getAll() { List<Trek> treks = (List<Trek>) trekServ.findAll(); return new ResponseEntity<List<Trek>>(treks, HttpStatus.ACCEPTED); } @RequestMapping(method = RequestMethod.POST) public ResponseEntity<Trek> startTrek(@RequestBody Treasure treasure) { Trek trek = new Trek(userServ.findById(1), treasure); trekServ.save(trek); return new ResponseEntity<Trek>(trek, HttpStatus.ACCEPTED); } @RequestMapping(method = RequestMethod.POST, value = "/end") public ResponseEntity<Trek> endtTrek(@RequestBody Trek trekOld) { // If database query is too slow, then the endtime set must be brought // forward Trek trek = trekServ.findById(trekOld.getId()); trek.setEndTime(new Date()); trek.setDifference(0); trek.setScore(0); trekServ.save(trek); return new ResponseEntity<Trek>(trek, HttpStatus.ACCEPTED); } }
C
UTF-8
1,250
3.21875
3
[]
no_license
#include "functions_headerfile.h" ssize_t ft_strlen(char *string) { int i; i = 0; if (string == NULL) return (-1); while (string[i] != 0) i++; return (i); } char *my_calloc(int length) { int i; char *result; i = 0; result = malloc(length); if (result == NULL) return (NULL); while (i < length) { result[i] = '\0'; i++; } return (result); } char *my_realloc(char *str, char c) { ssize_t length; char *result; int i; i = 0; if (str == NULL) return (NULL); length = ft_strlen(str) + 2; result = my_calloc(length); while (str[i] != 0) { result[i] = str[i]; i++; } result[i] = c; free(str); str = NULL; return (result); } int my_strcmp(char *s1, char *s2) { int a; int b; int i; i = 0; if (s1 == NULL || s2 == NULL) return (-1); a = ft_strlen(s1); b = ft_strlen(s2); if (a != b) return (1); else { while (s1[i] != 0 && s2[i] != 0 && s1[i] == s2[i]) i++; if (s1[i] != s2[i]) return (1); else return (0); } } char *fetch_input(void) { char *input; char c; input = my_calloc(1 * sizeof(char)); if (input == NULL) return (NULL); while (read(1, &c, 1) == 1 && c != '\n') { input = my_realloc(input, c); if (input == NULL) return (NULL); } return (input); }
Shell
UTF-8
428
2.546875
3
[]
no_license
#!/bin/bash -l #SBATCH -p aolin.q #SBATCH --exclusive hostname module rm gcc/8.2.0 module add gcc/9.2.0 # compile for CPU with optimization level 1 gcc -O1 -lm $1 -o ${2}.O1 # execute and measure total time and general performance counters perf stat ${2}.O1 echo # execute and generate performance profiling file (perf.stat) perf record ${2}.O1 # after remote execution, use the command "perf report" to visualize results
C++
UTF-8
1,655
3.140625
3
[]
no_license
#include "../classes/Airplane.h" #include "../classes/Airport.h" #include "../classes/Runway.h" #include "../classes/Location.h" #include <gtest/gtest.h> class LocationDomainTests: public ::testing::Test { protected: friend class Location; virtual void SetUp() { ::testing::FLAGS_gtest_death_test_style = "threadsafe"; }; virtual void TearDown() { }; }; TEST_F(LocationDomainTests, initializerAndGetters) { std::string locationName = "Alpha"; Location location = Location(locationName); EXPECT_EQ(location.getName(), locationName); EXPECT_EQ(location.getAirport(), static_cast<Airport*>(NULL)); EXPECT_EQ(location.getPreviousLocation(), static_cast<Location*>(NULL)); EXPECT_EQ(location.getNextLocation(), static_cast<Location*>(NULL)); } TEST_F(LocationDomainTests, setters) { std::string locationName = "Alpha"; Location location = Location(locationName); Airport airport = Airport("Dummy Airport", "DUM", "Dummy", 3); EXPECT_EQ(location.getAirport(), static_cast<Airport*>(NULL)); location.setAirport(&airport); EXPECT_EQ(location.getAirport(), &airport); Location previousLocation = Location("Dummy Previous Location"); EXPECT_EQ(location.getPreviousLocation(), static_cast<Location*>(NULL)); location.setPreviousLocation(&previousLocation); EXPECT_EQ(location.getPreviousLocation(), &previousLocation); Location nextLocation = Location("Dummy Next Location"); EXPECT_EQ(location.getNextLocation(), static_cast<Location*>(NULL)); location.setNextLocation(&nextLocation); EXPECT_EQ(location.getNextLocation(), &nextLocation); }
C++
UTF-8
392
3.234375
3
[]
no_license
// loops.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include <iostream> using namespace std; int main() { for (int i = 0; i < 10; i++) { if (i == 6) { break; //if i is 6 the program stops without printing it } else if (i == 4) { continue; //if i is 4, doesn't print 4 } cout << i << "\n"; } }
Java
UTF-8
301
1.671875
2
[]
no_license
package com.TwistWallet.service; import com.TwistWallet.utils.TwistWalletRequest; import com.TwistWallet.utils.TwistWalletResponse; public interface UserService { public TwistWalletResponse createUser(TwistWalletRequest request); public TwistWalletResponse sendMail(TwistWalletRequest request); }
Python
UTF-8
2,454
3.53125
4
[]
no_license
# AdaptiveLinearStretching.py # # Description: # This program gets as inputs a window parameter (w) and names of the input and the # output images. The output image is computed from the input image by changing only # the L values such that L(i, j) is computed by applying linear stretching to the # window of size (2w+1 × 2w+1) centered at (i, j). The L value at the center of the # window is the output value L(i, j). It should be executed as follows: # python AdaptiveLinearStretching.py <w> <inputImage> <outputImage> import cv2 import numpy as np import sys # Read arguments if(len(sys.argv) != 4) : print(sys.argv[0], ": takes 3 arguments. Not ", len(sys.argv)-1) print("Expecting arguments: w ImageIn ImageOut.") print("Example:", sys.argv[0], "10 fruits.jpg out.png") sys.exit() w = int(sys.argv[1]) inputName = sys.argv[2] outputName = sys.argv[3] # Read image inputImage = cv2.imread(inputName, cv2.IMREAD_COLOR) if(inputImage is None) : print(sys.argv[0], ": Failed to read image from: ", inputName) sys.exit() cv2.imshow("input image: " + inputName, inputImage) rows, cols, bands = inputImage.shape if(bands != 3) : print("Input image is not a standard color image:", inputImage) sys.exit() # Convert BGR image to Luv image luvImage = cv2.cvtColor(inputImage, cv2.COLOR_BGR2Luv) # Initialize output image newLuvImage = np.zeros([rows, cols, bands],dtype=np.uint8) # Note: Output pixel is computed from a window of size 2w+1 x 2w+1 in the input image # Loop through windows for i in range(w, rows-w) : for j in range(w, cols-w) : # Get array of all L values in window L_values = luvImage[i-w:i+w+1, j-w:j+w+1, 0].flatten() # Find the min and max L values a = min(L_values) # Min L value b = max(L_values) # Max L value # Get L, u, and v values at pixel (i,j) origL, u, v = luvImage[i, j] # Perform linear stretching of L in the range [0, 255] if (a != b): newL = (origL - a) * 255 // (b - a) else: newL = origL newLuvImage[i, j] = [newL, u, v] # Convert Luv image back to BGR image outputImage = cv2.cvtColor(newLuvImage, cv2.COLOR_Luv2BGR) cv2.imshow("output image", outputImage) # Saving the output cv2.imwrite(outputName, outputImage) # Wait for key to exit cv2.waitKey(0) cv2.destroyAllWindows()
Java
UTF-8
509
2.234375
2
[]
no_license
package service; import dao.RainManageDao; import entity.RainQuality; import java.util.List; public class RainMangerService { private RainManageDao rainManageDao = new RainManageDao(); public List<RainQuality>getAllInfo(){ return rainManageDao.getAllInfo(); } //新增雨量 public int addNewRainInfo(RainQuality rain){ return rainManageDao.addNewRainInfo(rain); } //删除 public int deleteById(String id){ return rainManageDao.deleteById(id); } }
Markdown
UTF-8
692
3.09375
3
[]
no_license
--- layout: post title: Depends on yourself date: 2017-02-02 22:22:22 +0800 --- 算下来,从12岁离家上初中到现在,将近20年都是一个人面对着一切,中考,高考,工作,北漂,就算已经结婚四年,依然如此,只不过从我一个人变成了我们两个的一个人。 这种一个人,在面对问题的时候,往往首先想到的是我自己能不能解决,不寄希望于别人。 这种一个人,让我特别害怕欠人情,比如借钱,比如麻烦朋友,尽管我知道他们并不在意,每次还是会打心底感谢他们的帮助。 这种一个人,一定程度上强迫自己变强,因为你只能依靠你自己。
Python
UTF-8
4,434
2.5625
3
[]
no_license
import numpy as np import bornagain as ba from bornagain import deg, angstrom, nm, nm2, kvector_t def get_sample(height=50): # Defining Materials material_1 = ba.MaterialBySLD("example10_Air", 0.0, 0.0) material_2 = ba.MaterialBySLD("example10_Particle", 108.29e-6, 0.0) material_3 = ba.MaterialBySLD("example10_Substrate", 19.92e-6, 0.0) #Ref: http://gisaxs.com/index.php/Refractive_index # Defining Layers layer_1 = ba.Layer(material_1) layer_2 = ba.Layer(material_3) # Defining Form Factors sphere_radius = 25.0*nm formFactor_1 = ba.FormFactorFullSphere(sphere_radius) formFactor_2 = ba.FormFactorFullSphere(sphere_radius) formFactor_3 = ba.FormFactorFullSphere(sphere_radius) # Defining Particles particle_1 = ba.Particle(material_2, formFactor_1) particle_1_position = kvector_t(-100.0*nm, -100.0*nm, 0.0*nm) particle_1.setPosition(particle_1_position) particle_2 = ba.Particle(material_2, formFactor_2) particle_2_position = kvector_t(-100.0*nm, 100.0*nm, 0.0*nm) particle_2.setPosition(particle_2_position) particle_3 = ba.Particle(material_2, formFactor_3) particle_3_position = kvector_t(0.0*nm, 0.0*nm, height*nm) particle_3.setPosition(particle_3_position) # Defining composition of particles at specific positions particleComposition_1 = ba.ParticleComposition() particleComposition_1.addParticle(particle_1) particleComposition_1.addParticle(particle_2) particleComposition_1.addParticle(particle_3) # Defining Interference Functions interference_1 = ba.InterferenceFunction2DLattice(200.0*nm, 1300.0*nm, 90.0*deg, 0.0*deg) #interference_1 = ba.InterferenceFunction2DLattice(1300.0*nm, 200.0*nm, 90.0*deg, 0.0*deg) interference_1_pdf = ba.FTDecayFunction2DCauchy(1000.0*nm, 1000.0*nm, 0.0*deg) interference_1.setDecayFunction(interference_1_pdf) # Defining Particle Layouts and adding Particles layout_1 = ba.ParticleLayout() layout_1.addParticle(particleComposition_1, 1.0) layout_1.setInterferenceFunction(interference_1) layout_1.setWeight(1) layout_1.setTotalParticleSurfaceDensity(3.84615384615e-06) # Adding layouts to layers layer_1.addLayout(layout_1) # Defining Multilayers multiLayer_1 = ba.MultiLayer() multiLayer_1.addLayer(layer_1) multiLayer_1.addLayer(layer_2) return multiLayer_1 def get_simulation(alpha_i=0.15): spherical_detector = False simulation = ba.GISASSimulation() simulation.setBeamParameters(0.1*nm, alpha_i*deg, 0.0*deg) simulation.setBeamIntensity(1.0e+08) distr_1 = ba.DistributionGaussian(0.1*nm, 0.01*nm) simulation.addParameterDistribution("*/Beam/Wavelength", distr_1, 25, 3.0, ba.RealLimits.positive()) simulation.getOptions().setMonteCarloIntegration(False, 50) if spherical_detector: simulation.setDetectorParameters(500, -1.0*deg, 1.0*deg, 500, 0.0*deg, 2.0*deg) else: qy_limit = 0.7#4487765659211788 qz_limit = 1.31 wavelength_nm = 0.1 side_bins = 200 distance_to_detector_mm = 7000.0 side_mm_x = 2. * distance_to_detector_mm * np.tan( 2. * np.arcsin(qy_limit/4./np.pi)) * wavelength_nm side_mm_y = distance_to_detector_mm * np.tan( 2. * np.arcsin(qz_limit/4./np.pi)) * wavelength_nm direct_beam_vertical_mm = - distance_to_detector_mm * np.tan(alpha_i*np.pi/180.0) detector = ba.RectangularDetector(side_bins, side_mm_x, side_bins, side_mm_y) detector.setPerpendicularToDirectBeam(distance_to_detector_mm, side_mm_x/2.0, 0.0)#direct_beam_vertical_mm) simulation.setDetector(detector) return simulation def run_simulation(alpha_i, height): sample = get_sample(height) simulation = get_simulation(alpha_i) simulation.setSample(sample) simulation.runSimulation() return simulation.result() if __name__ == '__main__': alpha_height_arr = [] for alpha_i in [0.15, 0.4]: height_arr = [] print("alpha_i = {}...".format(alpha_i)) for height in [0.0, 50.0, 200.0]: print("\t height = {}...".format(height)) title=f"$\\alpha_i = {alpha_i}^\\circ$, $ h = {height}$ nm" result = run_simulation(alpha_i, height) height_arr.append((result,title)) #ba.plot_simulation_result(result, title = title) alpha_height_arr.append(height_arr)