blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
281
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
6
116
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
313 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
18.2k
668M
star_events_count
int64
0
102k
fork_events_count
int64
0
38.2k
gha_license_id
stringclasses
17 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
107 values
src_encoding
stringclasses
20 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
4
6.02M
extension
stringclasses
78 values
content
stringlengths
2
6.02M
authors
listlengths
1
1
author
stringlengths
0
175
ff580552aad775843c2df38fbad72481e81d8f4b
55c5c9e34a672bb148f2b50e610ca2e92ff415c1
/test_main.py
ec304cf2473a62d74df6cf2280552bc038c836ee
[]
no_license
HisashiMiura/duct_type_central_hc_system
8b7d164f8e8c9551a9649a1add5f207dd83f01c5
905588f4917847e2209dbd0ffb4cdbaca976f623
refs/heads/master
2022-02-13T17:13:24.161174
2019-09-02T05:34:22
2019-09-02T05:34:22
178,965,355
0
0
null
null
null
null
UTF-8
Python
false
false
708
py
import unittest import numpy as np import pandas as pd import analyze_control as ac class TestMain(unittest.TestCase): def test_total_result(self): CASE = 6 result = ac.get_main_value(CASE) t = result.get_time_value_dict() df_t = pd.DataFrame(t) self.assertAlmostEqual(6.253757008549898, df_t.heating_load_room1[0]) self.assertAlmostEqual(17.958762933266666, df_t.output_of_heat_source_heating[0]) self.assertAlmostEqual(1.07990470028857, df_t.output_of_heat_source_sensible_cooling[4798]) self.assertAlmostEqual(1.1893886188521219, df_t.output_of_heat_source_latent_cooling[4798]) if __name__ == '__main__': unittest.main()
[ "hisashi.office@gmail.com" ]
hisashi.office@gmail.com
161236073ff6140bf341098a3f9c576ae68325b0
1d6af07e4e9a779019bf509a8ff90358cb7b1337
/regex.py
c4dd296f6486a5e0b2f4e76f72be26af12a7850b
[]
no_license
nghiahsgs/practice-typing-10-fingers-mini-program-python
eace206f549f9c16e2b1d520f4e5ef083e9477b4
dffe4a7a53830deb157040d18b0fbbed2c4c6bac
refs/heads/master
2020-09-27T05:52:10.405147
2019-12-29T04:13:57
2019-12-29T04:13:57
226,445,194
1
0
null
null
null
null
UTF-8
Python
false
false
24,299
py
import re regex1=re.compile(r'"(.*)"') regex1=re.compile(r'\d. (.*)') regex1=re.compile(r'([A-Z](.*?))\.') regex1=re.compile(r'“(.*?)”') ndung=''' 1. Your limitation—it’s only your imagination. 2. Push yourself, because no one else is going to do it for you. 3. Sometimes later becomes never. Do it now. 4. Great things never come from comfort zones. 5. Dream it. Wish it. Do it. 6. Success doesn’t just find you. You have to go out and get it. 7. The harder you work for something, the greater you’ll feel when you achieve it. 8. Dream bigger. Do bigger. 9. Don’t stop when you’re tired. Stop when you’re done. 10. Wake up with determination. Go to bed with satisfaction. 11. Do something today that your future self will thank you for. 12. Little things make big days. 13. It’s going to be hard, but hard does not mean impossible. 14. Don’t wait for opportunity. Create it. 15. Sometimes we’re tested not to show our weaknesses, but to discover our strengths. 16. The key to success is to focus on goals, not obstacles. 17. Dream it. Believe it. Build it. ''' ndung=''' 1. "If you want to achieve greatness stop asking for permission." --Anonymous 2. "Things work out best for those who make the best of how things work out." --John Wooden 3. "To live a creative life, we must lose our fear of being wrong." --Anonymous 4. "If you are not willing to risk the usual you will have to settle for the ordinary." --Jim Rohn 5. "Trust because you are willing to accept the risk, not because it's safe or certain." --Anonymous 6. "Take up one idea. Make that one idea your life--think of it, dream of it, live on that idea. Let the brain, muscles, nerves, every part of your body, be full of that idea, and just leave every other idea alone. This is the way to success." --Swami Vivekananda 7. "All our dreams can come true if we have the courage to pursue them." --Walt Disney 8. "Good things come to people who wait, but better things come to those who go out and get them." --Anonymous 9. "If you do what you always did, you will get what you always got." --Anonymous 10. "Success is walking from failure to failure with no loss of enthusiasm." --Winston Churchill 11. "Just when the caterpillar thought the world was ending, he turned into a butterfly." --Proverb 12. "Successful entrepreneurs are givers and not takers of positive energy." --Anonymous 13. "Whenever you see a successful person you only see the public glories, never the private sacrifices to reach them." --Vaibhav Shah 14. "Opportunities don't happen, you create them." --Chris Grosser 15. "Try not to become a person of success, but rather try to become a person of value." --Albert Einstein 16. "Great minds discuss ideas; average minds discuss events; small minds discuss people." --Eleanor Roosevelt 17. "I have not failed. I've just found 10,000 ways that won't work." --Thomas A. Edison 18. "If you don't value your time, neither will others. Stop giving away your time and talents--start charging for it." --Kim Garst 19. "A successful man is one who can lay a firm foundation with the bricks others have thrown at him." --David Brinkley 20. "No one can make you feel inferior without your consent." --Eleanor Roosevelt 21. "The whole secret of a successful life is to find out what is one's destiny to do, and then do it." --Henry Ford 22. "If you're going through hell keep going." --Winston Churchill 23. "The ones who are crazy enough to think they can change the world, are the ones who do." --Anonymous 24. "Don't raise your voice, improve your argument." --Anonymous 25. "What seems to us as bitter trials are often blessings in disguise." --Oscar Wilde 26. "The meaning of life is to find your gift. The purpose of life is to give it away." --Anonymous 27. "The distance between insanity and genius is measured only by success." --Bruce Feirstein 28. "When you stop chasing the wrong things, you give the right things a chance to catch you." --Lolly Daskal 29. "I believe that the only courage anybody ever needs is the courage to follow your own dreams." --Oprah Winfrey 30. "No masterpiece was ever created by a lazy artist." --Anonymous 31. "Happiness is a butterfly, which when pursued, is always beyond your grasp, but which, if you will sit down quietly, may alight upon you." --Nathaniel Hawthorne 32. "If you can't explain it simply, you don't understand it well enough." --Albert Einstein 33. "Blessed are those who can give without remembering and take without forgetting." --Anonymous 34. "Do one thing every day that scares you." --Anonymous 35. "What's the point of being alive if you don't at least try to do something remarkable." --Anonymous 36. "Life is not about finding yourself. Life is about creating yourself." --Lolly Daskal 37. "Nothing in the world is more common than unsuccessful people with talent." --Anonymous 38. "Knowledge is being aware of what you can do. Wisdom is knowing when not to do it." --Anonymous 39. "Your problem isn't the problem. Your reaction is the problem." --Anonymous 40. "You can do anything, but not everything. --Anonymous 41. "Innovation distinguishes between a leader and a follower." --Steve Jobs 42. "There are two types of people who will tell you that you cannot make a difference in this world: those who are afraid to try and those who are afraid you will succeed." --Ray Goforth 43. "Thinking should become your capital asset, no matter whatever ups and downs you come across in your life." --A.P.J. Abdul Kalam 44. "I find that the harder I work, the more luck I seem to have." --Thomas Jefferson 45. "The starting point of all achievement is desire." --Napoleon Hill 46. "Success is the sum of small efforts, repeated day-in and day-out." --Robert Collier 47. "If you want to achieve excellence, you can get there today. As of this second, quit doing less-than-excellent work." --Thomas J. Watson 48. "All progress takes place outside the comfort zone." --Michael John Bobak 49. "You may only succeed if you desire succeeding; you may only fail if you do not mind failing." --Philippos 50. "Courage is resistance to fear, mastery of fear--not absence of fear." --Mark Twain 51. "Only put off until tomorrow what you are willing to die having left undone." --Pablo Picasso 52. "People often say that motivation doesn't last. Well, neither does bathing--that's why we recommend it daily." --Zig Ziglar 53. "We become what we think about most of the time, and that's the strangest secret." --Earl Nightingale 54. "The only place where success comes before work is in the dictionary." --Vidal Sassoon 55. "Too many of us are not living our dreams because we are living our fears. " --Les Brown 56. "I find that when you have a real interest in life and a curious life, that sleep is not the most important thing." --Martha Stewart 57. "It's not what you look at that matters, it's what you see." --Anonymous 58. "The road to success and the road to failure are almost exactly the same." --Colin R. Davis 59. "The function of leadership is to produce more leaders, not more followers." --Ralph Nader 60. "Success is liking yourself, liking what you do, and liking how you do it." --Maya Angelou 61. "As we look ahead into the next century, leaders will be those who empower others." --Bill Gates 62. "A real entrepreneur is somebody who has no safety net underneath them." --Henry Kravis 63. "The first step toward success is taken when you refuse to be a captive of the environment in which you first find yourself." --Mark Caine 64. "People who succeed have momentum. The more they succeed, the more they want to succeed, and the more they find a way to succeed. Similarly, when someone is failing, the tendency is to get on a downward spiral that can even become a self-fulfilling prophecy." --Tony Robbins 65. "When I dare to be powerful, to use my strength in the service of my vision, then it becomes less and less important whether I am afraid." --Audre Lorde 66. "Whenever you find yourself on the side of the majority, it is time to pause and reflect." --Mark Twain 67. "The successful warrior is the average man, with laser-like focus." --Bruce Lee 68. "There is no traffic jam along the extra mile." --Roger Staubach 69. "Develop success from failures. Discouragement and failure are two of the surest stepping stones to success." --Dale Carnegie 70. "If you don't design your own life plan, chances are you'll fall into someone else's plan. And guess what they have planned for you? Not much." --Jim Rohn 71. "If you genuinely want something, don't wait for it--teach yourself to be impatient." --Gurbaksh Chahal 72. "Don't let the fear of losing be greater than the excitement of winning." --Robert Kiyosaki 73. "If you want to make a permanent change, stop focusing on the size of your problems and start focusing on the size of you!" --T. Harv Eker 74. "You can't connect the dots looking forward; you can only connect them looking backwards. So you have to trust that the dots will somehow connect in your future. You have to trust in something--your gut, destiny, life, karma, whatever. This approach has never let me down, and it has made all the difference in my life." --Steve Jobs 75. "Two roads diverged in a wood and I  took the one less traveled by, and that made all the difference." --Robert Frost 76. "The number one reason people fail in life is because they listen to their friends, family, and neighbors." --Napoleon Hill 77. "The reason most people never reach their goals is that they don't define them, or ever seriously consider them as believable or achievable. Winners can tell you where they are going, what they plan to do along the way, and who will be sharing the adventure with them." --Denis Waitley 78. "In my experience, there is only one motivation, and that is desire. No reasons or principle contain it or stand against it." --Jane Smiley 79. "Success does not consist in never making mistakes but in never making the same one a second time." --George Bernard Shaw 80. "I don't want to get to the end of my life and find that I lived just the length of it. I want to have lived the width of it as well." --Diane Ackerman 81. "You must expect great things of yourself before you can do them." --Michael Jordan 82. "Motivation is what gets you started. Habit is what keeps you going." --Jim Ryun 83. "People rarely succeed unless they have fun in what they are doing." --Dale Carnegie 84. "There is no chance, no destiny, no fate, that can hinder or control the firm resolve of a determined soul." --Ella Wheeler Wilcox 85. "Our greatest fear should not be of failure but of succeeding at things in life that don't really matter." --Francis Chan 86. "You've got to get up every morning with determination if you're going to go to bed with satisfaction." --George Lorimer 87. "A goal is not always meant to be reached; it often serves simply as something to aim at." -- Bruce Lee 88. "Success is ... knowing your purpose in life, growing to reach your maximum potential, and sowing seeds that benefit others." --John C. Maxwell 89. "Be miserable. Or motivate yourself. Whatever has to be done, it's always your choice." --Wayne Dyer 90. "To accomplish great things, we must not only act, but also dream, not only plan, but also believe." --Anatole France 91. "Most of the important things in the world have been accomplished by people who have kept on trying when there seemed to be no help at all." --Dale Carnegie 92. "You measure the size of the accomplishment by the obstacles you had to overcome to reach your goals." --Booker T. Washington 93. "Real difficulties can be overcome; it is only the imaginary ones that are unconquerable." --Theodore N. Vail 94. "It is better to fail in originality than to succeed in imitation." --Herman Melville 95. "What would you do if you weren't afraid." --Spencer Johnson 96. "Little minds are tamed and subdued by misfortune; but great minds rise above it." --Washington Irving 97. "Failure is the condiment that gives success its flavor." --Truman Capote 98. "Don't let what you cannot do interfere with what you can do." --John R. Wooden 99. "You may have to fight a battle more than once to win it." --Margaret Thatcher 100. "A man can be as great as he wants to be. If you believe in yourself and have the courage, the determination, the dedication, the competitive drive and if you are willing to sacrifice the little things in life and pay the price for the things that are worthwhile, it can be done." --Vince Lombardi''' ndung=''' Everything you’ve ever wanted is on the other side of fear. — George Addair Pain is temporary. Quitting lasts forever. – Lance Armstrong The pain you feel today will be the strength you feel tomorrow. – Unknown We must embrace pain and burn it as fuel for our journey. – Kenji Miyazawa A problem is a chance for you to do your best. – Duke Ellington Hard times don’t create heroes. It is during the hard times when the ‘hero’ within us is revealed. – Bob Riley Whatever is worrying you right now, forget about it. Take a deep breath, stay positive and know that things will get better. – Unknown It’s not about perfect. It’s about effort. – Jillian Michaels Believe you can and you’re halfway there. – Theodore Roosevelt Challenges are what make life interesting. Overcoming them is what makes them meaningful. You are so much more than what you are going through. – John Tew Passion first and everything will fall into place. – Holly Holm Difficult roads always lead to beautiful destinations. – Zig Ziglar Staying positive does not mean that things will turn out okay. Rather it is knowing that you will be okay no matter how things turn out. – Unknown Goals may give focus, but dreams give power. – John Maxwell Don’t wish it were easier. Wish you were better. ― Jim Rohn Your mind is a powerful thing. When you fill it with positive thoughts, your life will start to change. Hustle until you no longer have to introduce yourself. Success is what happens after you have survived all of your disappointments. You don’t always get what you wish for. But you always get what you work for. You don’t find will power, you create it. Once you choose hope, anything’s possible. – Christopher Reeve Push yourself because no one else is going to do it. You cannot fail at being yourself. – Wayne Dyer Don’t wait for opportunity. Create it. You are the only one who can limit your greatness. – Unknown The first and greatest victory is to conquer self. – Plato Results happen over time, not overnight. Work hard, stay consistent, and be patient. With confidence you have won before you have started. – Marcus Garvey Success is what comes after you stop making excuses. – Luis Galarza You don’t want to look back and know you could have done better. The moment you doubt whether you can fly, you cease for ever to be able to do it. – J.M. Barrie Be so good they can’t ignore you. – Steve Martin You will never always be motivated. You have to learn to be disciplined. Believe in yourself! Have faith in your abilities! Without a humble but reasonable confidence in your own powers you cannot be successful or happy. – Norman Vincent Peale When you know what you want, and want it bad enough, you’ll find a way to get it. – Jim Rohn The best way to gain self-confidence is to do what you are afraid to do. – Swati Sharma Motivation is what gets you started. Habit is what keeps you going. – Jim Rohn Never stop trying. Never stop believing. Never give up. Your day will come. – Unknown Results happen over time, not overnight. Work hard, stay consistent, and be patient. – Unknown Our greatest glory is not in never falling, but in rising every time we fall. — Confucius Success is what happens after you have survived all of your disappointments. – Unknown Don’t try to be perfect. Just try to be better than you were yesterday. – Unknown Start where you are. Use what you have. Do what you can. – Arthur Ashe Don’t stop until you’re proud. Strength does not come from physical capacity. It comes from an indomitable will. – Mahatma Gandhi I’m not telling you it is going to be easy, I’m telling you it’s going to be worth it. – Art Williams If you want it, you’ll find a way. If you don’t, you’ll find an excuse. Perseverance is the hard work you do after you get tired of doing the hard work you already did. – Newt Gingrich It is during our darkest moments that we must focus to see the light. — Aristotle Onassis Perfection is not attainable, but if we chase perfection we can catch excellence. — Vince Lombardi We may encounter many defeats but we must not be defeated. – Maya Angelou Strength doesn’t come from what you can do. It comes from overcoming the things you once thought you couldn’t. – Rikki Rogers He who is not courageous enough to take risks will accomplish nothing in life. – Muhammad Ali We don’t develop courage by being happy every day. We develop it by surviving difficult times and challenging adversity. – Barbara De Angelis When you fear your struggles, your struggles consume you. When you face your struggles, you overcome them. I learned that courage was not the absence of fear, but the triumph over it. The brave man is not he who does not feel afraid, but he who conquers that fear. – Nelson Mandela Keep going. Everything you need will come to you at the perfect time. Set a goal so big that you can’t achieve it until you grow into the person who can. – Unknown All our dreams can come true, if we have the courage to pursue them. – Walt Disney The path to success is to take massive, determined action. – Tony Robbins The only person you are destined to become is the person you decide to be. —Ralph Waldo Emerson If you get tired, learn to rest, not quit. Pessimism leads to weakness, optimism to power. – William James ''' ndung=''' 1) “The Way Get Started Is To Quit Talking And Begin Doing.” – Walt Disney 2) “The Pessimist Sees Difficulty In Every Opportunity. The Optimist Sees Opportunity In Every Difficulty.” – Winston Churchill 3) “Don’t Let Yesterday Take Up Too Much Of Today.” – Will Rogers 4) “You Learn More From Failure Than From Success. Don’t Let It Stop You. Failure Builds Character.” – Unknown 5) “It’s Not Whether You Get Knocked Down, It’s Whether You Get Up.” – Inspirational Quote By Vince Lombardi 6) “If You Are Working On Something That You Really Care About, You Don’t Have To Be Pushed. The Vision Pulls You.” – Steve Jobs 7) “People Who Are Crazy Enough To Think They Can Change The World, Are The Ones Who Do.” – Rob Siltanen 8) “Failure Will Never Overtake Me If My Determination To Succeed Is Strong Enough.” – Og Mandino 9) “Entrepreneurs Are Great At Dealing With Uncertainty And Also Very Good At Minimizing Risk. That’s The Classic Entrepreneur.” – Mohnish Pabrai 10) “We May Encounter Many Defeats But We Must Not Be Defeated.” – Maya Angelou 11) “Knowing Is Not Enough; We Must Apply. Wishing Is Not Enough; We Must Do.” – Johann Wolfgang Von Goethe 12) “Imagine Your Life Is Perfect In Every Respect; What Would It Look Like?” – Brian Tracy 13) “We Generate Fears While We Sit. We Overcome Them By Action.” – Dr. Henry Link 14) “Whether You Think You Can Or Think You Can’t, You’re Right.” – Quote By Henry Ford 15) “Security Is Mostly A Superstition. Life Is Either A Daring Adventure Or Nothing.” – Life Quote By Helen Keller 16) “The Man Who Has Confidence In Himself Gains The Confidence Of Others.” – Hasidic Proverb 17) “The Only Limit To Our Realization Of Tomorrow Will Be Our Doubts Of Today.” – Motivational Quote By Franklin D. Roosevelt 18) “Creativity Is Intelligence Having Fun.” – Albert Einstein 19) “What You Lack In Talent Can Be Made Up With Desire, Hustle And Giving 110% All The Time.” – Don Zimmer 20) “Do What You Can With All You Have, Wherever You Are.” – Theodore Roosevelt 21) “Develop An ‘Attitude Of Gratitude’. Say Thank You To Everyone You Meet For Everything They Do For You.” – Encouraging Quote By Brian Tracy 22) “You Are Never Too Old To Set Another Goal Or To Dream A New Dream.” – C.S. Lewis 23) “To See What Is Right And Not Do It Is A Lack Of Courage.” – Confucius 24) “Reading Is To The Mind, As Exercise Is To The Body.” – Brian Tracy 25) “Fake It Until You Make It! Act As If You Had All The Confidence You Require Until It Becomes Your Reality.” – Brian Tracy 26) “The Future Belongs To The Competent. Get Good, Get Better, Be The Best!” – Success Quote By Brian Tracy 27) “For Every Reason It’s Not Possible, There Are Hundreds Of People Who Have Faced The Same Circumstances And Succeeded.” – Jack Canfield 28) “Things Work Out Best For Those Who Make The Best Of How Things Work Out.” – Positive Quote By John Wooden 29) “A Room Without Books Is Like A Body Without A Soul.” – Marcus Tullius Cicero 30) “I Think Goals Should Never Be Easy, They Should Force You To Work, Even If They Are Uncomfortable At The Time.” – Michael Phelps 31) “One Of The Lessons That I Grew Up With Was To Always Stay True To Yourself And Never Let What Somebody Else Says Distract You From Your Goals.” – Michelle Obama 32) “Today’s Accomplishments Were Yesterday’s Impossibilities.” – Robert H. Schuller 33) “The Only Way To Do Great Work Is To Love What You Do. If You Haven’t Found It Yet, Keep Looking. Don’t Settle.” – Steve Jobs 34) “You Don’t Have To Be Great To Start, But You Have To Start To Be Great.” – Zig Ziglar 35)  “A Clear Vision, Backed By Definite Plans, Gives You A Tremendous Feeling Of Confidence And Personal Power.” – Brian Tracy 36) “There Are No Limits To What You Can Accomplish, Except The Limits You Place On Your Own Thinking.” – Brian Tracy 20 Success Quotes For Inspirational Leaders 37) “Integrity Is The Most Valuable And Respected Quality Of Leadership. Always Keep Your Word.” 38) “Leadership Is The Ability To Get Extraordinary Achievement From Ordinary People” 39) “Leaders Set High Standards. Refuse To Tolerate Mediocrity Or Poor Performance” 40) “Clarity Is The Key To Effective Leadership. What Are Your Goals?” 41) “The Best Leaders Have A High Consideration Factor. They Really Care About Their People” 42) “Leaders Think And Talk About The Solutions. Followers Think And Talk About The Problems.” 43) “The Key Responsibility Of Leadership Is To Think About The Future. No One Else Can Do It For You.” 44) “The Effective Leader Recognizes That They Are More Dependent On Their People Than They Are On Them. Walk Softly.” 45) “Leaders Never Use The Word Failure. They Look Upon Setbacks As Learning Experiences.” 46) “Practice Golden Rule Management In Everything You Do. Manage Others The Way You Would Like To Be Managed.” 47) “Superior Leaders Are Willing To Admit A Mistake And Cut Their Losses. Be Willing To Admit That You’ve Changed Your Mind. Don’t Persist When The Original Decision Turns Out To Be A Poor One.” 48) “Leaders Are Anticipatory Thinkers. They Consider All Consequences Of Their Behaviors Before They Act.” 49) “The True Test Of Leadership Is How Well You Function In A Crisis.” 50) “Leaders Concentrate Single-Mindedly On One Thing– The Most Important Thing, And They Stay At It Until It’s Complete.” 51) “The Three ‘C’s’ Of Leadership Are Consideration, Caring, And Courtesy. Be Polite To Everyone.” 52) “Respect Is The Key Determinant Of High-Performance Leadership. How Much People Respect You Determines How Well They Perform.” 53) “Leadership Is More Who You Are Than What You Do.” 54) “Entrepreneurial Leadership Requires The Ability To Move Quickly When Opportunity Presents Itself.” 55) “Leaders Are Innovative, Entrepreneurial, And Future-Oriented. They Focus On Getting The Job Done.” 56) “Leaders Are Never Satisfied; They Continually Strive To Be Better.” ''' kq=regex1.findall(ndung) for line in kq: print(line) #print(line[0])
[ "Hoangphohieu1@gmai.com" ]
Hoangphohieu1@gmai.com
bf7843e2014ca20cec8ef555db4f17883fb03c40
a4add3ee9288ea8664d1770ac91eafcda206b0aa
/format2.py
115a32d135f7f807601f2e366931ab67a08e6ec9
[]
no_license
re-born/stc
a54b417c0fc52aa8d56c6b35ec48d2d28519e0ae
a4acdcc887494460911db58b0a4ac6a965aeb216
refs/heads/master
2020-04-10T14:52:42.386927
2016-04-29T05:38:42
2016-04-29T05:38:42
51,678,665
0
0
null
2016-04-30T15:49:30
2016-02-14T03:53:17
TeX
UTF-8
Python
false
false
307
py
# -*- coding: utf-8 -*- import sys if __name__ == "__main__": filename = sys.argv[1] for line in open(filename, 'r'): line = line.replace('(', '').replace(')', '').replace( 'u', '').replace('\'', '').replace('\n', '') array = line.split() print ' '.join(array)
[ "snoopies.drum@gmail.com" ]
snoopies.drum@gmail.com
507c4a7a07a6e91ebb47e5b09d5d925116439c7b
a91750b9bcc6aaeff8aae48f0607bf6a5d41d386
/Project/catkin_ws/src/jaco_trajectory/script/jaco_control.py
ff9f24bb9d1a0477e91c721420899e7dd974830c
[ "BSD-3-Clause" ]
permissive
lydiarong/2019_Numerical_Analysis
6c053fd1306b01c3b5f8bf563b8d4a2643aca60d
b21f03a44e87ba14ce4d86ba77549e193b1801d2
refs/heads/master
2020-12-12T11:59:25.684819
2020-01-15T18:16:14
2020-01-15T18:16:14
234,120,192
1
1
null
null
null
null
UTF-8
Python
false
false
10,451
py
#! /usr/bin/env python """Takes trajectory data from xyz and uses inverse kinematics algorithms to calculate the best state. """ #rosrun jaco_trajectory jaco_control.py from trajectory_msgs.msg import JointTrajectory from trajectory_msgs.msg import JointTrajectoryPoint import rospy import numpy from scipy.linalg import pinv import time import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from math import pi from math import cos from math import sin from sympy import * from robot_functions import * # Built functions for jaco model from time import strftime, sleep def moveJoint (jointcmds): topic_name = '/' + 'j2n6s300' + '/effort_joint_trajectory_controller/command' pub = rospy.Publisher(topic_name, JointTrajectory, queue_size=1) jointCmd = JointTrajectory() point = JointTrajectoryPoint() jointCmd.header.stamp = rospy.Time.now() + rospy.Duration.from_sec(0.0); point.time_from_start = rospy.Duration.from_sec(5.0) for i in range(0, 6): jointCmd.joint_names.append('j2n6s300' +'_joint_'+str(i+1)) point.positions.append(jointcmds[i]) point.velocities.append(0) point.accelerations.append(0) point.effort.append(0) jointCmd.points.append(point) rate = rospy.Rate(100) count = 0 while (count < 50): pub.publish(jointCmd) count = count + 1 rate.sleep() def moveFingers (jointcmds): topic_name = '/' + 'j2n6s300' + '/effort_finger_trajectory_controller/command' pub = rospy.Publisher(topic_name, JointTrajectory, queue_size=1) jointCmd = JointTrajectory() point = JointTrajectoryPoint() jointCmd.header.stamp = rospy.Time.now() + rospy.Duration.from_sec(0.0); point.time_from_start = rospy.Duration.from_sec(5.0) for i in range(0, 3): jointCmd.joint_names.append('j2n6s300' +'_joint_finger_'+str(i+1)) point.positions.append(jointcmds[i]) point.velocities.append(0) point.accelerations.append(0) point.effort.append(0) jointCmd.points.append(point) rate = rospy.Rate(100) count = 0 while (count < 500): pub.publish(jointCmd) count = count + 1 rate.sleep() if __name__ == '__main__': try: ti = time.time() rospy.init_node('move_robot_using_trajectory_msg') # Allow gazebo to launch rospy.sleep(1) ######################### EDIT THIS SECTION ############################### # Parameters numPts = 2 # Discretized path (Choose number of points) step = 0.1 # Step size error = 0.000001 # Error between state and desired state (theshold value, in meters) # Initial state q10 = 0.0 q20 = 2.9 q30 = 1.3 q40 = 4.2 q50 = 1.4 q60 = 0.0 # Final state xf = -0.2 yf = 0.6 zf = 0.4 ########################################################################### # Boundary conditions (DON'T WORRY ABOUT THESE, and DON'T UNCOMMENT) init_q = Matrix([[-q10], [q20-pi/2], [q30+pi/2], [q40], [q50-pi], [q60+pi/2]]) # Initial position _, init_X = systemKinematics(init_q) final_X = Matrix([[xf],[yf],[zf]]) ######################### EDIT THIS SECTION ############################### # Discretize path (change this to change path shape, default is line) xPath = numpy.linspace(float(init_X[0]), float(final_X[0]), num=numPts) yPath = numpy.linspace(float(init_X[1]), float(final_X[1]), num=numPts) zPath = numpy.linspace(float(init_X[2]), float(final_X[2]), num=numPts) ########################################################################### # Move robot to initial state moveJoint([q10,q20,q30,q40,q50,q60]) moveFingers([1.3,1.3,1.3]) # Initialize variables delta_X = Matrix([[1000],[1000],[1000]]) X = [] Y = [] Z = [] # Matrix calculatations dynMatrix,_ = systemKinematics(init_q) row0 = dynMatrix.row(0) row1 = dynMatrix.row(1) row2 = dynMatrix.row(2) DynMatrix = Matrix([[row0],[row1],[row2]]) J_x = robotJacobian(DynMatrix[0]) J_y = robotJacobian(DynMatrix[1]) J_z = robotJacobian(DynMatrix[2]) currentTime = strftime('%m_%d_%H_%M_%S') Output = open ('Output-' + currentTime, 'w') Output.write(str(init_q)) Output.write('Initial q state:'+str(init_q)+'\n') Output.write('Initial x state:'+str(init_X)+'\n') Output.flush() # Connect all points in mesh path (START LOOP AT 1, NOT 0) for i in range(1,numPts): path_X = Matrix([[xPath[i]]]) path_Y = Matrix([[yPath[i]]]) path_Z = Matrix([[zPath[i]]]) print(i) # print "init_q:" # print init_q # print init_X _, init_X = systemKinematics(init_q) delta_X = path_X - Matrix([[init_X[0]]]) delta_Y = path_Y - Matrix([[init_X[1]]]) delta_Z = path_Z - Matrix([[init_X[2]]]) F=(path_X-DynMatrix[0])**2 HJ_x = robotJacobian(F) H_x = robotHessian(F) print 'start' HJ_x_type=robotJacobian(path_X-DynMatrix[0]) H_x_type=robotHessian_type(HJ_x_type) print 'end' print H_x.shape ,HJ_x.shape,H_x_type.shape G=((Matrix([[init_X[1]]])-DynMatrix[1])**2) G_J=robotJacobian(G) G_H=robotHessian(G) G_H_type=robotHessian_type(robotJacobian((Matrix([[init_X[1]]])-DynMatrix[1]))) print G_J.shape ,G_H.shape,G_H_type.shape # print evalJacobian(G,init_q) lamba=symbols('lamba') L=F+G*lamba L_J=robotJacobian(L) temp=Matrix(H_x_type+lamba.transpose()*G_H_type) Z1=Matrix(H_x_type+lamba.transpose()*G_H_type).col_insert(7,G_J.transpose()) Z2=Matrix(G_J).col_insert(7,zeros(1,1)) Z3=Z1.row_insert(7,Z2) B1=Matrix([-L_J.transpose()]).row_insert(7,Matrix([-G])) print L_J.shape ,Z3.shape,B1.shape delta_v,delta_v1,delta_v2,delta_v3,delta_v4,delta_v5,delta_v6=symbols('delta_v delta_v1 delta_v2 delta_v3 delta_v4 delta_v5 delta_v6') delta_v=Matrix([[delta_v1],[delta_v2],[delta_v3],[delta_v4],[delta_v5],[delta_v6]]) cond=abs(HJ_x*delta_v)+abs(lamba*G) itertion = 0 new_lamba=0.1 new_delta_v=Matrix([[0.1],[0.1],[0.1],[0.1],[0.1],[0.1]]) # print evalCond1(Z3,init_q,new_lamba),evalCond1(temp,init_q,new_lamba) # print evalCond(cond,init_q,new_lamba,new_delta_v)[0] # print 'Param start' # print evalCond1(temp,init_q,new_lamba) # print evalJacobian(G_J.transpose(),init_q) # print evalJacobian(G_J,init_q) # print evalCond1(-L_J.transpose(),init_q,new_lamba) # print evalJacobian(G,init_q) # useful_J=evalCond1(Z3,init_q,new_lamba) # useful_H=evalCond1(B1,init_q,new_lamba) # print useful_J,useful_H # KKT=inverseKinematics_type(useful_J,step,useful_H) # print KKT # new_delta_v=Matrix(KKT[0:6]) # init_q = init_q + step*new_delta_v # print new_delta_v # print init_q # print evalJacobian(G,init_q) # print 'Param end' while evalCond(cond,init_q,new_lamba,new_delta_v)[0]>error: # print evalCond(cond,init_q,new_lamba,new_delta_v)[0] if evalCond(cond,init_q,new_lamba,new_delta_v)[0]>error: _, init_X = systemKinematics(init_q) delta_X = path_X - Matrix([[init_X[0]]])#,[init_X[1]],[init_X[2]] # print(Abs(delta_X.norm())) useful_J = evalCond1(Z3,init_q,new_lamba) useful_H = evalCond1(B1,init_q,new_lamba) KKT=inverseKinematics_type(useful_J,step,useful_H) print KKT.shape new_delta_v=Matrix(KKT[0:6]) new_lamba=new_lamba+step*(KKT[6]-new_lamba) print init_q.shape,new_delta_v.shape init_q = init_q + step*new_delta_v print evalJacobian(G_J,init_q)*new_delta_v+evalJacobian(G,init_q) # if (Abs(delta_X.norm()) > error): # _, init_X = systemKinematics(init_q) # delta_X = path_X - Matrix([[init_X[0]]])#,[init_X[1]],[init_X[2]] # # print(Abs(delta_X.norm())) # # Linearize dynamics matrix # useful_J = evalJacobian(HJ_x,init_q) # useful_H = evalHessian(H_x,init_q) # # Calculate joint state change and new state # # delta_q = inverseKinematics_type(useful_J,step,delta_X) # # init_q = init_q + step*delta_q # delta_q=inverseKinematics_newton(useful_H,step,useful_J) # init_q = init_q - step*delta_q # Convert back from DH angles to JACO angles # moveJoint([-init_q[0], init_q[1]+pi/2, init_q[2]-pi/2, init_q[3], init_q[4]+pi, init_q[5]-pi/2]) # if (Abs(delta_X.norm()) > error): # _, init_X = systemKinematics(init_q) # delta_X = path_X - Matrix([[init_X[0]]])#,[init_X[1]],[init_X[2]] # # print(Abs(delta_X.norm())) # # Linearize dynamics matrix # useful_J = evalJacobian(J_x,init_q) # useful_H = evalHessian(H_x,init_q) # # Calculate joint state change and new state # delta_q = inverseKinematics_type(useful_J,step,delta_X) # init_q = init_q + step*delta_q # if (Abs(delta_Y.norm()) > error): # _, init_X = systemKinematics(init_q) # delta_Y = path_Y - Matrix([[init_X[1]]])#,[init_X[1]],[init_X[2]] # # print(Abs(delta_X.norm())) # # Linearize dynamics matrix # useful_J = evalJacobian(J_y,init_q) # # Calculate joint state change and new state # delta_q = inverseKinematics_type(useful_J,step,delta_Y) # init_q = init_q + step*delta_q # Convert back from DH angles to JACO angles # moveJoint([-init_q[0], init_q[1]+pi/2, init_q[2]-pi/2, init_q[3], init_q[4]+pi, init_q[5]-pi/2]) # if (Abs(delta_Z.norm()) > error): # _, init_X = systemKinematics(init_q) # delta_Z = path_Z - Matrix([[init_X[2]]])#,[init_X[1]],[init_X[2]] # # print(Abs(delta_X.norm())) # # Linearize dynamics matrix # useful_J = evalJacobian(J_z,init_q) # # Calculate joint state change and new state # delta_q = inverseKinematics_type(useful_J,step,delta_Z) # init_q = init_q + step*delta_q # Convert back from DH angles to JACO angles # moveJoint([-init_q[0], init_q[1]+pi/2, init_q[2]-pi/2, init_q[3], init_q[4]+pi, init_q[5]-pi/2]) # # Convert back from DH angles to JACO angles moveJoint([-init_q[0], init_q[1]+pi/2, init_q[2]-pi/2, init_q[3], init_q[4]+pi, init_q[5]-pi/2]) print init_X itertion = itertion + 1 # Trajectory plotting X.append(init_X[0]) Y.append(init_X[1]) Z.append(init_X[2]) Output.write('Final X:'+str(X)+'\n') Output.write('Final Y:'+str(Y)+'\n') Output.write('Final Z:'+str(Z)+'\n') Output.write('Final q state:'+str(init_q)+'\n') Output.write('Final x state:'+str(init_X)+'\n') elapsed = time.time() - ti Output.write('time:'+str(elapsed)+'\n') Output.write('itertion:'+str(itertion)+'\n') Output.flush() print("time",elapsed) print("itertion", itertion) print init_q fig = plt.figure() ax = fig.gca(projection='3d') ax.plot(X, Y, Z, label='traveled') ax.plot(xPath, yPath, zPath, label='path') ax.legend() plt.show() except rospy.ROSInterruptException: print ("program interrupted before completion")
[ "rongchy@shanghaitech.edu.cn" ]
rongchy@shanghaitech.edu.cn
f5a1dfa890eb4a9d7d3f23ddfeb0103a10fec395
8e14b3fecf89f38826c9d75e11e4fbc5319f9100
/tensorflow_io/core/python/experimental/kafka_batch_io_dataset_ops.py
bd18d120e952e05dbed98d1fb949b9a6093c19cd
[ "Apache-2.0" ]
permissive
djl11/io
0096f1aaaa3bc1c78baf4bc0e7b456f2c6f8ba1b
44e0c9e116c681d0479ea2f5efde290d2c956ba1
refs/heads/master
2022-12-23T01:44:04.554987
2020-09-18T00:29:10
2020-09-18T00:29:10
296,404,678
0
0
Apache-2.0
2020-09-17T18:05:01
2020-09-17T18:05:00
null
UTF-8
Python
false
false
6,101
py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # 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. # ============================================================================== """KafkaBatchIODatasets""" import tensorflow as tf from tensorflow_io.core.python.ops import core_ops class KafkaBatchIODataset(tf.data.Dataset): """Represents a streaming batch dataset from kafka using consumer groups. The dataset is created by fetching batches of messages from kafka using consumer clients which are part of a consumer group. Each batch of messages is of type `tf.data.Dataset`. This dataset is suitable in scenarios where the 'keys' and 'messages' in kafka topics are synonimous with 'labels' and 'data' items respectively. Thus, enabling the user to train their model in an online learning fashion. The dataset is similar to the `tfio.experimental.streaming.KafkaGroupIODataset` in it's consumer client configuration as it utilizes the consumer groups for retrieving messages from the topics. The dataset can be prepared and iterated in the following manner: >>> import tensorflow_io as tfio >>> dataset = tfio.experimental.streaming.KafkaBatchIODataset( topics=["topic1"], group_id="cg", servers="localhost:9092" ) >>> for mini_batch in dataset: ... mini_batch = mini_batch.map( ... lambda m, k: (tf.cast(m, tf.float32), tf.cast(k, tf.float32))) Since `mini_batch` is of type `tf.data.Dataset` we can perform all the operations that it inherits from `tf.data.Dataset`. To train a keras model on this stream of incoming data: >>> for mini_batch in dataset: ... mini_batch = mini_batch.map( ... lambda m, k: (tf.cast(m, tf.float32), tf.cast(k, tf.float32))) ... model.fit(mini_batch, epochs=10) The `mini_batch` can be directly passed into the `tf.keras` model for training. """ def __init__( self, topics, group_id, servers, message_timeout=5000, stream_timeout=5000, configuration=None, internal=True, ): """ Args: topics: A `tf.string` tensor containing topic names in [topic] format. For example: ["topic1"] group_id: The id of the consumer group. For example: cgstream servers: An optional list of bootstrap servers. For example: `localhost:9092`. message_timeout: An optional timeout value (in milliseconds) for retrieving messages from kafka. Default value is 5000. stream_timeout: An optional timeout value (in milliseconds) to wait for the new messages from kafka to be retrieved by the consumers. Default value is 5000. NOTE: The `stream_timeout` value should always be greater than or equal to the `message_timeout`. value. configuration: An optional `tf.string` tensor containing configurations in [Key=Value] format. Global configuration: please refer to 'Global configuration properties' in librdkafka doc. Examples include ["enable.auto.commit=false", "heartbeat.interval.ms=2000"] Topic configuration: please refer to 'Topic configuration properties' in librdkafka doc. Note all topic configurations should be prefixed with `configuration.topic.`. Examples include ["conf.topic.auto.offset.reset=earliest"] internal: Whether the dataset is being created from within the named scope. Default: True """ with tf.name_scope("KafkaBatchIODataset"): assert internal if stream_timeout < message_timeout: raise ValueError( "stream_timeout {} is less than the message_timeout {}".format( stream_timeout, message_timeout ) ) metadata = list(configuration or []) if group_id is not None: metadata.append("group.id=%s" % group_id) if servers is not None: metadata.append("bootstrap.servers=%s" % servers) resource = core_ops.io_kafka_group_readable_init( topics=topics, metadata=metadata ) self._resource = resource dataset = tf.data.experimental.Counter() dataset = dataset.map( lambda i: core_ops.io_kafka_group_readable_next( input=self._resource, index=i, message_timeout=message_timeout, stream_timeout=stream_timeout, ) ) dataset = dataset.apply( tf.data.experimental.take_while( lambda v: tf.greater(tf.shape(v.message)[0], 0) ) ) dataset = dataset.map( lambda v: tf.data.Dataset.zip( ( tf.data.Dataset.from_tensor_slices(v.message), tf.data.Dataset.from_tensor_slices(v.key), ) ) ) self._dataset = dataset super().__init__( self._dataset._variant_tensor ) # pylint: disable=protected-access def _inputs(self): return [] @property def element_spec(self): return self._dataset.element_spec
[ "noreply@github.com" ]
noreply@github.com
546b3cb45e4b9ea0687a59966b66945ae31d4219
33e95435e493563934271774f37a4ed31c4c3eff
/Atm.py
503ee45b39a428b68052bb73163ffc01466e09ea
[]
no_license
Suryansh-code709/project100
462a5c13ca6f37d5eda32ab8130bb97531f5aa51
e62b95f6fff3337e3a8aa8f9c8b73f62e47f9f2c
refs/heads/master
2023-07-26T11:43:46.089173
2021-08-31T09:45:33
2021-08-31T09:45:33
401,650,227
0
0
null
null
null
null
UTF-8
Python
false
false
951
py
class Atm(object): def __init__(self,cardNumber,pin): self.cardNumber=cardNumber self.pin=pin def check_balance(self): print("your balance is 10000") def withdrawl (self,amount): new_amount=50000-amount print("your withdrawl amount is "+str(amount)+"your remaining balance is "+str(new_amount)) def main(): cardName=input("insert your card number") pinNumber=input("enter your pin") newUser=Atm(cardName,pin_number) print("choose your activity") print("1.balance enquiry 2.Withdrawl") activity=int(input("enter activity number")) if (activity==1): new_user.check_balance() elif(activity==2): amount=int(input("enter the amount:-")) new_user.withdrawl(amount) else: print("enter the valid number") if __name__== "main": main()
[ "noreply@github.com" ]
noreply@github.com
a5f111402661dc059cae8cb061839575063d1371
e84feabf99ff6e15df9eeee7b7c2595853fe746d
/app/utils/rabbit.py
34a303f35e2f07bacfe9fb45fc79e5897dccb18e
[]
no_license
Ravillatypov/freeswitch-intergration
f0536b3abf3982cb2051291dbe101d07e59809b8
cac8cc829ca0d5734a5294847bf7587758b45eb1
refs/heads/main
2023-01-23T02:06:53.070823
2020-10-01T17:19:33
2020-10-01T17:19:33
300,362,493
2
0
null
null
null
null
UTF-8
Python
false
false
943
py
from uuid import uuid4 from aio_pika import Message from app.settings import MQ_CONVERTER_QUEUE_NAME, MQ_UPLOADS_QUEUE_NAME, ENVIRONMENT from aio_pika import RobustConnection async def send_message(rabbit_mq: RobustConnection, routing_key: str, body: bytes): if ENVIRONMENT == 'test': return async with rabbit_mq: channel = await rabbit_mq.channel() await channel.default_exchange.publish( Message(body=body), routing_key=routing_key, ) async def need_convert(rabbit_mq: RobustConnection, call_id: uuid4, path: str): await send_message( rabbit_mq, body=f'{call_id}\n{path}'.encode(), routing_key=MQ_CONVERTER_QUEUE_NAME, ) async def need_upload(rabbit_mq: RobustConnection, call_id: uuid4, path: str): await send_message( rabbit_mq, body=f'{call_id}\n{path}'.encode(), routing_key=MQ_UPLOADS_QUEUE_NAME, )
[ "ravillatypov12@gmail.com" ]
ravillatypov12@gmail.com
d8df7f059625c0c3d099afd29a92a21e68884249
91bc417ffbe13060345dc57d0b88c0499a04d9f7
/Lab6/SeqSum.py
9f0938bb13a9f8c6ea9c85ad166eb7eaadf4c141
[]
no_license
AlexPasechnuy/Python_labs_2.1
ae11e506759d3675a47724493844c185f35963ee
5c7278ff8b2bc40065dd313cde481bf45afa6192
refs/heads/master
2022-03-03T00:25:49.169587
2019-11-03T17:43:17
2019-11-03T17:43:17
null
0
0
null
null
null
null
UTF-8
Python
false
false
83
py
i = int(input()) sum = i while i != 0: i = int(input()) sum += i print(sum)
[ "alexpasechnuy@gmail.com" ]
alexpasechnuy@gmail.com
fe0fdeeb1a24aa276c9885f0de97685b0f54d455
44c2f66912f66d80a0b0ccbe2e286d5ab1ad422b
/uvalibroomcount_api/roomcounter/serializers/room_occupancy_serializer.py
7b07c3e6be4106274cbbc4506606e3ff4604a9de
[]
no_license
scholarslab/uvalibroomcount_api
12d2dee7eb123fb174db732313e9238031ad3288
d3d043e11d9e679204c8d3c401d77082019f285c
refs/heads/master
2021-08-23T11:39:48.813295
2017-12-04T18:58:52
2017-12-04T18:58:52
110,748,333
0
0
null
2017-12-04T18:58:53
2017-11-14T21:43:49
Python
UTF-8
Python
false
false
444
py
from rest_framework import serializers from roomcounter.models import * class RoomOccupancySerializer(serializers.HyperlinkedModelSerializer): ''' The RoomOccupancySerializer class translates the Room Occupancy models into other formats, in this case JSON by default. Method List: -Meta -create -update ''' class Meta: model = room_occupancy_model.RoomOccupancy fields = '__all__' depth = 2
[ "zgleblanc@gmail.com" ]
zgleblanc@gmail.com
23d30041203d14cec8969c7808191158452c4e92
ab48b0ef758953c5a869af38758327337c2bb9ae
/com/lf/pd/index_test.py
4f0d6d4c614e1767e6fb5b7cf9a3cf2386349f40
[]
no_license
liufei0820/lf-first-python-project
920bfaf5ad1a58682da044b42e255cac15c81387
691522d5cfa6d9b5a9f9779a5626e644dd3338e6
refs/heads/master
2023-06-04T08:46:27.942459
2021-06-26T12:14:25
2021-06-26T12:14:25
296,800,690
0
0
null
null
null
null
UTF-8
Python
false
false
921
py
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Time : 2020-09-14 13:37 # @Author : fei.liu import pandas as pd from sklearn.utils import shuffle df = pd.read_csv(r'/Users/apple/Documents/git-source/python-source/my-python-project/resources/ratings.csv') # print(df.count()) # 使用index查询数据 df.set_index('userId', inplace=True, drop=False) # print(df.loc[500].head()) # print(df.head()) # 查询速度对比 df_shuffle = shuffle(df) # print(df_shuffle.head()) # 查看索引是否是递增的 # print(df_shuffle.index.is_monotonic_increasing) # print(df_shuffle.index.is_unique) # 计时,查询id==500数据性能 # %timeit df_shuffle.loc[500] # 排序 df_sorted = df_shuffle.sort_index() # print(df_sorted.index.is_monotonic_increasing) # print(df_sorted.index.is_unique) # index自动对齐 s1 = pd.Series([1, 2, 3], index=list('abc')) s2 = pd.Series([2, 3, 4], index=list('bcd')) print(s1 + s2)
[ "fly.liu@dbappsecurity.com.cn" ]
fly.liu@dbappsecurity.com.cn
1b2d839fd3c17fb5df1b27fb86d98b5a88521421
1d19f60f2f7e2918a360224754bce91547b05155
/functions_nosetests.py
c17ecd126b2c5fa4967f05fb77727cdf07a4776e
[]
no_license
tdupu/excel_tools
f4846cbf87b080a24d66a2b42e77165c1e54d4d6
acb8c1159a9a66a6aeaab7fb1d53729fdecac271
refs/heads/master
2022-12-02T01:46:29.764762
2020-08-19T06:31:56
2020-08-19T06:31:56
285,748,907
0
0
null
null
null
null
UTF-8
Python
false
false
4,998
py
import sys #sys.path.append('/Library/Python/3.7/site-packages/zulip_bots/bots/roboshep/table_functions') #sys.path.append('/Library/Python/3.7/site-packages/zulip_bots/bots/roboshep/table_editor') #sys.path.append('/Library/Python/3.7/site-packages/zulip_bots/bots/roboshep') from mod_functions import * from table_editor import * def test_numbers_3_4(): x = 3*4 assert x==12 def test_make_inclusive_search_key1(): words = ['apple','banana','c'] key=make_inclusive_search_key(words) print(key) assert key =="^(apple|banana|c)" def test_make_inclusive_search_key2(): words = ['apple','banana','c'] key=make_inclusive_search_key(words) assert re.search(key,"copper") def test_match_key(): dicta = {'name':'Cindy', 'hobby':'golf', 'favorite_food':'pizza'} dictb = {'name':'Chuck', 'hobby':'sports', 'favorite_food':'fish'} dictc = {'name':'Mike', 'hobby':'sports', 'favorite_food':'chocolate'} my_list_of_dicts = [dicta,dictb,dictc] answer1 = [dictb,dictc] output_list=match_key(my_list_of_dicts,'hobby','sports') assert output_list == answer1 def test_sheet_name(): S = SheetObject('testbook.xlsx','Sheet1') name = S.sheetname assert name == 'Sheet1' def test_file_name(): S = SheetObject('testbook.xlsx','Sheet1') name = S.filename assert name =='testbook.xlsx' def test_column_dict(): S = SheetObject('testbook.xlsx','Sheet1') column_dict = S.column_dict answer = {1:"name",2:"age", 3:"rank"} assert column_dict ==answer def test_set_of_keys(): S = SheetObject('testbook.xlsx','Sheet1') set_of_keys = S.set_of_keys answer = set(['name','age','rank']) assert set_of_keys == answer def test_number_of_keys(): S = SheetObject('testbook.xlsx','Sheet1') n = S.number_of_keys assert n==3 def test_keys(): S = SheetObject('testbook.xlsx','Sheet1') answer = ['name','age','rank'] keys = S.keys assert keys==answer def test_subsets(): dict0 ={'name':'Joe', 'age':9, 'rank':'captain' } dict1 = {'rank':'noob'} keys0 = dict0.keys() keys1 = dict1.keys() set0 = set(keys0) set1 = set(keys1) assert (set1.issubset(set0))==True def test_valid_new_entry(): S = SheetObject('testbook.xlsx','Sheet1') new_entry = {'name':'Joe', 'age':9, 'rank':'noob' } new_entry2 = {'name':'Joe', 'age':9} is_it_ok = S.is_valid_entry(new_entry) is_it_ok2 = S.is_valid_entry(new_entry2) is_it_ok3 = S.is_valid_entry({'rank':'captain'}) output = (is_it_ok and is_it_ok2 and is_it_ok3) assert (output == True) def test_get_entries1(): """ Tests for a good partial query when passed as a variable """ S = SheetObject('testbook.xlsx','Sheet1') partial_entry = {'rank':'captain'} is_it_ok = S.is_valid_entry(partial_entry) assert (is_it_ok == True) def test_get_entries2(): """ Tests for a good partial query when passed directly """ S = SheetObject('testbook.xlsx','Sheet1') is_it_ok = S.is_valid_entry({'rank':'captain'}) assert (is_it_ok == True) def test_get_entries3(): """ Tests for a good partial query when passed directly """ S = SheetObject('testbook.xlsx','Sheet1') is_it_ok3 = S.is_valid_entry({'rank':'captain'},is_full=True) assert (is_it_ok3 == False) def test_get_entries4(): S = SheetObject('testbook.xlsx','Sheet1') entries = S.get({'rank':'captain'}) answer = [{'name':'joe', 'age':1, 'rank':'captain'}, {'name':'mary', 'age':4, 'rank':'captain' }] assert (entries==answer) def test_get_by_index(): S = SheetObject('testbook.xlsx','Sheet1') output= S.get_by_excel_row_index(2) answer={'name':'joe', 'age':1, 'rank':'captain'} assert output == answer def test_append_and_save(): S = SheetObject('testbook.xlsx','Sheet1') a=S.number_of_entries() new_entry ={'name':'taylor', 'age':36, 'rank':'asst prof'} S.append(new_entry) S.save('testtestbook.xlsx') SS = SheetObject('testtestbook.xlsx','Sheet1') b=SS.number_of_entries() is_ok = (a+1==b) last_entry = SS.get_by_excel_row_index(b+1) is_ok2 = (last_entry == new_entry ) both_ok = (is_ok and is_ok2) assert both_ok == True def test_has_entry(): S = SheetObject('testbook.xlsx','Sheet1') assert S.has_entry({'name':'joe', 'age':1, 'rank':'captain'})==True def test_get_with_index(): S = SheetObject('testbook.xlsx','Sheet1') result = S.get_with_index({'name':'joe', 'age':1, 'rank':'captain'}) answer = [[{'name':'joe', 'age':1, 'rank':'captain'}],[2]] assert result == answer def test_replace(): S = SheetObject('testbook.xlsx','Sheet1') new_entry = {'name':'christelle', 'age':36, 'rank':'full professor'} S.replace({'name':'joe', 'age':1, 'rank':'captain'},new_entry) assert (S.has_entry({'name':'joe', 'age':1, 'rank':'captain'}))==False and (S.has_entry(new_entry)==True)
[ "taylor.dupuy@gmail.com" ]
taylor.dupuy@gmail.com
b23f824b7609fe9d3ffd6dfc970b4fa7214f72ef
cd5e10b919538ff191acf5379e12c4ef7030b259
/2019/08-main.py
4bd0a0b7207fe05c11bb8cea1c4d718550590d89
[]
no_license
jtrinklein/advent-of-code
0eec97811f082f5b1ff999f598e8761555682d77
a7dec73b1ca0c687cc6093badafa8c04ea0cd85a
refs/heads/main
2022-12-12T19:38:30.967243
2022-12-12T01:24:11
2022-12-12T01:24:11
160,144,326
1
1
null
null
null
null
UTF-8
Python
false
false
1,144
py
#!/usr/bin/env python3 data = None with open('./08-data.txt') as f: data = [int(x) for x in list(f.read())] w = 25 h = 6 layer_size = w*h def part1(data): layer = data[:layer_size] data = data[layer_size:] zero_count = layer.count(0) while len(data) > 0: l = data[:layer_size] data = data[layer_size:] zc = l.count(0) if zc < zero_count: layer = l[:] zero_count = zc print(layer.count(1) * layer.count(2)) # part1(data[:]) black = 0 white = 1 transparent = 2 def draw_img(img): for y in range(h): line = '' for x in range(w): p = img[y*w + x] if p == black or p == transparent: line += '-' else: line += '#' print(line) def part2(data): img = [None]*layer_size while img.count(None) > 0 and len(data) > 0: layer = data[:layer_size] data = data[layer_size:] for i in range(layer_size): if img[i] is None and layer[i] != transparent: img[i] = layer[i] draw_img(img) part2(data[:])
[ "jtrinklein@daptiv.com" ]
jtrinklein@daptiv.com
0ba8e6cf08ec403a39f4114cd07dae91ac4183bf
f572e0a4b843ed3fd2cd8edec2ad3aab7a0019d3
/ows/wms/v13/test_encoders.py
d57cc1d1d58cfd386dcf9b086e8f9df557098abf
[ "MIT" ]
permissive
EOxServer/pyows
9039c8ed7358c98d736e2b8fd9f47be944f0b0a1
e09310f992d6e69088940e9b5dbd7302f697344b
refs/heads/master
2022-10-09T23:27:43.884159
2022-10-04T10:03:25
2022-10-04T10:03:25
218,005,699
1
1
null
2022-01-04T13:36:06
2019-10-28T09:01:51
Python
UTF-8
Python
false
false
7,902
py
# ------------------------------------------------------------------------------- # # Project: pyows <http://eoxserver.org> # Authors: Fabian Schindler <fabian.schindler@eox.at> # # ------------------------------------------------------------------------------- # Copyright (C) 2019 EOX IT Services GmbH # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies of this Software or works derived from this Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # ------------------------------------------------------------------------------- from datetime import datetime, timedelta from ows.util import Version, year, month from ows.common.types import WGS84BoundingBox, BoundingBox from ..types import ( ServiceCapabilities, FormatOnlineResource, Layer, Style, LegendURL, Dimension, Range, GetMapRequest, GetFeatureInfoRequest ) from .encoders import xml_encode_capabilities, kvp_encode_get_map_request def test_encode_capabilities(): capabilities = ServiceCapabilities() print(xml_encode_capabilities(capabilities, pretty_print=True).value.decode('utf-8')) capabilities = ServiceCapabilities.with_defaults( 'http://provider.org', ['image/png', 'image/jpeg'], ['text/html', 'application/json'], update_sequence='2018-05-08', title='Title', abstract='Description', keywords=[ 'test', 'WMS', ], fees='None', access_constraints=['None'], provider_name='Provider Inc', provider_site='http://provider.org', individual_name='John Doe', organisation_name='Provider Inc', position_name='CTO', phone_voice='+99/9008820', phone_facsimile='+99/9008821', delivery_point='Point du Hoc', city='City', administrative_area='Adminity', postal_code='12345', country='Cooontry', electronic_mail_address='john.doe@provider.org', online_resource='http://provider.org', hours_of_service='09:00AM - 18:00PM', contact_instructions='Just send a mail or a carrier pidgeon', role='Chief', layer=Layer( title='root layer', abstract='Some abstract', keywords=['Root', 'right?'], crss=['EPSG:4326', 'EPSG:3857'], wgs84_bounding_box=WGS84BoundingBox([-180, -90, 180, 90]), bounding_boxes=[ BoundingBox('EPSG:3857', [ -20026376.39, -20048966.10, 20026376.39, 20048966.10, ]) ], attribution='root attribution', authority_urls={ 'root-auth': 'http://provider.org', }, identifiers={ 'root-auth': 'myId', }, metadata_urls=[ FormatOnlineResource( format='text/xml', href='http://provider.com/metadata.xml', ) ], data_urls=[ FormatOnlineResource( format='image/tiff', href='http://provider.com/data.tif', ) ], min_scale_denominator=5, max_scale_denominator=10, layers=[ Layer( name='sublayer', title='My Sub-layer', queryable=True, styles=[ Style( name='styli', title='Styli', abstract='stylisch Style', legend_urls=[ LegendURL( width=500, height=300, format='image/jpeg', href='http://provider.com/legend.jpg', ) ], style_sheet_url=FormatOnlineResource( 'text/xml', href='http://provider.com/stylesheet.xml', ), style_url=FormatOnlineResource( 'text/xml', href='http://provider.com/style.xml', ) ) ], dimensions=[ Dimension( name='time', units='seconds', values=Range( datetime(2018, 5, 10), datetime(2018, 5, 12), timedelta(hours=1), ), unit_symbol='s', default='', multiple_values=False, nearest_value=True, current=False ), Dimension( name='elevation', units='meters', values=[5, 10, 500, 1000, 15000], unit_symbol='m', default='', multiple_values=False, nearest_value=True, current=False ) ] ) ] ), ) # print(xml_encode_capabilities(capabilities, pretty_print=True).value.decode('utf-8')) def test_encode_getmap(): print(kvp_encode_get_map_request(GetMapRequest( Version(1, 3, 0), layers=['a', 'b', 'c'], styles=['s1', 's2', None], bounding_box=BoundingBox('EPSG:4326', [0, 0, 10, 10]), width=256, height=256, format='image/jpeg', dimensions={} ))) print(kvp_encode_get_map_request(GetMapRequest( Version(1, 3, 0), layers=['a', 'b', 'c'], styles=['s1', 's2', None], bounding_box=BoundingBox('EPSG:4326', [0, 0, 10, 10]), width=256, height=256, format='image/jpeg', time=Range(year(2012), year(2013)), elevation=1000, dimensions={ 'wavelength': '2456.2', 'pressure': ['123', '234'], 'range': [Range('0', '1'), Range('2', '4')] } ))) def test_encode_getfeatureinfo(): GetFeatureInfoRequest( Version(1, 3, 0), layers=['a', 'b', 'c'], styles=['s1', 's2', None], bounding_box=BoundingBox('EPSG:4326', [0, 0, 10, 10]), width=256, height=256, format='image/jpeg', dimensions={}, query_layers=['a', 'b'], info_format='text/xml', i=12, j=12, feature_count=15, )
[ "fabian.schindler.strauss@gmail.com" ]
fabian.schindler.strauss@gmail.com
94d56d92b1ccb581f9240a4dd6a3b26838f67a18
0b588ba7b87d07c9d1191e2677689fffc1cbbbec
/code/chap06/average_by_key_use_aggregatebykey.py
ea83401b40dd3a3f0fb77d807eeca0c359da7119
[ "Apache-2.0" ]
permissive
AnanthaVamshi/PySpark_Tutorials
9fe7698417d729d89acd231291cd9c781e1a31b1
fd94f9af0517f0bffca26d4c7b751333d42b8f3d
refs/heads/master
2020-09-09T08:51:35.459769
2019-11-13T08:53:15
2019-11-13T08:53:15
221,404,965
0
0
null
null
null
null
UTF-8
Python
false
false
2,736
py
#!/usr/bin/python #----------------------------------------------------- # This program find average per key using # the aggregateByKey() transformation. #------------------------------------------------------ # Input Parameters: # none #------------------------------------------------------- # @author Mahmoud Parsian #------------------------------------------------------- from __future__ import print_function import sys from pyspark.sql import SparkSession if __name__ == '__main__': # create an instance of SparkSession spark = SparkSession\ .builder\ .appName("average_by_key_use_aggregatebykey")\ .getOrCreate() input = [("k1", 1), ("k1", 2), ("k1", 3), ("k1", 4), ("k1", 5),\ ("k2", 6), ("k2", 7), ("k2", 8),\ ("k3", 10), ("k3", 12)] # build RDD<key, value> rdd = spark.sparkContext.parallelize(input) # By KEY, simultaneously calculate the SUM (the numerator # for the average that we want to compute), and COUNT (the # denominator for the average that we want to compute): # Combined data structure (C) is a Tuple2(sum, count) # The following lambda functions needs to be defined: # # zero --> C (initial-value per partition) # C, v --> C (within-partition reduction) # C, C --> C (cross-Partition reduction) # zero = (0.0, 0) # zero = (sum, count) as initial value per partition # C = (sum, count) # C1 = (sum1, count1) # C2 = (sum2, count2) # C1 + C2 = (sum1+sum2, count1+count2) # sum_count = rdd.aggregateByKey(\ zero,\ lambda C, V: (C[0] + V, C[1] + 1),\ lambda C1, C2: (C1[0] + C2[0], C1[1] + C[1])) # What did happen? The following is true about the meaning of # each a and b pair above (so you can visualize what's happening): # # First lambda expression for Within-Partition Reduction Step:: # C: is a TUPLE that holds: (runningSum, runningCount). # V: is a SCALAR that holds the next Value # # Second lambda expression for Cross-Partition Reduction Step:: # C1: is a TUPLE that holds: (runningSum, runningCount). # C2: is a TUPLE that holds: (nextPartitionsSum, nextPartitionsCount). # Finally, calculate the average for each KEY, and collect results. # show sum_count print("sum_count = ", sum_count.collect()) # [ # ('k3', (22, 2)), # ('k2', (21, 3)), # ('k1', (15, 5)) # ] # find averages avg = sum_count.mapValues( lambda v : float(v[0]) / float(v[1])) print("avg = ", avg.collect()) # avg.collect() # [ # ('k3', 11), # ('k2', 7), # ('k1', 3) # ] # done! spark.stop()
[ "44905464+AnanthaVamshi@users.noreply.github.com" ]
44905464+AnanthaVamshi@users.noreply.github.com
88f492c63ddff713d0a4aac43cf1c41801c01612
fcd6bff51f26f70d44135e50f1e47982ae971ee3
/medical.py
739291790669f25dfacbcef09749d4905a4cdb2c
[]
no_license
bax24/Coding-Theory
485c64dc104d8bae70a093dbe655c84c13fa4680
20ccaf8c688eb6d6852173ddb3c672bbf97c190b
refs/heads/main
2023-03-18T03:02:52.827152
2021-03-09T11:14:35
2021-03-09T11:14:35
344,070,418
0
0
null
null
null
null
UTF-8
Python
false
false
2,701
py
import pandas as pd import implementation as f import numpy as np df = pd.read_csv (r'P1_medicalDB.csv') def get_prob_distribution(variable): prob = [] N = df.shape[0] card = len(df[variable].value_counts()) for i in range(card): p = df[variable].value_counts()[i]/N prob.append(p) return prob def get_cardinality(variable): return len(df[variable].value_counts()) # à tester avec 2 autres variables def get_cond_prob(variable, given, disp = False): card_variable = len(df[variable].value_counts()) card_given = len(df[given].value_counts()) prob = np.zeros((card_given , card_variable)) for i in range(card_given): N = df[given].value_counts()[i] for j in range(card_variable): name_var = df[given].value_counts().index.tolist()[i] if disp: print(name_var) prob[i][j] = df[df[given] == name_var][variable].value_counts(sort = False)[j]/N df[variable].value_counts(sort = False) return prob def get_joint_prob(variable_1, variable_2): card_variable_1 = len(df[variable_1].value_counts()) card_variable_2 = len(df[variable_2].value_counts()) joint_prob = np.zeros((card_variable_2 , card_variable_1)) cond_prob = get_cond_prob(variable_1, variable_2) marg_prob = get_prob_distribution(variable_2) for i in range(cond_prob.shape[0]): for j in range(cond_prob.shape[1]): joint_prob[i][j] = cond_prob[i][j]*marg_prob[i] return joint_prob if __name__ == "__main__": variable = 'DIS' given = ' p = get_cond_prob('DIS', 'sex', True) # Entropy of each variable card = [] entropies = [] for variable in list(df.columns): card.append(get_cardinality(variable)) prob_dist = get_prob_distribution(variable) entropy = f.entropy(prob_dist) entropies.append(round(entropy, 3)) print(card) print(entropies) # Conditional entropy of the disease given each variables cond_entropies = [] variable = 'DIS' for given in list(df.columns): if given == variable: continue cond_prob = get_cond_prob(variable, given) marg_prob = get_prob_distribution(given) cond_entr = f.conditional_entropy(cond_prob, marg_prob) cond_entropies.append(round(cond_entr, 3)) print(cond_entropies) # Mutual information variable_1 = 'obesity' variable_2 = 'age' joint_prob = get_joint_prob(variable_1, variable_2) prob_var_1 = get_prob_distribution(variable_1) prob_var_2 = get_prob_distribution(variable_2) mut_inf = f.mutual_information(prob_var_1, prob_var_2, joint_prob) cond_prob = get_cond_prob('obesity', 'age') marg_prob = get_prob_distribution('age') cond_entr = f.conditional_entropy(cond_prob, marg_prob) p = get_prob_distribution('obesity') entr = f.entropy(p)
[ "lucas.backes07@gmail.com" ]
lucas.backes07@gmail.com
50c3edc350ae21616f9a71a761c9bb660ec1bd46
d87af6cc4e1d2575b9c943ec178552154564748c
/server/server/urls.py
946c03d17336dfcd760f686e350f457dfc041031
[]
no_license
liyangguang1993/Django_Backend
0defc7079f40efd442025348e884e40b14048bc7
1516493781af79dc36e82ab62f99474418098d6b
refs/heads/master
2021-01-10T08:11:22.742750
2015-11-27T03:53:13
2015-11-27T03:53:13
46,957,267
0
0
null
null
null
null
UTF-8
Python
false
false
4,448
py
"""server URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import include, url from django.contrib import admin #user_views from users.views_user_operation import * from users.views import * #TrafficMonitor_views from TrafficMonitor.views_dushboard_resources import * from TrafficMonitor.views_resource_list import * from TrafficMonitor.views_traffic_applications import * from TrafficMonitor.views_traffic_report import * #DataManager_views from DataManager.views_history_data import * from DataManager.views_apply_for_collection import * from DataManager.views_dataset_query import * from DataManager.views_management_applications import * #ClusterManager from ClusterManager.views_log_management import * from ClusterManager.views_report_management import * from ClusterManager.views_cluster_overview import * from ClusterManager.views_job_management import * urlpatterns = [ url(r'^admin/', include(admin.site.urls)), ] #Useroperation urlpatterns += [ url(r'^users/$', User_list.as_view()), #user_operation url(r'^OperatorLogin/$', OperatorLogin.as_view()), url(r'^OperatorChgPsw/', OperatorChgPsw.as_view()), url(r'^OperatorReg/', OperatorReg.as_view()), url(r'^AdminLogin/', AdminLogin.as_view()), url(r'^AdminChgPsw/', AdminChgPsw.as_view()), url(r'^AdminReg/', AdminReg.as_view()), url(r'^ResearcherLogin/', ResearcherLogin.as_view()), url(r'^ResearcherChgPsw/', ResearcherChgPsw.as_view()), url(r'^ResearcherReg/', ResearcherReg.as_view()), ] #TrafficMonitor urlpatterns += [ #dushboard_resources url(r'^RealtimeApplicationThroughput/$', RealtimeApplicationThroughput.as_view()), url(r'^RealtimeApplicationDataPacket/$', RealtimeApplicationDataPacket.as_view()), url(r'^RealtimeApplicationStream/$', RealtimeApplicationStream.as_view()), url(r'^RealtimeSourceCountryThroughput/$', RealtimeSourceCountryThroughput.as_view()), url(r'^RealtimeDestinationCountryThroughput/$', RealtimeDestinationCountryThroughput.as_view()), url(r'^RealtimeApplicationStatisticsForm/$', RealtimeApplicationStatisticsForm.as_view()), url(r'^RealtimeApplicationChart/$', RealtimeApplicationChart.as_view()), url(r'^RealtimeSourceCountryChart/$', RealtimeSourceCountryChart.as_view()), url(r'^RealtimeDestinationCountryChart/$', RealtimeDestinationCountryChart.as_view()), #resource_list url(r'^ResourceList/$', ResourceList.as_view()), #traffic_applications url(r'^AnomlyDetections/$', AnomlyDetections.as_view()), url(r'^AnomlyDetectionsid/$', AnomlyDetectionsid.as_view()), #traffic_report url(r'^ReportForm/$', ReportForm.as_view()), ] #DataManager urlpatterns += [ #history_data url(r'^OfflineApplicationLayerResults/$', OfflineApplicationLayerResults.as_view()), url(r'^OfflineTransportLayerResults/$', OfflineTransportLayerResults.as_view()), url(r'^OfflineNetworkLayerResults/$', OfflineNetworkLayerResults.as_view()), #dataset_query url(r'^StandardDatasetList/$', StandardDatasetList.as_view()), url(r'^StandardDatasetsDetail/$', StandardDatasetsDetail.as_view()), url(r'^StandardDatasetQuery/$', StandardDatasetQuery.as_view()), #apply_for_collection url(r'^GetAvailableDatasets/$', GetAvailableDatasets.as_view()), url(r'^ApplyNewDataset/$', ApplyNewDataset.as_view()), #management_application url(r'^GetAvailableJar/$', GetAvailableJar.as_view()), url(r'^UploadJar/$', UploadJar.as_view()), url(r'^RunJar/$', RunJar.as_view()), ] #ClusterManager urlpatterns += [ #cluster_overview url(r'^ClusterOverview/$', ClusterOverview.as_view()), #job_management url(r'^JobManagement/$', JobManagement.as_view()), #log_management url(r'^LogManagement/$', LogManagement.as_view()), #report_management url(r'^ReportManagement/$', ReportManagement.as_view()), ]
[ "308159288@qq.com" ]
308159288@qq.com
1a2c6b71e90eaaf3b8b7f16f74458d75c5a212f1
e4016fda4e1857e29c1d25e30f57f01a9e8181d8
/day10b.py
28f6d8d9c9c8f24fad8d9fd0b2b79343dfa7c009
[ "MIT" ]
permissive
boneillhawk/advent2017
9eee7fdaa830e368d2fdb083c6b3e71649cb25d8
ccf89ea0d15da86286de4e4475e0bd71aca9e404
refs/heads/master
2021-08-31T15:22:50.645886
2017-12-21T22:02:45
2017-12-21T22:02:45
112,771,888
0
0
null
null
null
null
UTF-8
Python
false
false
1,209
py
import itertools import functools import copy import collections import heapq import math import hashlib def day10b(): f = open('input\\input10.txt', 'r') data = f.readline() f.close() lens = [ord(x) for x in data] lens += [17,31,73,47,23] mylist = list(range(256)) current = 0 skip = 0 for rd in range(64): for i in lens: mylist = reverse(mylist, current, i) current += (i + skip) current = current%len(mylist) skip += 1 dense = [xor(mylist,a,a+16) for a in range(0,len(mylist),16)] result = [hex(j)[2:] for j in dense] return ''.join(result) def xor(mylist,start,end): return functools.reduce(lambda x, y: x^y, mylist[start:end]) def reverse(mylist, start, amt): if start+amt > len(mylist): diff = (start+amt)-len(mylist) reversable = mylist[start:]+mylist[:diff] reversed = reversable[::-1] return reversed[-diff:]+mylist[diff:start]+reversed[:-diff] else: end = start+amt return mylist[:start]+mylist[end-1:start:-1]+[mylist[start]]+mylist[end:] print(day10b())
[ "noreply@github.com" ]
noreply@github.com
64c3347230261e1f9e6d7d5b790373ca03fc9182
007eeac2ea8a860abcde2e3479fac2095d4a9db3
/sample/utils.py
e17674db41ba1008c218a2cbbc6c4713767dd4c6
[]
no_license
autocyz/CornerNet_easy_use
21b78a5f22447415804e9291345abc86666e23d4
fabc1bd6d96bfae0863931176df7f307529b5203
refs/heads/master
2020-05-16T23:27:10.294082
2019-04-25T06:01:39
2019-04-25T06:01:39
183,366,023
15
3
null
null
null
null
UTF-8
Python
false
false
4,150
py
import numpy as np import xml.etree.ElementTree as ET class ParseLabel(object): def __init__(self, xml_file): parser = ET.XMLParser(encoding="utf-8") self.xml_file = xml_file self.tree = ET.parse(xml_file, parser=parser) self.root = self.tree.getroot() def get_file_name(self): return self.root.find('filename').text def get_img_size(self): """ :return: return image size (C, H, W) """ size = self.root.find('size') width = int(size.find('width')) height = int(size.find('height')) depth = int(size.find('depth')) return depth, height, width def get_bboxes(self): """ get all the boudingboxes :return: bboxes, [[bbox1],[bbox2],[bbox3],....] """ objects = self.root.findall('object') bboxes = [] for ob in objects: bndbox = ob.find('bndbox') xmin = int(bndbox.find('xmin').text) ymin = int(bndbox.find('ymin').text) xmax = int(bndbox.find('xmax').text) ymax = int(bndbox.find('ymax').text) bboxes.append([xmin, ymin, xmax, ymax]) return bboxes def gaussian2D(shape, sigma=1): m, n = [(ss - 1.) / 2. for ss in shape] y, x = np.ogrid[-m:m + 1, -n:n + 1] h = np.exp(-(x * x + y * y) / (2 * sigma * sigma)) h[h < np.finfo(h.dtype).eps * h.max()] = 0 return h def draw_gaussian(heatmap, center, radius, k=1): diameter = 2 * radius + 1 gaussian = gaussian2D((diameter, diameter), sigma=diameter / 6) x, y = center height, width = heatmap.shape[0:2] left, right = min(x, radius), min(width - x, radius + 1) top, bottom = min(y, radius), min(height - y, radius + 1) masked_heatmap = heatmap[y - top:y + bottom, x - left:x + right] masked_gaussian = gaussian[radius - top:radius + bottom, radius - left:radius + right] np.maximum(masked_heatmap, masked_gaussian * k, out=masked_heatmap) def gaussian_radius(det_size, min_overlap): height, width = det_size a1 = 1 b1 = (height + width) c1 = width * height * (1 - min_overlap) / (1 + min_overlap) sq1 = np.sqrt(b1 ** 2 - 4 * a1 * c1) r1 = (b1 - sq1) / (2 * a1) a2 = 4 b2 = 2 * (height + width) c2 = (1 - min_overlap) * width * height sq2 = np.sqrt(b2 ** 2 - 4 * a2 * c2) r2 = (b2 - sq2) / (2 * a2) a3 = 4 * min_overlap b3 = -2 * min_overlap * (height + width) c3 = (min_overlap - 1) * width * height sq3 = np.sqrt(b3 ** 2 - 4 * a3 * c3) r3 = (b3 + sq3) / (2 * a3) return min(r1, r2, r3) def _get_border(border, size): i = 1 while size - border // i <= border // i: i *= 2 return border // i def random_crop(image, detections, random_scales, view_size, border=64): view_height, view_width = view_size image_height, image_width = image.shape[0:2] scale = np.random.choice(random_scales) height = int(view_height * scale) width = int(view_width * scale) cropped_image = np.zeros((height, width, 3), dtype=image.dtype) w_border = _get_border(border, image_width) h_border = _get_border(border, image_height) ctx = np.random.randint(low=w_border, high=image_width - w_border) cty = np.random.randint(low=h_border, high=image_height - h_border) x0, x1 = max(ctx - width // 2, 0), min(ctx + width // 2, image_width) y0, y1 = max(cty - height // 2, 0), min(cty + height // 2, image_height) left_w, right_w = ctx - x0, x1 - ctx top_h, bottom_h = cty - y0, y1 - cty # crop image cropped_ctx, cropped_cty = width // 2, height // 2 x_slice = slice(cropped_ctx - left_w, cropped_ctx + right_w) y_slice = slice(cropped_cty - top_h, cropped_cty + bottom_h) cropped_image[y_slice, x_slice, :] = image[y0:y1, x0:x1, :] # crop detections cropped_detections = detections.copy() cropped_detections[:, 0:4:2] -= x0 cropped_detections[:, 1:4:2] -= y0 cropped_detections[:, 0:4:2] += cropped_ctx - left_w cropped_detections[:, 1:4:2] += cropped_cty - top_h return cropped_image, cropped_detections
[ "chenyongzhi@chenyongzhideMacBook-Air.local" ]
chenyongzhi@chenyongzhideMacBook-Air.local
2175f0c6c75b4f6669609f7a09d8ddb6bacc229e
93bf4bbafe0524335ea1216f7f2941348c2cd1bd
/tensorflow/python/kernel_tests/pad_op_test.py
1597a8c947eb82da5cb47f2e9aac7d6a2967bbbf
[ "Apache-2.0" ]
permissive
sachinpro/sachinpro.github.io
c4951734b09588cad58711a76fe657f110163c11
c3bbd8d89818f5d8bb7296c851ed5e52c19728e3
refs/heads/master
2022-12-23T10:00:13.902459
2016-06-27T13:18:27
2016-06-27T13:25:58
25,289,839
1
1
Apache-2.0
2022-12-15T00:45:03
2014-10-16T06:44:30
C++
UTF-8
Python
false
false
6,742
py
# Copyright 2015 Google Inc. All Rights Reserved. # # 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. # ============================================================================== """Tests for tensorflow.ops.nn_ops.Pad.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf class PadOpTest(tf.test.TestCase): def _npPad(self, inp, paddings, mode): return np.pad(inp, paddings, mode=mode.lower()) def testNpPad(self): self.assertAllEqual( np.array([[0, 0, 0, 0, 0, 0], [0, 3, 3, 0, 0, 0], [0, 4, 4, 0, 0, 0], [0, 5, 5, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]]), self._npPad( np.array([[3, 3], [4, 4], [5, 5]]), [[1, 2], [1, 3]], mode="constant")) self.assertAllEqual( np.array([[4, 3, 4, 9, 4, 3], [1, 0, 1, 2, 1, 0], [4, 3, 4, 9, 4, 3], [1, 0, 1, 2, 1, 0]]), self._npPad( np.array([[0, 1, 2], [3, 4, 9]]), [[1, 1], [1, 2]], mode="reflect")) self.assertAllEqual( np.array([[0, 0, 1, 2, 2, 1], [0, 0, 1, 2, 2, 1], [3, 3, 4, 9, 9, 4], [3, 3, 4, 9, 9, 4]]), self._npPad( np.array([[0, 1, 2], [3, 4, 9]]), [[1, 1], [1, 2]], mode="symmetric")) def _testPad(self, np_inputs, paddings, mode, use_gpu=False): np_val = self._npPad(np_inputs, paddings, mode=mode) with self.test_session(use_gpu=use_gpu): tf_val = tf.pad(np_inputs, paddings, mode=mode) out = tf_val.eval() self.assertAllEqual(np_val, out) self.assertShapeEqual(np_val, tf_val) def _testGradient(self, x, a, mode): with self.test_session(): inx = tf.convert_to_tensor(x) xs = list(x.shape) ina = tf.convert_to_tensor(a) y = tf.pad(inx, ina, mode=mode) # Expected y's shape to be: ys = list(np.array(x.shape) + np.sum(np.array(a), axis=1)) jacob_t, jacob_n = tf.test.compute_gradient(inx, xs, y, ys, x_init_value=x) self.assertAllClose(jacob_t, jacob_n, rtol=1e-5, atol=1e-5) def _testAll(self, np_inputs, paddings): for mode in ("CONSTANT", "REFLECT", "SYMMETRIC"): self._testPad(np_inputs, paddings, mode=mode, use_gpu=False) self._testPad(np_inputs, paddings, mode=mode, use_gpu=True) if np_inputs.dtype == np.float32: self._testGradient(np_inputs, paddings, mode=mode) def testInputDims(self): with self.test_session(): with self.assertRaises(ValueError): tf.pad( tf.reshape([1, 2], shape=[1, 2, 1, 1, 1, 1]), tf.reshape([1, 2], shape=[1, 2])) def testPaddingsDim(self): with self.test_session(): with self.assertRaises(ValueError): tf.pad( tf.reshape([1, 2], shape=[1, 2]), tf.reshape([1, 2], shape=[2])) def testPaddingsDim2(self): with self.test_session(): with self.assertRaises(ValueError): tf.pad( tf.reshape([1, 2], shape=[1, 2]), tf.reshape([1, 2], shape=[2, 1])) def testPaddingsDim3(self): with self.test_session(): with self.assertRaises(ValueError): tf.pad( tf.reshape([1, 2], shape=[1, 2]), tf.reshape([1, 2], shape=[1, 2])) def testPaddingsDim4(self): with self.test_session(): with self.assertRaises(ValueError): tf.pad( tf.reshape([1, 2], shape=[1, 2]), tf.reshape([1, 2, 3, 4, 5, 6], shape=[3, 2])) def testPaddingsNonNegative(self): with self.test_session(): with self.assertRaisesRegexp(ValueError, "must be non-negative"): tf.pad( tf.constant([1], shape=[1]), tf.constant([-1, 0], shape=[1, 2])) def testPaddingsNonNegative2(self): with self.test_session(): with self.assertRaisesRegexp(ValueError, "must be non-negative"): tf.pad( tf.constant([1], shape=[1]), tf.constant([-1, 0], shape=[1, 2])) def testPaddingsMaximum(self): with self.test_session(): with self.assertRaises(Exception): tf.pad( tf.constant([1], shape=[2]), tf.constant([2, 0], shape=[1, 2]), mode="REFLECT").eval() with self.assertRaises(Exception): tf.pad( tf.constant([1], shape=[2]), tf.constant([0, 3], shape=[1, 2]), mode="SYMMETRIC").eval() def testIntTypes(self): # TODO(touts): Figure out why the padding tests do not work on GPU # for int types and rank > 2. for t in [np.int32, np.int64]: self._testAll((np.random.rand(4, 4, 3) * 100).astype(t), [[1, 0], [2, 3], [0, 2]]) def testFloatTypes(self): for t in [np.float32, np.float64, np.complex64]: self._testAll(np.random.rand(2, 5).astype(t), [[1, 0], [2, 0]]) def testShapeFunctionEdgeCases(self): # Unknown paddings shape. inp = tf.constant(0.0, shape=[4, 4, 4, 4]) padded = tf.pad(inp, tf.placeholder(tf.int32)) self.assertEqual([None, None, None, None], padded.get_shape().as_list()) # Unknown input shape. inp = tf.placeholder(tf.float32) padded = tf.pad(inp, [[2, 2], [2, 2]]) self.assertEqual([None, None], padded.get_shape().as_list()) # Unknown input and paddings shape. inp = tf.placeholder(tf.float32) padded = tf.pad(inp, tf.placeholder(tf.int32)) self.assertAllEqual(None, padded.get_shape().ndims) def testScalars(self): paddings = np.zeros((0, 2), dtype=np.int32) inp = np.asarray(7) for use_gpu in False, True: with self.test_session(use_gpu=use_gpu): tf_val = tf.pad(inp, paddings) out = tf_val.eval() self.assertAllEqual(inp, out) self.assertShapeEqual(inp, tf_val) if __name__ == "__main__": tf.test.main()
[ "x0234443@ti.com" ]
x0234443@ti.com
4fffc7a80242a3f0658869191f8a522ab2c838b3
730cad7bf4a17ec2cb8844fc68a11d7895109c9d
/gui/ui/ui_generated/portWindow.py
c21f850ec779370cd8e0696ffa8ead3eff28c901
[]
no_license
Ilya-Belyanov/PyArduino
4f4cb579a36dfd11fb667cb867b7c9ad31352c86
fdcb33a46428a142938b43689ea824b3a8331422
refs/heads/master
2023-01-25T00:02:19.832156
2020-11-30T19:12:20
2020-11-30T19:12:20
312,907,006
0
0
null
null
null
null
UTF-8
Python
false
false
4,583
py
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'C:\Code\Python\Arduino-PyInterface-MRS\gui\ui\portWindow.ui' # # Created by: PyQt5 UI code generator 5.15.1 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(300, 310) MainWindow.setMinimumSize(QtCore.QSize(300, 310)) MainWindow.setMaximumSize(QtCore.QSize(300, 310)) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.verticalLayout_2 = QtWidgets.QVBoxLayout(self.centralwidget) self.verticalLayout_2.setObjectName("verticalLayout_2") self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setObjectName("horizontalLayout") self.port = QtWidgets.QComboBox(self.centralwidget) self.port.setMinimumSize(QtCore.QSize(0, 0)) self.port.setObjectName("port") self.horizontalLayout.addWidget(self.port) self.lPort = QtWidgets.QLabel(self.centralwidget) self.lPort.setMaximumSize(QtCore.QSize(400, 400)) self.lPort.setAlignment(QtCore.Qt.AlignCenter) self.lPort.setObjectName("lPort") self.horizontalLayout.addWidget(self.lPort) self.verticalLayout_2.addLayout(self.horizontalLayout) self.horizontalLayout_2 = QtWidgets.QHBoxLayout() self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.speed = QtWidgets.QComboBox(self.centralwidget) self.speed.setMinimumSize(QtCore.QSize(0, 0)) self.speed.setObjectName("speed") self.horizontalLayout_2.addWidget(self.speed) self.lSpeed = QtWidgets.QLabel(self.centralwidget) self.lSpeed.setMaximumSize(QtCore.QSize(400, 16777215)) self.lSpeed.setAlignment(QtCore.Qt.AlignCenter) self.lSpeed.setObjectName("lSpeed") self.horizontalLayout_2.addWidget(self.lSpeed) self.verticalLayout_2.addLayout(self.horizontalLayout_2) self.progressBar = QtWidgets.QProgressBar(self.centralwidget) self.progressBar.setProperty("value", 24) self.progressBar.setObjectName("progressBar") self.verticalLayout_2.addWidget(self.progressBar) self.connect = QtWidgets.QPushButton(self.centralwidget) self.connect.setObjectName("connect") self.verticalLayout_2.addWidget(self.connect) self.lConnect = QtWidgets.QLabel(self.centralwidget) self.lConnect.setMinimumSize(QtCore.QSize(0, 58)) self.lConnect.setText("") self.lConnect.setAlignment(QtCore.Qt.AlignCenter) self.lConnect.setObjectName("lConnect") self.verticalLayout_2.addWidget(self.lConnect) self.horizontalLayout_3 = QtWidgets.QHBoxLayout() self.horizontalLayout_3.setObjectName("horizontalLayout_3") self.OK = QtWidgets.QPushButton(self.centralwidget) self.OK.setMinimumSize(QtCore.QSize(0, 50)) self.OK.setObjectName("OK") self.horizontalLayout_3.addWidget(self.OK) self.Cancel = QtWidgets.QPushButton(self.centralwidget) self.Cancel.setMinimumSize(QtCore.QSize(0, 50)) self.Cancel.setObjectName("Cancel") self.horizontalLayout_3.addWidget(self.Cancel) self.verticalLayout_2.addLayout(self.horizontalLayout_3) MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 300, 26)) self.menubar.setObjectName("menubar") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.lPort.setText(_translate("MainWindow", "Choice available port")) self.lSpeed.setText(_translate("MainWindow", "Choice speed of port")) self.connect.setText(_translate("MainWindow", "Connect")) self.OK.setText(_translate("MainWindow", "OK")) self.Cancel.setText(_translate("MainWindow", "Cancel"))
[ "belyanov.99@mail.ru" ]
belyanov.99@mail.ru
f7460f6641108e37de035ca72ab022c1e7990a3d
c9ddbdb5678ba6e1c5c7e64adf2802ca16df778c
/cases/synthetic/tree-big-3507.py
f4222a0786dc84c1b850189e6ca510c0b4caf33c
[]
no_license
Virtlink/ccbench-chocopy
c3f7f6af6349aff6503196f727ef89f210a1eac8
c7efae43bf32696ee2b2ee781bdfe4f7730dec3f
refs/heads/main
2023-04-07T15:07:12.464038
2022-02-03T15:42:39
2022-02-03T15:42:39
451,969,776
0
0
null
null
null
null
UTF-8
Python
false
false
23,286
py
# Binary-search trees class TreeNode(object): value:int = 0 left:"TreeNode" = None right:"TreeNode" = None def insert(self:"TreeNode", x:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode(x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode(x) return True else: return self.right.insert(x) return False def contains(self:"TreeNode", x:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True class TreeNode2(object): value:int = 0 value2:int = 0 left:"TreeNode2" = None left2:"TreeNode2" = None right:"TreeNode2" = None right2:"TreeNode2" = None def insert(self:"TreeNode2", x:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode2(x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode2(x, x) return True else: return self.right.insert(x) return False def insert2(self:"TreeNode2", x:int, x2:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode2(x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode2(x, x) return True else: return self.right.insert(x) return False def contains(self:"TreeNode2", x:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains2(self:"TreeNode2", x:int, x2:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True class TreeNode3(object): value:int = 0 value2:int = 0 value3:int = 0 left:"TreeNode3" = None left2:"TreeNode3" = None left3:"TreeNode3" = None right:"TreeNode3" = None right2:"TreeNode3" = None right3:"TreeNode3" = None def insert(self:"TreeNode3", x:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode3(x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode3(x, x, x) return True else: return self.right.insert(x) return False def insert2(self:"TreeNode3", x:int, x2:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode3(x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode3(x, x, x) return True else: return self.right.insert(x) return False def insert3(self:"TreeNode3", x:int, x2:int, x3:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode3(x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode3(x, x, x) return True else: return self.right.insert(x) return False def contains(self:"TreeNode3", x:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains2(self:"TreeNode3", x:int, x2:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains3(self:"TreeNode3", x:int, x2:int, x3:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True class TreeNode4(object): value:int = 0 value2:int = 0 value3:int = 0 value4:int = 0 left:"TreeNode4" = None left2:"TreeNode4" = None left3:"TreeNode4" = None left4:"TreeNode4" = None right:"TreeNode4" = None right2:"TreeNode4" = None right3:"TreeNode4" = None right4:"TreeNode4" = None def insert(self:"TreeNode4", x:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode4(x, x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode4(x, x, x, x) return True else: return self.right.insert(x) return False def insert2(self:"TreeNode4", x:int, x2:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode4(x, x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode4(x, x, x, x) return True else: return self.right.insert(x) return False def insert3(self:"TreeNode4", x:int, x2:int, x3:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode4(x, x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode4(x, x, x, x) return True else: return self.right.insert(x) return False def insert4(self:"TreeNode4", x:int, x2:int, x3:int, x4:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode4(x, x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode4(x, x, x, x) return True else: return self.right.insert(x) return False def contains(self:"TreeNode4", x:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains2(self:"TreeNode4", x:int, x2:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains3(self:"TreeNode4", x:int, x2:int, x3:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains4(self:"TreeNode4", x:int, x2:int, x3:int, x4:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True class TreeNode5(object): value:int = 0 value2:int = 0 value3:int = 0 value4:int = 0 value5:int = 0 left:"TreeNode5" = None left2:"TreeNode5" = None left3:"TreeNode5" = None left4:"TreeNode5" = None left5:"TreeNode5" = None right:"TreeNode5" = None right2:"TreeNode5" = None right3:"TreeNode5" = None right4:"TreeNode5" = None right5:"TreeNode5" = None def insert(self:"TreeNode5", x:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode5(x, x, x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode5(x, x, x, x, x) return True else: return self.right.insert(x) return False def insert2(self:"TreeNode5", x:int, x2:int) -> bool: if x < $Member: if self.left is None: self.left = makeNode5(x, x, x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode5(x, x, x, x, x) return True else: return self.right.insert(x) return False def insert3(self:"TreeNode5", x:int, x2:int, x3:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode5(x, x, x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode5(x, x, x, x, x) return True else: return self.right.insert(x) return False def insert4(self:"TreeNode5", x:int, x2:int, x3:int, x4:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode5(x, x, x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode5(x, x, x, x, x) return True else: return self.right.insert(x) return False def insert5(self:"TreeNode5", x:int, x2:int, x3:int, x4:int, x5:int) -> bool: if x < self.value: if self.left is None: self.left = makeNode5(x, x, x, x, x) return True else: return self.left.insert(x) elif x > self.value: if self.right is None: self.right = makeNode5(x, x, x, x, x) return True else: return self.right.insert(x) return False def contains(self:"TreeNode5", x:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains2(self:"TreeNode5", x:int, x2:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains3(self:"TreeNode5", x:int, x2:int, x3:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains4(self:"TreeNode5", x:int, x2:int, x3:int, x4:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True def contains5(self:"TreeNode5", x:int, x2:int, x3:int, x4:int, x5:int) -> bool: if x < self.value: if self.left is None: return False else: return self.left.contains(x) elif x > self.value: if self.right is None: return False else: return self.right.contains(x) else: return True class Tree(object): root:TreeNode = None size:int = 0 def insert(self:"Tree", x:int) -> object: if self.root is None: self.root = makeNode(x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def contains(self:"Tree", x:int) -> bool: if self.root is None: return False else: return self.root.contains(x) class Tree2(object): root:TreeNode2 = None root2:TreeNode2 = None size:int = 0 size2:int = 0 def insert(self:"Tree2", x:int) -> object: if self.root is None: self.root = makeNode2(x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert2(self:"Tree2", x:int, x2:int) -> object: if self.root is None: self.root = makeNode2(x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def contains(self:"Tree2", x:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains2(self:"Tree2", x:int, x2:int) -> bool: if self.root is None: return False else: return self.root.contains(x) class Tree3(object): root:TreeNode3 = None root2:TreeNode3 = None root3:TreeNode3 = None size:int = 0 size2:int = 0 size3:int = 0 def insert(self:"Tree3", x:int) -> object: if self.root is None: self.root = makeNode3(x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert2(self:"Tree3", x:int, x2:int) -> object: if self.root is None: self.root = makeNode3(x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert3(self:"Tree3", x:int, x2:int, x3:int) -> object: if self.root is None: self.root = makeNode3(x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def contains(self:"Tree3", x:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains2(self:"Tree3", x:int, x2:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains3(self:"Tree3", x:int, x2:int, x3:int) -> bool: if self.root is None: return False else: return self.root.contains(x) class Tree4(object): root:TreeNode4 = None root2:TreeNode4 = None root3:TreeNode4 = None root4:TreeNode4 = None size:int = 0 size2:int = 0 size3:int = 0 size4:int = 0 def insert(self:"Tree4", x:int) -> object: if self.root is None: self.root = makeNode4(x, x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert2(self:"Tree4", x:int, x2:int) -> object: if self.root is None: self.root = makeNode4(x, x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert3(self:"Tree4", x:int, x2:int, x3:int) -> object: if self.root is None: self.root = makeNode4(x, x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert4(self:"Tree4", x:int, x2:int, x3:int, x4:int) -> object: if self.root is None: self.root = makeNode4(x, x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def contains(self:"Tree4", x:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains2(self:"Tree4", x:int, x2:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains3(self:"Tree4", x:int, x2:int, x3:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains4(self:"Tree4", x:int, x2:int, x3:int, x4:int) -> bool: if self.root is None: return False else: return self.root.contains(x) class Tree5(object): root:TreeNode5 = None root2:TreeNode5 = None root3:TreeNode5 = None root4:TreeNode5 = None root5:TreeNode5 = None size:int = 0 size2:int = 0 size3:int = 0 size4:int = 0 size5:int = 0 def insert(self:"Tree5", x:int) -> object: if self.root is None: self.root = makeNode5(x, x, x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert2(self:"Tree5", x:int, x2:int) -> object: if self.root is None: self.root = makeNode5(x, x, x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert3(self:"Tree5", x:int, x2:int, x3:int) -> object: if self.root is None: self.root = makeNode5(x, x, x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert4(self:"Tree5", x:int, x2:int, x3:int, x4:int) -> object: if self.root is None: self.root = makeNode5(x, x, x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def insert5(self:"Tree5", x:int, x2:int, x3:int, x4:int, x5:int) -> object: if self.root is None: self.root = makeNode5(x, x, x, x, x) self.size = 1 else: if self.root.insert(x): self.size = self.size + 1 def contains(self:"Tree5", x:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains2(self:"Tree5", x:int, x2:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains3(self:"Tree5", x:int, x2:int, x3:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains4(self:"Tree5", x:int, x2:int, x3:int, x4:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def contains5(self:"Tree5", x:int, x2:int, x3:int, x4:int, x5:int) -> bool: if self.root is None: return False else: return self.root.contains(x) def makeNode(x: int) -> TreeNode: b:TreeNode = None b = TreeNode() b.value = x return b def makeNode2(x: int, x2: int) -> TreeNode2: b:TreeNode2 = None b2:TreeNode2 = None b = TreeNode2() b.value = x return b def makeNode3(x: int, x2: int, x3: int) -> TreeNode3: b:TreeNode3 = None b2:TreeNode3 = None b3:TreeNode3 = None b = TreeNode3() b.value = x return b def makeNode4(x: int, x2: int, x3: int, x4: int) -> TreeNode4: b:TreeNode4 = None b2:TreeNode4 = None b3:TreeNode4 = None b4:TreeNode4 = None b = TreeNode4() b.value = x return b def makeNode5(x: int, x2: int, x3: int, x4: int, x5: int) -> TreeNode5: b:TreeNode5 = None b2:TreeNode5 = None b3:TreeNode5 = None b4:TreeNode5 = None b5:TreeNode5 = None b = TreeNode5() b.value = x return b # Input parameters n:int = 100 n2:int = 100 n3:int = 100 n4:int = 100 n5:int = 100 c:int = 4 c2:int = 4 c3:int = 4 c4:int = 4 c5:int = 4 # Data t:Tree = None t2:Tree = None t3:Tree = None t4:Tree = None t5:Tree = None i:int = 0 i2:int = 0 i3:int = 0 i4:int = 0 i5:int = 0 k:int = 37813 k2:int = 37813 k3:int = 37813 k4:int = 37813 k5:int = 37813 # Crunch t = Tree() while i < n: t.insert(k) k = (k * 37813) % 37831 if i % c != 0: t.insert(i) i = i + 1 print(t.size) for i in [4, 8, 15, 16, 23, 42]: if t.contains(i): print(i)
[ "647530+Virtlink@users.noreply.github.com" ]
647530+Virtlink@users.noreply.github.com
4e8cdcafab5947bb4326836de6d15622eeff865a
28acf238f0379b032eeffa30ce5f086b73ea91bc
/colab/apps/flag/admin.py
c95db4c67661b9441b58fd065f030e07e022a3c2
[ "MIT" ]
permissive
caseywstark/colab
e6a613dbb78982689d8bd410ecc3c35f891b0195
e05293e45a657eda19d733bf05624a1613a7a9b7
refs/heads/master
2016-09-05T15:35:30.494890
2010-08-14T08:57:26
2010-08-14T08:57:26
728,947
9
1
null
null
null
null
UTF-8
Python
false
false
323
py
from django.contrib import admin from flag.models import FlaggedContent, FlagInstance class InlineFlagInstance(admin.TabularInline): model = FlagInstance extra = 0 class FlaggedContentAdmin(admin.ModelAdmin): inlines = [InlineFlagInstance] admin.site.register(FlaggedContent, FlaggedContentAdmin)
[ "casey@thestarkeffect.com" ]
casey@thestarkeffect.com
014e6f9ddeefb77f6716cb7eff213f705f3e70bd
f813eeed366b198ba4da5cf937c978125409a760
/assignment/src/process/mp.py
fffe9c9ba435c7cb77c8a2d55b4810e1d9b3fa18
[ "MIT" ]
permissive
Newtype07/RL_for_Stochastic_Control_Problems_in_Finance
4182406d64ccd56fde2899c3ee324fdf88592c39
e8f809ab864b5d360152f2284b01d730aede0f7a
refs/heads/master
2023-03-18T09:48:13.967221
2020-03-23T13:38:05
2020-03-23T13:38:05
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,710
py
# TODO: Check correctness of stationary distribution from typing import Generic, Mapping, Sequence import numpy as np from scipy import linalg # use math.fsum() instead of sum to get rid of rounding error import math from src.type_vars import S, SSf from src.utils import get_all_states # Note: if using relative path import like "from ..type_vars import S, SSf", then mp.py should be invoked using -m # option (https://napuzba.com/a/import-error-relative-no-parent/p4) class MP(Generic[S]): def __init__(self, state_transition_matrix: SSf) -> None: try: valid: bool = self.check_if_valid(state_transition_matrix) if not valid: raise ValueError() except ValueError: exit('Input is not a valid Markov Process') self.all_states: Sequence[S] = get_all_states(state_transition_matrix) self.state_transition_matrix: SSf = state_transition_matrix def check_if_valid(self, state_transition_matrix: SSf) -> bool: for s1 in state_transition_matrix: if math.fsum(state_transition_matrix[s1].values()) != 1.0: return False for s2 in state_transition_matrix[s1].keys(): if state_transition_matrix.get(s1).get(s2) < 0 or state_transition_matrix.get(s1).get(s2) > 1: return False return True def get_stationary_distribution(self) -> Mapping[S, float]: sz = len(self.all_states) P = np.zeros((sz, sz), dtype=float) # construct state transition matrix as a 2-d np array for i, s1 in enumerate(self.all_states): for j, s2 in enumerate(self.all_states): if self.state_transition_matrix.get(s1) is not None: if self.state_transition_matrix[s1].get(s2) is not None: P[i][j] = self.state_transition_matrix[s1][s2] # find a row vector v s.t. v * P = v && sum(v) == 1 by solving an overdetermined linear equation # ref: https://stephens999.github.io/fiveMinuteStats/stationary_distribution.html a = np.concatenate((np.transpose(P) - np.identity(sz), np.ones((1, sz))), axis=0) b = np.concatenate((np.zeros((sz, 1)), np.ones((1, 1))), axis=0) x = linalg.lstsq(a, b)[0] return {s: x[i][0].astype(float) for i, s in enumerate(self.all_states)} if __name__ == '__main__': state_transition_matrix = { 1: {1: 0.1, 2: 0.6, 3: 0.1, 4: 0.2}, 2: {1: 0.25, 2: 0.22, 3: 0.24, 4: 0.29}, 3: {1: 0.7, 2: 0.3}, 4: {1: 0.3, 2: 0.5, 3: 0.2} } mp_obj = MP(state_transition_matrix) print(mp_obj.all_states) print(mp_obj.get_stationary_distribution())
[ "xyzhang1@stanford.edu" ]
xyzhang1@stanford.edu
92a497f32036a0e5b6867d7696be18474a81cb68
880ec08b53270b88bf14f51ffab73a56281f96ec
/natas8.py
af394013285dddb79b5c95dcb45216b92e3105a0
[]
no_license
abbisQQ/OverTheWire-Natas-With-Python
6f68efe4bac42d90f73b28aca28477019b3abccd
f382464c292e96401d8cbc408337975c0942a929
refs/heads/master
2020-05-15T18:26:33.366408
2019-05-01T08:22:11
2019-05-01T08:22:11
182,426,587
1
0
null
null
null
null
UTF-8
Python
false
false
699
py
import requests import re import binascii import base64 username = "natas8" password = "DBfUBfqQG69KvJvJ1iAbMoIpwSNQ9bWe" #custom_headers = {"Referer":"http://natas5.natas.labs.overthewire.org/"} url = "http://%s.natas.labs.overthewire.org/" % username #custom_cookies = {"loggedin":"1"} session = requests.Session() secret = base64.b64decode(binascii.unhexlify("3d3d516343746d4d6d6c315669563362")[::-1]).decode()#make it binary, reverse it decode it from base64 then .decode() to get it as a string. response = session.post(url,data={"secret":secret, "submit":"submit"}, auth = (username, password)) content = response.text #print(content) print(re.findall('natas9 is (.*)', content)[0])
[ "noreply@github.com" ]
noreply@github.com
dc4e68ac5b189ea2e0119cedefbd33e0a5c254e5
0cce9a9d9b9da4a820e9ed5fc674d06f0be9810a
/ch10_first_exercises.py
61b5a7953658f4cd352dcef9cd381f374e582ead
[]
no_license
wbroach/python_work
3f4a85e998805f50b2400e64c5b7cbc31780b245
7e1842b317539d61bab0f04d72e71db893c865ff
refs/heads/master
2020-04-14T22:06:43.164595
2019-10-02T01:25:00
2019-10-02T01:25:00
164,151,112
0
0
null
null
null
null
UTF-8
Python
false
false
509
py
#~ file_name = 'python_can.txt' #~ with open(file_name) as file_object: #~ lines = file_object.readlines() #~ learning_summary = '' #~ for line in lines: #~ learning_summary += line.strip() + " \n" #~ print(learning_summary) file_name = 'python_can.txt' with open(file_name) as file_object: lines = file_object.readlines() for i in range(len(lines)): lines[i] = lines[i].replace('Python', 'C').strip() for line in lines: print(line)
[ "someone@someplace.com" ]
someone@someplace.com
9af2dbebb6239c53dc4023190a35f2b38e6f910c
e34a0695b777d9ea738917fe1c20d541930a0e0c
/Plots/viscotity.py
74d2bce9012ca2019f5de81f5df154729df129ca
[]
no_license
MikeVolk/RockPyV3
cc67dbd21d52fc966362fdd458574eb06f10e522
310693dbb2de30b3041850f5c9e98c528a5ce295
refs/heads/master
2021-05-27T21:34:50.136925
2014-09-12T16:00:26
2014-09-12T16:00:26
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,168
py
__author__ = 'mike' def plot_visc(visc_obj, ax, norm_factor=1, out='show', folder=None, name='output.pdf', plt_opt=None): ''' Main plotting of a hysteresis. :param visc_obj: hysteresis object :param ax: pyplot.ax object :param norm_factor: normalization of the y-data :param out: choice of: - 'show' : shows the plot - 'rtn' : returns the plot - 'save' : saves a pdf of the plot. a folder has to be specified. Name can be specified :param folder: str where the pdf should be saved :param name: str name of the pdf implemented plot_options: color linestyle markerstyle alpha ''' if not plt_opt: plt_opt = {} # ax.axhline(0, color='#555555') # 0 line horizontally # ax.axvline(0, color='#555555') # 0 line vertically # color_cycle = ax._get_lines.color_cycle # # color = popt.get('color', next(color_cycle)) # ls = popt.get('linestyle', '-') # markerstyle = popt.get('markerstyle', 'x') # alpha = popt.get('alpha', 1.0) std, = ax.plot(visc_obj.times, visc_obj.moments / norm_factor, label='t',**plt_opt) if out == 'show': plt.show() if out == 'rtn': return ax if out == 'save': if folder is not None: plt.savefig(folder + self.samples[0].name + '_' + name, dpi=300) def plot_log_visc(visc_obj, ax, norm_factor=1, out='show', folder=None, name='output.pdf', plt_opt={}): ''' Main plotting of a hysteresis. :param visc_obj: hysteresis object :param ax: pyplot.ax object :param norm_factor: normalization of the y-data :param out: choice of: - 'show' : shows the plot - 'rtn' : returns the plot - 'save' : saves a pdf of the plot. a folder has to be specified. Name can be specified :param folder: str where the pdf should be saved :param name: str name of the pdf ''' # ax.axhline(0, color='#555555') # 0 line horizontally # ax.axvline(0, color='#555555') # 0 line vertically std, = ax.plot(visc_obj.log_times, visc_obj.moments / norm_factor, label='log(t)', **plt_opt) if out == 'show': plt.show() if out == 'rtn': return ax if out == 'save': if folder is not None: plt.savefig(folder + self.samples[0].name + '_' + name, dpi=300) def add_label(visc_object, ax=None, log=True): if visc_object.norm is None: ax.set_ylabel('Magnetic Moment $Am^2$') if visc_object.norm == 'mass': ax.set_ylabel('Magnetic Moment $Am^2/kg$') else: ax.set_ylabel('Magnetic Moment normalized') if log: ax.set_xlabel('log(time [$s$])') else: ax.set_xlabel('time [$s$]') return ax def add_formula_text(visc_obj,ax = None, norm_factor=1): text = '$M = %.3e \cdot x %.3e \; R^2 = %.3e \; \sigma = %.3e$' % (visc_obj.intercept, visc_obj.slope, visc_obj.r_value**2, visc_obj.std_err) ax.text(0, 0.01, text, horizontalalignment='left', verticalalignment='bottom', transform=ax.transAxes, # fontsize=8, ) return ax
[ "grossstadtlegende@gmail.com" ]
grossstadtlegende@gmail.com
3e6d647b241ef033118d7f42d35487ab7325d571
413099eb18e622c6dcba4b2f07df83d6dca5d509
/myproject/api/lebov2/getPendingOrdersByCarPlateNo.py
580aa0bd3f9532a221515779c3dfcc1649c7a109
[]
no_license
chennuan/test
0b97d761abe6723374775695c4352ed26b8031c3
598b732a738ba5ff49ee0ceba93c2b719e8d8d6c
refs/heads/master
2022-12-20T19:19:08.676525
2020-10-15T04:21:47
2020-10-15T04:21:47
299,646,465
0
0
null
null
null
null
UTF-8
Python
false
false
565
py
#-*- coding: UTF-8 -*- class GetPendingOrdersByCarPlateNo: def __init__(self): self.ServiceName = "GetPendingOrdersByCarPlateNo" self.method = "get" self.header = { "Content-Type": "application/json" } self.body = { "userId": "157811", "isFlag": 0, "siteId": 1 } self.expect = { "code": 200, "data": { "amount": 0 }, "success": "true", "message": "待付费订单信息" }
[ "chennuan478440602@163.com" ]
chennuan478440602@163.com
d7b54e76bb7ec19036f88a2102a018574ade3d64
f638dad156f2dff153d1aaf5b5a60a9fde85ec19
/run_get_data.py
174c2e9679c4473f309b88423fe19ba489a98438
[]
no_license
eyelash500/2021_ironman_fintech
862ea29d560ba9eac48ffc4fabb0a0e912d4d339
fa895f8c727449ac5df866d5ee8444b4ce8a2e45
refs/heads/master
2023-08-23T03:40:58.623071
2021-09-30T15:48:32
2021-09-30T15:48:32
402,106,300
0
0
null
null
null
null
UTF-8
Python
false
false
1,709
py
from datetime import datetime from legal_person import legal_daily_future_option from market_info import daily_market_info from stock_transaction import stock_transaction from fin_signal import fin_signal class daily_transaction: """Save the daily transaction info to database.""" def save_to_db(self): print(f"=Start: {datetime.now().strftime('%H%M%S')}") legal_daily = legal_daily_future_option() market_data = daily_market_info() stock_trans_data = stock_transaction() r = legal_daily.get_and_save() if r is False: print(f"error:{legal_daily.__str__}") r = market_data.get_and_save() if r is False: print(f"error:{market_data.__str__}") r = stock_trans_data.get_and_save() if r is False: print(f"error:{stock_trans_data.__str__}") print(f"=Finish: {datetime.now().strftime('%H%M%S')}") class signal: """Show the signal""" def __init__(self) -> None: self.fin_signal = fin_signal() self.fin_signal._get_db_data() # get the row data def show_signal(self) -> None: """Create and show all the signal""" signal_list = self.fin_signal.get_signal() self._show_singnal(signal_list) def _show_singnal(self, signal_list) -> None: """Do showing the signal function""" print(f"時間:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") print("==訊號燈==") for title, signal in signal_list: print(f"* {title}: {signal}") """實作測試""" # 匯入資料 worker = daily_transaction() worker.save_to_db() # 訊號燈印出 signal = signal() signal.show_signal()
[ "eyelash.94500@gmail.com" ]
eyelash.94500@gmail.com
d2dded48a1d604bda8edaeb28fbb63865106133a
e406487b60cf9a220c4164a2e6f6e612ec98843f
/mall/apps/goods/migrations/0002_auto_20190117_1555.py
7fdd947712c4473763b67eca18cb03688ec0a703
[]
no_license
L-huihui/duoduo
3d7caad17664b045882043afacb3dcbc13008fb2
16bb64e1216a82a35867516e4351dffe68247415
refs/heads/master
2020-04-18T05:49:21.281388
2019-01-25T01:44:29
2019-01-25T01:44:29
167,293,055
0
0
null
null
null
null
UTF-8
Python
false
false
1,655
py
# -*- coding: utf-8 -*- # Generated by Django 1.11.11 on 2019-01-17 07:55 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('goods', '0001_initial'), ] operations = [ migrations.RenameField( model_name='brand', old_name='updata_time', new_name='update_time', ), migrations.RenameField( model_name='goods', old_name='updata_time', new_name='update_time', ), migrations.RenameField( model_name='goodscategory', old_name='updata_time', new_name='update_time', ), migrations.RenameField( model_name='goodschannel', old_name='updata_time', new_name='update_time', ), migrations.RenameField( model_name='goodsspecification', old_name='updata_time', new_name='update_time', ), migrations.RenameField( model_name='sku', old_name='updata_time', new_name='update_time', ), migrations.RenameField( model_name='skuimage', old_name='updata_time', new_name='update_time', ), migrations.RenameField( model_name='skuspecification', old_name='updata_time', new_name='update_time', ), migrations.RenameField( model_name='specificationoption', old_name='updata_time', new_name='update_time', ), ]
[ "xwp_fullstack@163.com" ]
xwp_fullstack@163.com
41a4b893fccb6fadb151d7d01fe97d8919a884e6
4a7b9351d61c3d815306631eada63d020275e7ec
/tests/test_exercise_5_4.py
51850a385dad9f36801902667e84094d26f59598
[]
no_license
Imperial-MATH50009/exercises-week-5
d95beecd3f7ce2bdeafb8228723c731064217eae
70f0d741aba2abe14f1c021dd3e4951a97089d45
refs/heads/main
2023-02-24T12:45:09.375455
2021-02-04T20:49:30
2021-02-04T20:49:30
336,022,669
0
1
null
null
null
null
UTF-8
Python
false
false
1,020
py
import pytest import numpy as np try: from adt_examples.fibonacci import Fib except ImportError: pass def test_fib_import(): from adt_examples.fibonacci import Fib def test_fib_iterator(): x = Fib() assert hasattr(x, '__iter__'), \ "Fib has no __iter__ special method." def test_fib_next(): x = Fib() assert hasattr(x, '__next__'), \ "Fib has no __next__ special method." @pytest.mark.parametrize("n, fib_lst", [ (5, [1, 2, 3, 5, 8]), (10, [1, 2, 3, 5, 8, 13, 21, 34, 55, 89]), (15, [1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987]), ]) def test_fib_values(n, fib_lst): x = Fib() test_lst = [next(x) for i in range(n)] assert np.array_equal(test_lst, fib_lst), \ "fibonacci sequences are not what is expected" @pytest.mark.timeout(30e0, method='signal') @pytest.mark.parametrize("size,", [ (1e7), (1e11), ]) def test_fibonacci_complexity(size): for n in Fib(): if n >= size: break pass
[ "noreply@github.com" ]
noreply@github.com
0e36b36487f76e86833e7dc2865f7971e3c05288
38f1a7106c78188b744026c198ed791c5faea914
/testssts.py
8270cf51654ec01215fc8a7080ac14e4b2008111
[]
no_license
kemccusker/pyscripts
19b50bb84a8d91ad1500ad883585f2d65bd27c84
1e6373f04355a2946a21fd3d3e613434f066c803
refs/heads/master
2021-01-25T15:15:07.083435
2017-11-28T05:52:00
2017-11-28T05:52:00
19,090,355
0
0
null
null
null
null
UTF-8
Python
false
false
4,173
py
import numpy as np import numpy.ma as ma import scipy as sp # scientific python import scipy.stats import matplotlib.pyplot as plt import platform as platform import cccmaplots as cplt import constants as con import cccmautils as cutl import cccmaNC as cnc cplt = reload(cplt) con = reload(con) cutl = reload(cutl) cnc = reload(cnc) """ Note, other testing of this is done in compareOBS.py when plotseacycmag=1 created 4/23/2014 """ checkpert1s=0 # check new pert1 BC against original checknewbcs=1 # check BCs for new runs: rcp85 2022-2032, etc timeperp = '2022-2032' #timeperp = '2042-2052' plat = platform.system() if plat == 'Darwin': # means I'm on my mac basepath2 = '/Volumes/MyPassport1TB/DATA/CanSISE/' basepath = '/Users/kelly/CCCma/CanSISE/BoundaryConditionFiles/' # @@ not sure else: # on linux workstation in Vic basepath = '/home/rkm/work/BCs/' if checkpert1s: # New Pert1 dataset that checks for open water colder than 271.2 pert1newf = 'GTfrzchkhistoricalrcp452002-2012_BC_CanESM2_historical_1979-1989_1870010100-2010120100.nc' lat = cnc.getNCvar(pert1newf,'lat') lon = cnc.getNCvar(pert1newf,'lon') pert1n = cnc.getNCvar(pert1newf,'GT') pert1n = pert1n[0:12,...] # original BC files for PERT1. I expected that the ssts would be below freezing in some places # where SICN was gone in PERT1 but not control. pert1f = '/home/rkm/work/BCs/CanESM2/GT_BC_CanESM2_historical1979-1989_1870010100-2011020100.nc' pert1=cnc.getNCvar(pert1f,'GT') pert1 = pert1[0:12,...] pert1sicf = '/home/rkm/work/BCs/CanESM2/SICN_BC_CanESM2_historical2002-2012_1870010100-2011020100.nc' pert1sic = cnc.getNCvar(pert1sicf,'SICN') pert1sic = pert1sic[0:12,...] landmask = con.get_t63landmask() landmask = np.tile(landmask,(12,1,1)) #pert1n[pert1n<271.2] = -1000 # @@ just for testing pert1n = ma.masked_where(landmask==-1,pert1n) pert1n = ma.masked_where(pert1sic>.15,pert1n) #pert1[pert1<271.2] = -1000 # @@ just for testing pert1 = ma.masked_where(landmask==-1,pert1) pert1 = ma.masked_where(pert1sic>.15,pert1) #cplt.map_allmonths(pert1n,lat,lon,cmin=271.2-35,cmax=271.2+35,cmap='blue2red_20',type='nh',conts=[271.2],climo=1,lmask=1) #cplt.map_allmonths(pert1,lat,lon,cmin=271.2-35,cmax=271.2+35,cmap='blue2red_20',type='nh',conts=[271.2],climo=1,lmask=1) cplt.map_allmonths(pert1n-pert1,lat,lon,cmin=-.1,cmax=.1,cmap='blue2red_20',type='nh',climo=1) #cplt.map_allmonths(landmask,lat,lon,cmap='blue2red_20',type='nh',climo=1) if checknewbcs: deni = 913 # density of ice if timeperp=='2022-2032': cming = -5; cmaxg = 5 # GT cminc = -.4; cmaxc = .4 # SI concentration cmint = -.7*deni; cmaxt = .7*deni # SI thickness else: cming = -6; cmaxg = 6 cminc = -.6; cmaxc = .6 # SI concentration cmint = -.8*deni; cmaxt = .8*deni # SI thickness ctlfile = basepath + 'CanESM2/GT_BC_CanESM2_historical_1979-1989_1870010100-2010120100.nc' pertfile = basepath + 'CanESM2/GTadjusted_BC_CanESM2_rcp85_' + timeperp + '_1870010100-2010120100_abs10thresh.nc' lat = cnc.getNCvar(ctlfile,'lat') lon = cnc.getNCvar(ctlfile,'lon') fldc = cnc.getNCvar(ctlfile,'GT') fldp = cnc.getNCvar(pertfile,'GT') #cplt.map_allmonths(fldp-fldc,lat,lon,cmin=cming,cmax=cmaxg,cmap='blue2red_20',type='nh') ctlfile = basepath + 'CanESM2/SICN_BC_CanESM2_historical_1979-1989_1870010100-2010120100.nc' pertfile = basepath + 'CanESM2/SICN_BC_CanESM2_rcp85_' + timeperp + '_1870010100-2010120100.nc' fldc = cnc.getNCvar(ctlfile,'SICN') fldp = cnc.getNCvar(pertfile,'SICN') #cplt.map_allmonths(fldp-fldc,lat,lon,cmin=cminc,cmax=cmaxc,cmap='red2blue_w20',type='nh') ctlfile = basepath + 'CanESM2/SIC_BC_CanESM2_historical_1979-1989_1870010100-2010120100.nc' pertfile = basepath + 'CanESM2/SIC_BC_CanESM2_rcp85_' + timeperp + '_1870010100-2010120100.nc' fldc = cnc.getNCvar(ctlfile,'SIC') fldp = cnc.getNCvar(pertfile,'SIC') cplt.map_allmonths(fldp-fldc,lat,lon,cmin=cmint,cmax=cmaxt,cmap='red2blue_w20',type='nh')
[ "kellymccusker@gmail.com" ]
kellymccusker@gmail.com
f2500f31743a20b0649290db590dad8676fbb1b2
e877cb0a94e025ff0f544ac69bb7479b303d6bd9
/arithmetic_arranger.py
f9e43423f0076d2991b9f27ff519bdf478c82d24
[]
no_license
Anunaya07/boilerplate-arithmetic-formatter
60d41d1656e020654851e9917e7f60c54734cf6c
bff228c5e3f4583ba36fcc233de0e7101867cc2c
refs/heads/master
2023-07-11T12:18:49.758433
2021-08-19T05:24:40
2021-08-19T05:24:40
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,824
py
def arithmetic_arranger(problems,ans=False): if len(problems)>5: return "Error: Too many problems." first=[] last=[] operators=[] max_num=[] for i in problems: if not('+' in i or '-' in i): return "Error: Operator must be '+' or '-'." temp_list=i.split(' ') if not temp_list[0].isdigit(): return "Error: Numbers must only contain digits." if not temp_list[2].isdigit(): return "Error: Numbers must only contain digits." if len(temp_list[0])>4: return "Error: Numbers cannot be more than four digits." if len(temp_list[2])>4: return "Error: Numbers cannot be more than four digits." first+=[temp_list[0]] last+=[temp_list[2]] operators+=[temp_list[1]] max_num+=[max(len(temp_list[0]),len(temp_list[2]))] return_str='' for i in range(len(max_num)): return_str+=" "+" "*(max_num[i]-len(first[i]))+first[i] return_str+=' '*4 return_str=return_str[:len(return_str)-4] return_str+='\n' for i in range(len(max_num)): return_str+=f"{operators[i]} "+" "*(max_num[i]-len(last[i]))+last[i] return_str+=' '*4 return_str=return_str[:len(return_str)-4] return_str+='\n' for i in range(len(max_num)): return_str+="-"*(2+max_num[i]) return_str+=' '*4 return_str=return_str[:len(return_str)-4] if ans: return_str+='\n' for i in range(len(problems)): if operators[i]=='+': answer=str(int(first[i])+int(last[i])) else: answer=str(int(first[i])-int(last[i])) length=len(answer) max_num[i]+=2 return_str+=' '*(max_num[i]-length)+answer return_str+=' '*4 return_str=return_str[:len(return_str)-4] return return_str #return arranged_problems
[ "coderxxyay@gmail.com" ]
coderxxyay@gmail.com
e804b42788019287fe661914728cefe9012a97e4
b78309f479960ef9c14c06dc14fb2bd1c5fbd8c5
/test_module/file_read_write/file.py
6dea48114001caa1dc5972a327b3aacaa1ec7a16
[]
no_license
p2a8t4a5a/learningnotes
ba8bbfcf5b44b7493664fd739ef09b8bb6fdf474
88a78cf4f423bd2da877b6144fd2c02b6de01b69
refs/heads/master
2022-03-04T19:32:10.134577
2019-09-29T07:31:01
2019-09-29T07:31:01
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,793
py
#! /usr/bin/python # -*- coding:utf-8 -*- import fcntl import stat import os import sys import time def file_test(): file_path='data.in' try: fd=os.open(file_path,os.O_RDWR|os.O_CREAT, stat.S_IRUSR | stat.S_IWUSR) except OSError as e: print 15,e sys.exit(1) # 如果执行exec时,关闭fd. # 因为当执行exec时,fork时父进程或者子程序就被完全替换掉。 # 但是你的fd没关掉,特别时有些复杂情况不适合手动关掉。 # 通过此方法会自动帮你关闭fd flags=fcntl.fcntl(fd,fcntl.F_GETFD) assert flags!=-1 flags|=fcntl.FD_CLOEXEC r=fcntl.fcntl(fd,fcntl.F_SETFD,flags) assert r!=-1 try: # 互斥锁定 #无法建立锁定时,此操作可不被阻断,马上返回进程 # os.SEEK_SET - 文件的开头, 可以用 0 代替 fcntl.lockf(fd,fcntl.LOCK_EX|fcntl.LOCK_NB, 0,0,os.SEEK_SET) except IOError as e: print 31,e sys.exit(1) return -1 #清空 os.ftruncate(fd,0) os.write(fd,bytes('123456')) return 0 def normal_file(): f=open('data.in','w') f.write('normal') f.close() def test_without_lock(): fd=os.open('data.in',os.O_RDWR|os.O_APPEND|os.O_CREAT) for i in range(3): pid=os.fork() if pid==0: t=i break else: t=4 try: # 同一个进程才有效 非强制 fcntl.lockf(fd, fcntl.LOCK_EX | fcntl.LOCK_NB, 0, 0, os.SEEK_SET) except IOError: print 'error' sys.exit(0) os.write(fd,bytes(str(t)+' yaoge'+'\n')) os.close(fd) if __name__ == "__main__": test_without_lock() # normal_file() # file_test()
[ "yde@dsjcj.com" ]
yde@dsjcj.com
4a0bab4d89d06934ab421a7ac688115a241fda15
a69e2baf00a5c7dd0633d7c279324d2815701f63
/core/views.py
135cb1c6b530d0814788432ae0f78ca4a4619ba2
[]
no_license
lac617a/ink-web
b3dc2a18b907c5b945c124bbe5070629e31bac54
09aca2e5e1098d91f28e10a9503a7a783c81ab63
refs/heads/master
2023-05-31T13:37:13.434335
2021-06-29T20:24:44
2021-06-29T20:24:44
369,619,370
0
0
null
null
null
null
UTF-8
Python
false
false
2,542
py
from django.shortcuts import render, redirect from django.conf import settings from django.core.mail import send_mail from .models import Computer, Printer # Create your views here. def windowMain(request): if request.method == 'POST': subject = request.POST.get('subject') mail = request.POST.get('mail') message = request.POST.get('content') + f' |Remitente {mail}' gmail = settings.EMAIL_HOST_USER email_from = gmail recipent_list = [gmail] send_mail(subject,message,email_from,recipent_list) return redirect('/') return render(request,'home.html') def termsAndConditions(request): return render(request,'termsAndCondition.html') def maintenance(request): return render(request,'maintenance/maintenance.html') def maintenancePreventive(request): return render(request,'maintenance/preventive/preventive.html') def maintenanceCorrective(request): return render(request,'maintenance/corrective/corrective.html') def maintenancePreventiveComputers(request): queryset = Computer.objects.all() return render(request,'maintenance/preventive/preventiveComputer/preventiveComputer.html',{'qs':queryset}) def maintenancePreventiveAllComputers(request,slug): queryset = Computer.objects.filter(name=slug) return render(request,'maintenance/preventive/preventiveComputer/preventiveAll.html',{'qs':queryset}) def maintenancePreventivePrinters(request): queryset = Printer.objects.all() return render(request,'maintenance/preventive/preventivePrinter/preventivePrinter.html',{'qs':queryset}) def maintenancePreventiveAllPrinters(request,slug): queryset = Printer.objects.filter(name=slug) return render(request,'maintenance/preventive/preventivePrinter/preventiveAll.html',{'qs':queryset}) def maintenanceCorrectiveComputers(request): queryset = Computer.objects.all() return render(request,'maintenance/corrective/correctiveComputer/correctiveComputer.html',{'qs':queryset}) def maintenanceCorrectiveAllComputers(request,slug): queryset = Computer.objects.filter(name=slug) return render(request,'maintenance/corrective/correctiveComputer/correctiveAll.html',{'qs':queryset}) def maintenanceCorrectivePrinters(request): queryset = Printer.objects.all() return render(request,'maintenance/corrective/correctivePrinter/correctivePrinter.html',{'qs':queryset}) def maintenanceCorrectiveAllPrinters(request,slug): queryset = Printer.objects.filter(name=slug) return render(request,'maintenance/corrective/correctivePrinter/correctiveAll.html',{'qs':queryset})
[ "botlacrita617@gmail.com" ]
botlacrita617@gmail.com
b72ad75306f31160948715d6656aedb45e1792c7
e2e993962d6e5e30905d13f0532acdac9302c84b
/HTL.tab/Test.panel/Test.pushbutton/keyman/keyman/keys/models.py
a35c8dcb63e577c0174f8f38772822ae3ef1b000
[ "MIT" ]
permissive
htlcnn/pyrevitscripts
a1777fa0ba36003443d95e0f9fbbcadc4ffa5fe7
b898a3a5e8d212570254772ae314f343498b1398
refs/heads/master
2021-01-01T20:08:31.001558
2018-01-11T06:44:26
2018-01-11T06:44:26
98,773,971
1
2
null
null
null
null
UTF-8
Python
false
false
300
py
from django.db import models from django.core.urlresolvers import reverse class Software(models.Model): name = models.CharField(max_length=200) def __unicode__(self): return self.name def get_absolute_url(self): return reverse('software_edit', kwargs={'pk': self.pk})
[ "hoangthanhlong@gmail.com" ]
hoangthanhlong@gmail.com
2902abb4e7312b37efda0ba597f2fe4811f7f057
1122dce58d53c39b45b20c408b666dae467af24f
/localsettings.example.py
846a32478e59f316365445d3e9931074fcd7cea0
[ "BSD-3-Clause", "AAL" ]
permissive
cyrildoussin/Django-Socialauth
2b3af0ef9e6000933f244906044600d14ffd6fc7
a92fe95896b4c9f49d48e0aaac15c72029287cde
refs/heads/master
2021-01-18T10:56:08.177511
2009-10-20T07:34:34
2009-10-20T07:34:34
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,379
py
# Put your local settings here. This will override corresponding settings in settings.py. # PLEASE DO NOT CHECK IN THIS FILE. ADMINS = ( ('Shabda', 'shabda@uswaretech.com'), ) # This is for dev environment. Display debug messages. DEBUG = True # site ID SITE_ID = 1 SITE_NAME = 'foobar' DATABASE_ENGINE = 'sqlite3' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'ado_mssql'. DATABASE_NAME = 'data.db' # Or path to database file if using sqlite3. DATABASE_USER = '' # Not used with sqlite3. DATABASE_PASSWORD = '' # Not used with sqlite3. DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. OPENID_REDIRECT_NEXT = '/accounts/openid/done/' OPENID_SREG = {"requred": "nickname, email", "optional":"postcode, country", "policy_url": ""} TWITTER_CONSUMER_KEY = '' TWITTER_CONSUMER_SECRET = '' FACEBOOK_API_KEY = '' FACEBOOK_API_SECRET = '' AUTHENTICATION_BACKENDS = ('django.contrib.auth.backends.ModelBackend', 'socialauth.auth_backends.OpenIdBackend', 'socialauth.auth_backends.TwitterBackend', 'socialauth.auth_backends.FacebookBackend', ) LOGIN_REDIRECT_URL = '/login/done/'
[ "shabda@uswaretech.com" ]
shabda@uswaretech.com
df38823587cc9e24c51012ac241656d65ad08683
5600369f072352d9b6103680a6288fe22aa956b5
/dynamic_inventory.py
15affb3391d370e6afac24c0a3e43f26adda0c70
[]
no_license
narayudu/ansible-dynamic-inventory-mysql
b0de6c263ba91018c0a8af889dd4c3f6b9766288
a2e7b7a178b3e864c50bb0f68390d34bcb808515
refs/heads/master
2020-03-27T04:58:50.862106
2018-01-11T11:37:03
2018-01-11T11:37:03
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,486
py
#!/usr/bin/env python ''' Example custom dynamic inventory script for Ansible, in Python. ''' import os import sys import argparse import mysql.connector as mariadb from collections import defaultdict try: import json except ImportError: import simplejson as json class DynamicInventory(object): def __init__(self, args): self.inventory = {} self.args = args self.mariadb_connection = mariadb.connect(user='ansible', password='ansible', database='inventory') self.cursor = self.mariadb_connection.cursor(dictionary=True) self.os = [] self.osgroup = [] self.result = {} # Called with `--list`. if self.args.list: self.inventory = self.dynamic_inventory() # If no groups or vars are present, return an empty inventory. else: self.inventory = self.empty_inventory() print json.dumps(self.inventory); # Example inventory for testing. def dynamic_inventory(self): self.cursor.execute("select h.name as hostname, h.os, g.name as groupname from hosts as h, groups as g where h.group_id = g.id") result_set = self.cursor.fetchall() # Normalize data based on db data. result_dict = lambda: defaultdict(result_dict) results_group = result_dict() results_os = result_dict() for row in result_set: results_group[row['groupname']][row['hostname']] = row['hostname'] results_os[row['os']][row['hostname']] = row['hostname'] # For groupname wise/all groups all_hostlist = [] for group in results_group: group_hostlist = [] for host in results_group[group]: group_hostlist.append(host) all_hostlist.append(host) self.result.update({group : group_hostlist}) self.result.update({'all' : list(set(all_hostlist))}) # For OS groups for os in results_os: os_hostlist = [] for host in results_os[os]: os_hostlist.append(host) self.result.update({os : os_hostlist}) return self.result # Empty inventory for testing. def empty_inventory(self): return {'_meta': {'hostvars': {}}} def __del__(self): self.cursor.close() self.mariadb_connection.close() # Main function def main(): # Read command line args parser = argparse.ArgumentParser() parser.add_argument('--list', action = 'store_true') args = parser.parse_args() # Get the inventory. DynamicInventory(args) if __name__ == '__main__': main()
[ "ec2-user@ip-10-0-0-121.us-west-2.compute.internal" ]
ec2-user@ip-10-0-0-121.us-west-2.compute.internal
b225f0c7ef6e3fb48db1bdd54f1a91178808953f
94b9eb6a3afec277e0418aed2274da66774e37c0
/fm_receiver.py
921b3c6027a8d430ba2191f643f789e212aacea3
[]
no_license
Hesham-Gaber/one
c12febb7e00de0c5f7bd1eeba9ba65089c4eec77
8872a3ace1940768aa5f0f8f7239dd3eb492cf62
refs/heads/master
2020-03-11T00:18:14.125034
2018-04-16T00:02:46
2018-04-16T00:02:46
129,660,451
0
0
null
null
null
null
UTF-8
Python
false
false
7,384
py
#!/usr/bin/env python2 # -*- coding: utf-8 -*- ################################################## # GNU Radio Python Flow Graph # Title: Lesson 3 - FM Rx # Author: John Malsbury - Ettus Research # Description: Working with the USRP! # Generated: Mon Apr 16 01:15:35 2018 ################################################## if __name__ == '__main__': import ctypes import sys if sys.platform.startswith('linux'): try: x11 = ctypes.cdll.LoadLibrary('libX11.so') x11.XInitThreads() except: print "Warning: failed to XInitThreads()" from gnuradio import analog from gnuradio import audio from gnuradio import blocks from gnuradio import eng_notation from gnuradio import filter from gnuradio import gr from gnuradio import uhd from gnuradio import wxgui from gnuradio.eng_option import eng_option from gnuradio.fft import window from gnuradio.filter import firdes from gnuradio.wxgui import fftsink2 from gnuradio.wxgui import forms from grc_gnuradio import wxgui as grc_wxgui from optparse import OptionParser import time import wx class fm_receiver(grc_wxgui.top_block_gui): def __init__(self): grc_wxgui.top_block_gui.__init__(self, title="Lesson 3 - FM Rx") _icon_path = "/usr/share/icons/hicolor/32x32/apps/gnuradio-grc.png" self.SetIcon(wx.Icon(_icon_path, wx.BITMAP_TYPE_ANY)) ################################################## # Variables ################################################## self.samp_rate = samp_rate = 4e6 self.rx_gain = rx_gain = 15 self.lpf_decim = lpf_decim = 20 self.freq = freq = 90.1e6 self.audio_samp_rate = audio_samp_rate = 96e3 ################################################## # Blocks ################################################## _rx_gain_sizer = wx.BoxSizer(wx.VERTICAL) self._rx_gain_text_box = forms.text_box( parent=self.GetWin(), sizer=_rx_gain_sizer, value=self.rx_gain, callback=self.set_rx_gain, label='rx_gain', converter=forms.float_converter(), proportion=0, ) self._rx_gain_slider = forms.slider( parent=self.GetWin(), sizer=_rx_gain_sizer, value=self.rx_gain, callback=self.set_rx_gain, minimum=0, maximum=30, num_steps=100, style=wx.SL_HORIZONTAL, cast=float, proportion=1, ) self.Add(_rx_gain_sizer) self.notebook_0 = self.notebook_0 = wx.Notebook(self.GetWin(), style=wx.NB_TOP) self.notebook_0.AddPage(grc_wxgui.Panel(self.notebook_0), "RF") self.notebook_0.AddPage(grc_wxgui.Panel(self.notebook_0), "Audio") self.Add(self.notebook_0) self._freq_text_box = forms.text_box( parent=self.GetWin(), value=self.freq, callback=self.set_freq, label='freq', converter=forms.float_converter(), ) self.Add(self._freq_text_box) self.wxgui_fftsink2_1 = fftsink2.fft_sink_f( self.notebook_0.GetPage(1).GetWin(), baseband_freq=0, y_per_div=10, y_divs=10, ref_level=0, ref_scale=2.0, sample_rate=samp_rate/lpf_decim, fft_size=1024, fft_rate=15, average=False, avg_alpha=None, title="FFT Plot", peak_hold=False, ) self.notebook_0.GetPage(1).Add(self.wxgui_fftsink2_1.win) self.wxgui_fftsink2_0 = fftsink2.fft_sink_c( self.notebook_0.GetPage(0).GetWin(), baseband_freq=freq, y_per_div=10, y_divs=10, ref_level=0, ref_scale=2.0, sample_rate=samp_rate, fft_size=1024, fft_rate=15, average=False, avg_alpha=None, title="FFT Plot", peak_hold=False, ) self.notebook_0.GetPage(0).Add(self.wxgui_fftsink2_0.win) self.uhd_usrp_source_0 = uhd.usrp_source( ",".join(("", "")), uhd.stream_args( cpu_format="fc32", channels=range(1), ), ) self.uhd_usrp_source_0.set_samp_rate(samp_rate) self.uhd_usrp_source_0.set_center_freq(freq, 0) self.uhd_usrp_source_0.set_gain(rx_gain, 0) self.uhd_usrp_source_0.set_antenna("TX/RX", 0) self.low_pass_filter_0 = filter.fir_filter_ccf(lpf_decim, firdes.low_pass( 1, samp_rate, 100e3, 10e3, firdes.WIN_HAMMING, 6.76)) self.gr_wavfile_sink_0 = blocks.wavfile_sink("fm_record.wav", 1, int(audio_samp_rate), 8) self.blks2_wfm_rcv_0 = analog.wfm_rcv( quad_rate=samp_rate/lpf_decim, audio_decimation=1, ) self.blks2_rational_resampler_xxx_0 = filter.rational_resampler_fff( interpolation=96, decimation=1, taps=None, fractional_bw=None, ) self.audio_sink_0 = audio.sink(int(audio_samp_rate), "", True) ################################################## # Connections ################################################## self.connect((self.blks2_rational_resampler_xxx_0, 0), (self.audio_sink_0, 0)) self.connect((self.blks2_rational_resampler_xxx_0, 0), (self.gr_wavfile_sink_0, 0)) self.connect((self.blks2_wfm_rcv_0, 0), (self.blks2_rational_resampler_xxx_0, 0)) self.connect((self.blks2_wfm_rcv_0, 0), (self.wxgui_fftsink2_1, 0)) self.connect((self.low_pass_filter_0, 0), (self.blks2_wfm_rcv_0, 0)) self.connect((self.uhd_usrp_source_0, 0), (self.low_pass_filter_0, 0)) self.connect((self.uhd_usrp_source_0, 0), (self.wxgui_fftsink2_0, 0)) def get_samp_rate(self): return self.samp_rate def set_samp_rate(self, samp_rate): self.samp_rate = samp_rate self.low_pass_filter_0.set_taps(firdes.low_pass(1, self.samp_rate, 100e3, 10e3, firdes.WIN_HAMMING, 6.76)) self.uhd_usrp_source_0.set_samp_rate(self.samp_rate) self.wxgui_fftsink2_0.set_sample_rate(self.samp_rate) self.wxgui_fftsink2_1.set_sample_rate(self.samp_rate/self.lpf_decim) def get_rx_gain(self): return self.rx_gain def set_rx_gain(self, rx_gain): self.rx_gain = rx_gain self._rx_gain_slider.set_value(self.rx_gain) self._rx_gain_text_box.set_value(self.rx_gain) self.uhd_usrp_source_0.set_gain(self.rx_gain, 0) def get_lpf_decim(self): return self.lpf_decim def set_lpf_decim(self, lpf_decim): self.lpf_decim = lpf_decim self.wxgui_fftsink2_1.set_sample_rate(self.samp_rate/self.lpf_decim) def get_freq(self): return self.freq def set_freq(self, freq): self.freq = freq self.uhd_usrp_source_0.set_center_freq(self.freq, 0) self.wxgui_fftsink2_0.set_baseband_freq(self.freq) self._freq_text_box.set_value(self.freq) def get_audio_samp_rate(self): return self.audio_samp_rate def set_audio_samp_rate(self, audio_samp_rate): self.audio_samp_rate = audio_samp_rate def main(top_block_cls=fm_receiver, options=None): tb = top_block_cls() tb.Start(True) tb.Wait() if __name__ == '__main__': main()
[ "passhesham@hotmail.com" ]
passhesham@hotmail.com
035e65f319bbdefadc24d8b1e15a14d4ff41e0f3
128c8882b3199cb4d0682b363c4ce5725708bf42
/project/wsgi.py
6787e3fee8a55aab479708746bbccd0f2a459471
[]
no_license
djangouroki/7less_foreign_key
c4ad7e94d91ec57466d2fa10baa43714546815bb
8d99c5b7e113f97f4860bf37d5808ffdcd5ba6c7
refs/heads/master
2023-04-23T04:44:59.410194
2021-04-25T10:14:44
2021-04-25T10:14:44
359,429,436
1
0
null
null
null
null
UTF-8
Python
false
false
396
py
""" WSGI config for project project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings.prod') application = get_wsgi_application()
[ "django.uroki@mail.ru" ]
django.uroki@mail.ru
10a0a9b602f69b8db8e93992dd0a42bf6c4fb2b5
9994ceceed154e3b07f3b4f9881d83af7fcea876
/run_manyLC.py
a777297b39dbb1f24497cfbc3b0d0274ea76b488
[]
no_license
rahuldave/time-series-feats
7c908ec24c7799c69a530e940d247c454bc12a2a
c91fdeb7795faf4eb06bc7340f659f4dc00cd153
refs/heads/master
2021-01-21T09:34:24.154469
2014-11-24T19:46:47
2014-11-24T19:46:47
27,090,036
0
1
null
null
null
null
UTF-8
Python
false
false
2,173
py
from Feature import FeatureSpace import numpy as np from import_lightcurve import LeerLC_MACHO from PreprocessLC import Preprocess_LC import os.path count = 0 folder = 1 path = '/Users/isadoranun/Dropbox/lightcurves/' for j in os.listdir(path): if os.path.isdir(path + j): for i in os.listdir(path + j): if i.endswith("B.mjd") and os.path.isfile(path + j +'/'+ i[2:-5] + 'R.mjd'): count = count + 1 lc_B = LeerLC_MACHO(path + j +'/'+ i[2:]) lc_R = LeerLC_MACHO(path + j +'/'+ i[2:-5] + 'R.mjd') #Opening the light curve [data, mjd, error] = lc_B.leerLC() [data2, mjd2, error2] = lc_R.leerLC() preproccesed_data = Preprocess_LC(data, mjd, error) [data, mjd, error] = preproccesed_data.Preprocess() preproccesed_data = Preprocess_LC(data2, mjd2, error2) [second_data, mjd2, error2] = preproccesed_data.Preprocess() a = FeatureSpace(category='all',featureList=None, automean=[0,0], StetsonL=second_data , B_R=second_data, Beyond1Std=error, StetsonJ=second_data, MaxSlope=mjd, LinearTrend=mjd, Eta_B_R=second_data, Eta_e=mjd, Q31B_R=second_data, PeriodLS=mjd, CAR_sigma=[mjd, error], SlottedA = mjd) a=a.calculateFeature(data) if count == 1: nombres = np.hstack(("MACHO_Id" , a.result(method='features') , "Class")) guardar = np.vstack((nombres, np.hstack((i[5:-6] , a.result(method='array') , folder )))) np.savetxt('test_real.csv', guardar, delimiter="," ,fmt="%s") else: my_data = np.genfromtxt('test_real.csv', delimiter=',', dtype=None) guardar = np.vstack((nombres,my_data[1:], np.hstack((i[5:-6] , a.result(method='array') , folder )))) np.savetxt('test_real.csv', guardar, delimiter="," ,fmt="%s") folder = folder + 1 #B_R = second_data, Eta_B_R = second_data, Eta_e = mjd, MaxSlope = mjd, PeriodLS = mjd, Q31B_R = second_data, StetsonJ = second_data, StetsonL = second_data)
[ "isadoranun@Isadoras-MacBook-Pro.local" ]
isadoranun@Isadoras-MacBook-Pro.local
849cad464c0731a0afd6cb94a57fdc9007ce5036
15f321878face2af9317363c5f6de1e5ddd9b749
/solutions_python/Problem_200/2122.py
c31ad8bdbc94a1aa0c0f79101990a413684bb5df
[]
no_license
dr-dos-ok/Code_Jam_Webscraper
c06fd59870842664cd79c41eb460a09553e1c80a
26a35bf114a3aa30fc4c677ef069d95f41665cc0
refs/heads/master
2020-04-06T08:17:40.938460
2018-10-14T10:12:47
2018-10-14T10:12:47
null
0
0
null
null
null
null
UTF-8
Python
false
false
986
py
def resolve_case(): num = int(input()) num_list = list(str(num)) assend_index = 0 same=1 for assend_index in range(1, len(num_list)): if num_list[assend_index - 1] > num_list[assend_index]: break; elif num_list[assend_index - 1] == num_list[assend_index]: same += 1 else: same = 1 print("".join(num_list[:assend_index-same]), end="") num_list_tmp = num_list[assend_index-same:] num_list_sorted = num_list[assend_index-same:] num_list_sorted.sort() length = len(num_list_tmp) for x in range(0, length): if num_list_tmp[x] is num_list_sorted[x]: print(num_list_tmp[x], end="") else: print(int(str(int(num_list_tmp[x]) - 1) + ("9" * (length - x - 1))), end="") break return cases = int(input()) for case in range(0, cases): print("Case #" + str(case + 1), end=": ") resolve_case() print()
[ "miliar1732@gmail.com" ]
miliar1732@gmail.com
a7399fadef7ec7257cbf947c3e818d52a13b725b
12f75ff50449717092789dc09da6e8d4dab409e0
/migrations/versions/78aa3d187c43_eltwelveth_migration.py
c132028c2501ad6742a53b2d81ebe5a62162e35b
[ "MIT" ]
permissive
lizKimita/Pitch-Deck
07e4ad3155aa6435b0d0a5615ef43b2a3fbc0571
0fd08aa2044ec76189e9eceea30b51907b885c8b
refs/heads/master
2020-05-15T11:19:57.997561
2019-04-27T07:00:59
2019-04-27T07:00:59
182,221,325
0
0
null
null
null
null
UTF-8
Python
false
false
796
py
"""eltwelveth migration Revision ID: 78aa3d187c43 Revises: b32a3e99a01b Create Date: 2019-04-23 15:02:55.858322 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '78aa3d187c43' down_revision = 'b32a3e99a01b' branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column('pitches', sa.Column('user_id', sa.Integer(), nullable=True)) op.create_foreign_key(None, 'pitches', 'users', ['user_id'], ['id']) # ### end Alembic commands ### def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_constraint(None, 'pitches', type_='foreignkey') op.drop_column('pitches', 'user_id') # ### end Alembic commands ###
[ "kimita.wanjiku@gmail.com" ]
kimita.wanjiku@gmail.com
012ba923be9e6450316c84cda3a5dc66f401dffd
7ad1f253166914797c97c472e374ea4204a0dcd1
/app/posts/routes.py
dd2d6bdc46ff74d5c47ca529fe681b54a4b614c4
[]
no_license
jaejunku/RSS-webapp
786e97a2f320cffe242e3597d7df9f2714cd357f
6a0526ee1434c6984901b16b9302c189dd70a74f
refs/heads/master
2022-07-07T20:26:14.957187
2020-05-15T03:09:22
2020-05-15T03:09:22
264,082,308
0
0
null
null
null
null
UTF-8
Python
false
false
2,063
py
from flask import Blueprint, redirect, render_template, flash, url_for, request, abort from flask_login import login_required, current_user from app import db from app.posts.forms import PostForm from app.models import Post posts = Blueprint('posts', __name__) @posts.route('/post/new', methods=['GET', 'POST']) @login_required def new_post(): form = PostForm() if form.validate_on_submit(): # Add post to database post = Post(title=form.title.data, content=form.content.data, author=current_user) db.session.add(post) db.session.commit() flash('Your post has been created!', 'success') return redirect(url_for('main.home')) return render_template('create_post.html', title='New posts', form=form, legend='Update posts') @posts.route("/post/<int:post_id>") def post(post_id): post = Post.query.get_or_404(post_id) return render_template('post.html', title=post.title, post=post) @posts.route("/post/<int:post_id>/update", methods=['GET', 'POST']) @login_required def update_post(post_id): post = Post.query.get_or_404(post_id) if post.author != current_user: abort(403) form = PostForm() if form.validate_on_submit(): post.title = form.title.data post.content = form.content.data db.session.commit() flash('Your post has been updated!', 'success') return redirect(url_for('posts.post', post_id=post.id)) elif request.method == 'GET': # Make field already populated with existing info form.title.data = post.title form.content.data = post.content return render_template('create_post.html', title='Update posts', form=form, legend='Update posts') @posts.route("/post/<int:post_id>/delete", methods=['POST']) @login_required def delete_post(post_id): post = Post.query.get_or_404(post_id) if post.author != current_user: abort(403) db.session.delete(post) db.session.commit() flash('Your post has been deleted!', 'success') return redirect(url_for('main.home'))
[ "jaejunk39@gmail.com" ]
jaejunk39@gmail.com
c7501f8f316081a9760f088927549c3576de37b0
ccc4f2c2351355212af9aef447cf33a38932cbfc
/plugins/discovery/jigsaw.py
1249c1d9201f9d49357e32e4741525191e92d624
[ "Apache-2.0" ]
permissive
stig81/hackers-tool-kit
fe1e4353d429a54cf1e503dc5ffdb52de2381309
9f1d45dd0da81207ae4bd775ffd51ba3168184bc
refs/heads/master
2020-05-23T14:26:40.782403
2019-05-14T21:08:18
2019-05-14T21:08:18
186,803,293
1
0
Apache-2.0
2019-05-15T10:23:20
2019-05-15T10:23:20
null
UTF-8
Python
false
false
1,794
py
import string import httplib import sys import myparser import re # http://www.jigsaw.com/SearchAcrossCompanies.xhtml?opCode=refresh&rpage=4&mode=0&cnCountry=&order=0&orderby=0&cmName=accuvant&cnDead=false&cnExOwned=false&count=0&screenNameType=0&screenName=&omitScreenNameType=0&omitScreenName=&companyId=0&estimatedCount=277&rowsPerPage=50 class search_jigsaw: def __init__(self, word, limit): self.word = word.replace(' ', '%20') self.results = "" self.totalresults = "" self.server = "www.jigsaw.com" self.hostname = "www.jigsaw.com" self.userAgent = "(Mozilla/5.0 (Windows; U; Windows NT 6.0;en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6" self.quantity = "100" self.limit = int(limit) self.counter = 0 def do_search(self): h = httplib.HTTP(self.server) h.putrequest( 'GET', "/FreeTextSearch.xhtml?opCode=search&autoSuggested=True&freeText=" + self.word) h.putheader('User-agent', self.userAgent) h.endheaders() returncode, returnmsg, headers = h.getreply() self.results = h.getfile().read() self.totalresults += self.results def check_next(self): renext = re.compile('> Next <') nextres = renext.findall(self.results) if nextres != []: nexty = "1" else: nexty = "0" return nexty def get_people(self): rawres = myparser.parser(self.totalresults, self.word) return rawres.people_jigsaw() def process(self): while (self.counter < self.limit): self.do_search() more = self.check_next() if more == "1": self.counter += 100 else: break
[ "noreply@github.com" ]
noreply@github.com
2ce97362db302bca16c4ce50d46abe8cef6a939d
e2e39726195c7bc075b9bd56e757acd136527d5c
/typings/vtkmodules/vtkCommonCore/vtkDenseArray_IhE.pyi
1e566c0d11ab4d5b928576e9018c81f9d2190df0
[ "BSD-3-Clause" ]
permissive
gen4438/vtk-python-stubs
a652272183d2d1ee48d4639e86bcffc1ac454af0
c9abd76362adf387af64ce5ddbd04c5d3bebe9da
refs/heads/main
2023-04-04T02:13:15.459241
2021-04-15T10:47:28
2021-04-15T10:53:59
358,224,363
1
0
null
null
null
null
UTF-8
Python
false
false
9,465
pyi
""" This type stub file was generated by pyright. """ from .vtkTypedArray_IhE import vtkTypedArray_IhE class vtkDenseArray_IhE(vtkTypedArray_IhE): """ vtkDenseArray<unsigned char> - Contiguous storage for N-way arrays. Superclass: vtkTypedArray[uint8] vtkDenseArray is a concrete vtkArray implementation that stores values using a contiguous block of memory. Values are stored with fortran ordering, meaning that if you iterated over the memory block, the left-most coordinates would vary the fastest. In addition to the retrieval and update methods provided by vtkTypedArray, vtkDenseArray provides methods to: Fill the entire array with a specific value. Retrieve a pointer to the storage memory block. @sa vtkArray, vtkTypedArray, vtkSparseArray @par Thanks: Developed by Timothy M. Shead (tshead@sandia.gov) at Sandia National Laboratories. """ def DeepCopy(self): """ V.DeepCopy() -> vtkArray C++: vtkArray *DeepCopy() override; Returns a new array that is a deep copy of this array. """ ... def Fill(self, p_int): """ V.Fill(int) C++: void Fill(const unsigned char &value) Fills every element in the array with the given value. """ ... def GetCoordinatesN(self, p_int, vtkArrayCoordinates): """ V.GetCoordinatesN(int, vtkArrayCoordinates) C++: void GetCoordinatesN(const SizeT n, vtkArrayCoordinates &coordinates) override; Returns the coordinates of the n-th value in the array, where n is in the range [0, GetNonNullSize()). Note that the order in which coordinates are visited is undefined, but is guaranteed to match the order in which values are visited using vtkTypedArray::GetValueN() and vtkTypedArray::SetValueN(). """ ... def GetExtents(self): """ V.GetExtents() -> vtkArrayExtents C++: const vtkArrayExtents &GetExtents() override; Returns the extents (the number of dimensions and size along each dimension) of the array. """ ... def GetNonNullSize(self): """ V.GetNonNullSize() -> int C++: SizeT GetNonNullSize() override; Returns the number of non-null values stored in the array. Note that this value will equal GetSize() for dense arrays, and will be less-than-or-equal to GetSize() for sparse arrays. """ ... def GetNumberOfGenerationsFromBase(self, string): """ V.GetNumberOfGenerationsFromBase(string) -> int C++: vtkIdType GetNumberOfGenerationsFromBase(const char *type) override; Given a the name of a base class of this class type, return the distance of inheritance between this class type and the named class (how many generations of inheritance are there between this class and the named class). If the named class is not in this class's inheritance tree, return a negative value. Valid responses will always be nonnegative. This method works in combination with vtkTypeMacro found in vtkSetGet.h. """ ... def GetNumberOfGenerationsFromBaseType(self, string): """ V.GetNumberOfGenerationsFromBaseType(string) -> int C++: static vtkIdType GetNumberOfGenerationsFromBaseType( const char *type) Given a the name of a base class of this class type, return the distance of inheritance between this class type and the named class (how many generations of inheritance are there between this class and the named class). If the named class is not in this class's inheritance tree, return a negative value. Valid responses will always be nonnegative. This method works in combination with vtkTypeMacro found in vtkSetGet.h. """ ... def GetStorage(self): """ V.GetStorage() -> (int, ...) C++: unsigned char *GetStorage() Returns a mutable reference to the underlying storage. Values are stored contiguously with fortran ordering. Use at your own risk! """ ... def GetValue(self, p_int): """ V.GetValue(int) -> int C++: const unsigned char &GetValue(CoordinateT i) override; V.GetValue(int, int) -> int C++: const unsigned char &GetValue(CoordinateT i, CoordinateT j) override; V.GetValue(int, int, int) -> int C++: const unsigned char &GetValue(CoordinateT i, CoordinateT j, CoordinateT k) override; V.GetValue(vtkArrayCoordinates) -> int C++: const unsigned char &GetValue( const vtkArrayCoordinates &coordinates) override; Returns the value stored in the array at the given coordinates. Note that the number of dimensions in the supplied coordinates must match the number of dimensions in the array. """ ... def GetValueN(self, p_int): """ V.GetValueN(int) -> int C++: const unsigned char &GetValueN(const SizeT n) override; Returns the n-th value stored in the array, where n is in the range [0, GetNonNullSize()). This is useful for efficiently visiting every value in the array. Note that the order in which values are visited is undefined, but is guaranteed to match the order used by vtkArray::GetCoordinatesN(). """ ... def IsA(self, string): """ V.IsA(string) -> int C++: vtkTypeBool IsA(const char *type) override; Return 1 if this class is the same type of (or a subclass of) the named class. Returns 0 otherwise. This method works in combination with vtkTypeMacro found in vtkSetGet.h. """ ... def IsDense(self): """ V.IsDense() -> bool C++: bool IsDense() override; Returns true iff the underlying array storage is "dense", i.e. that GetSize() and GetNonNullSize() will always return the same value. If not, the array is "sparse". """ ... def IsTypeOf(self, string): """ V.IsTypeOf(string) -> int C++: static vtkTypeBool IsTypeOf(const char *type) Return 1 if this class type is the same type of (or a subclass of) the named class. Returns 0 otherwise. This method works in combination with vtkTypeMacro found in vtkSetGet.h. """ ... def NewInstance(self): """ V.NewInstance() -> vtkDenseArray_IhE C++: vtkDenseArray<unsigned char> *NewInstance() """ ... def SafeDownCast(self, vtkObjectBase): """ V.SafeDownCast(vtkObjectBase) -> vtkDenseArray_IhE C++: static vtkDenseArray<unsigned char> *SafeDownCast( vtkObjectBase *o) """ ... def SetValue(self, p_int, p_int_1): """ V.SetValue(int, int) C++: void SetValue(CoordinateT i, const unsigned char &value) override; V.SetValue(int, int, int) C++: void SetValue(CoordinateT i, CoordinateT j, const unsigned char &value) override; V.SetValue(int, int, int, int) C++: void SetValue(CoordinateT i, CoordinateT j, CoordinateT k, const unsigned char &value) override; V.SetValue(vtkArrayCoordinates, int) C++: void SetValue(const vtkArrayCoordinates &coordinates, const unsigned char &value) override; Overwrites the value stored in the array at the given coordinates. Note that the number of dimensions in the supplied coordinates must match the number of dimensions in the array. """ ... def SetValueN(self, p_int, p_int_1): """ V.SetValueN(int, int) C++: void SetValueN(const SizeT n, const unsigned char &value) override; Overwrites the n-th value stored in the array, where n is in the range [0, GetNonNullSize()). This is useful for efficiently visiting every value in the array. Note that the order in which values are visited is undefined, but is guaranteed to match the order used by vtkArray::GetCoordinatesN(). """ ... def __delattr__(self, *args, **kwargs): """ Implement delattr(self, name). """ ... def __getattribute__(self, *args, **kwargs): """ Return getattr(self, name). """ ... def __init__(self, *args, **kwargs) -> None: ... @staticmethod def __new__(*args, **kwargs): """ Create and return a new object. See help(type) for accurate signature. """ ... def __repr__(self, *args, **kwargs): """ Return repr(self). """ ... def __setattr__(self, *args, **kwargs): """ Implement setattr(self, name, value). """ ... def __str__(self, *args, **kwargs) -> str: """ Return str(self). """ ... __this__ = ... __dict__ = ... __vtkname__ = ...
[ "g1e2n04@gmail.com" ]
g1e2n04@gmail.com
5975696fda5601ace983ede2e4e31ea4bc52d380
45bec06057e05dd35a4aa8cd5065cfe9aaf3fa03
/ICE7/ICE7.py
c4c77394d8ef06eb50802cf2e8901991f1bac009
[]
no_license
flarefansy/ASE_lab-Assignments
cd210fb8318946abddd381cd95c7c42a60cb996b
8600f96a65221709ccb42aa00d7ec1a1d225d506
refs/heads/master
2021-01-22T17:23:01.158962
2018-11-09T01:28:33
2018-11-09T01:28:33
102,388,947
0
0
null
null
null
null
UTF-8
Python
false
false
1,150
py
# -*- coding: utf-8 -*- """ Created on Thu Oct 5 14:09:12 2017 @author: Spencersun """ import nltk from nltk.corpus import wordnet as wn from nltk.tokenize import word_tokenize,wordpunct_tokenize,sent_tokenize from nltk.stem import SnowballStemmer, WordNetLemmatizer from nltk.tag import pos_tag from nltk.util import ngrams from nltk import ne_chunk synsets = wn.synsets('car') print (synsets) #input_tokenizer = nltk.data.load('input.txt') input_tokenizer = "hello world, Tim" sentences = sent_tokenize(input_tokenizer) print (sentences) #words = [word_tokenize(t) for t in sentences] words = word_tokenize(input_tokenizer) print (words) stemmer = SnowballStemmer('english') output_stemmer = stemmer.stem('eating') print (output_stemmer) output_POStags = [] for tokens in words: output_POStags.append(nltk.pos_tag(tokens)) print (output_POStags) lemmatizer = WordNetLemmatizer() output_lemmatizer = lemmatizer.lemmatize('walked', pos='v') print (output_lemmatizer) trigrams = list(ngrams(words,2)) print (trigrams) NER = ne_chunk(pos_tag(wordpunct_tokenize(input_tokenizer))) print (NER)
[ "noreply@github.com" ]
noreply@github.com
0c6ea69e387fc0e769c4ae108a2f13a9c03c7cc7
a8e11eb540138c11c79a54adee909389a256b9a9
/modules/tools.py
14e7b78154f1388291216566b99e0d7cfeda8c59
[ "MIT" ]
permissive
Daisuke0209/word-conversion
4a9b103e638e7f958211ce81d299c3efc875baf5
6c3f4053427806881a1435be9d63115d443f3273
refs/heads/develop
2023-04-10T06:31:16.720255
2021-04-09T11:40:37
2021-04-09T11:40:37
355,205,945
0
0
MIT
2021-04-09T11:40:38
2021-04-06T13:50:33
Python
UTF-8
Python
false
false
3,382
py
import re import pandas as pd from docx import Document from docx.enum.text import WD_COLOR_INDEX def convert_character(text : str): """ Convert consecutive full-size numbers to half-size numbers. Convert a single half-size number into a full-size number. Convert half-size English characters to full-size ones. Parameters ---------- text : str input text Returns ---------- output : str converted text """ list_text = list(text) half_nums = re.findall('[0-9]+', text) full_nums = re.findall('[0-9]+', text) c_half_nums = [] for half_num in half_nums: if len(half_num) == 1: c_half_nums.append(half_num) c_full_nums = [] for full_num in full_nums: if len(full_num) > 1: c_full_nums.append(full_num) #half to full for c_half_num in c_half_nums: index = text.find(c_half_num) convert = c_half_num.translate(str.maketrans({chr(0x0021 + i): chr(0xFF01 + i) for i in range(94)})) list_text[index] = convert #full to half for c_full_num in c_full_nums: index = text.find(c_full_num) converts = c_full_num.translate(str.maketrans({chr(0xFF01 + i): chr(0x21 + i) for i in range(94)})) for i, convert in enumerate(converts): list_text[index + i] = convert output = "".join(list_text) return output def convert_eng_character(text : str): """ Convert half-size English characters to full-size ones. Parameters ---------- text : str input text Returns ---------- output : str converted text """ #Upper English character output = text.translate(str.maketrans({chr(0x0041 + i): chr(0xFF21 + i) for i in range(26)})) #Lower English character output = output.translate(str.maketrans({chr(0x0061 + i): chr(0xFF41 + i) for i in range(26)})) return output def convert_docx( document : Document, use_num_convert : bool, use_eng_convert : bool, use_highlight : bool ): """ Convert a word file. Parameters ---------- document : Document word file use_num_convert : bool flag to use number conversion(True:use, False:not use) use_eng_convert : bool flag to use english conversion(True:use, False:not use) use_highlight : bool flag to use hightligt the changes Returns ---------- document : Document converted word file df : pd.DataFrame A dataframe that organizes the conversion points """ diff_originals, diff_covnerts, diff_indices = [], [], [] for i, paragraph in enumerate(document.paragraphs): original_text = paragraph.text if use_num_convert: paragraph.text = convert_character(paragraph.text) if use_eng_convert: paragraph.text = convert_eng_character(paragraph.text) if original_text != paragraph.text: if use_highlight: paragraph.runs[0].font.highlight_color = WD_COLOR_INDEX.YELLOW diff_originals.append(original_text) diff_covnerts.append(paragraph.text) diff_indices.append(i) df = pd.DataFrame([diff_indices, diff_originals, diff_covnerts]).T df.columns = ['index', 'original', 'converted'] return document, df
[ "stumble.on.the.stair@gmail.com" ]
stumble.on.the.stair@gmail.com
a99b7ef1e4369541a38a0f755a7f9a70dda5d14c
bd1fc4945e044ee82d27b4828a77c60f7ff1886d
/my_algo/prog12987.py
9941d458db18297063fce9c348df5134f21d42a7
[]
no_license
nailerHeum/codesquad
89930db1fe8b910e7831f88c5e4928f4a08bf266
adcd6046fa481a353a1fd74dd3bde54442a7c25e
refs/heads/master
2020-05-04T11:01:05.860974
2019-05-02T04:40:26
2019-05-02T04:40:26
179,099,118
1
1
null
null
null
null
UTF-8
Python
false
false
390
py
def solution(A, B): answer = 0 bOverFlow = False A.sort() B.sort() j = 0 for i in range(len(A)): while A[i] >= B[j]: j += 1 if j == len(B): bOverFlow = True break if bOverFlow == True: break answer+=1 j+=1 if j == len(B): break return answer
[ "kingman330@gmail.com" ]
kingman330@gmail.com
2e0da8eff224e62862cabf14b96105ad43c669bf
ab52e3212fce7df6c14314b9f32476bea134f289
/monai/engines/multi_gpu_supervised_trainer.py
6f0fd4f800c51a18a906aeff98425d05a7c99605
[ "Apache-2.0" ]
permissive
AllenAkhaumere/MONAI
30ab4e8c5774b32059894f154779e3842dfd7e69
33dab6fe152a1b8f38c13d456de583bd6fa0e0ae
refs/heads/master
2022-11-12T18:14:32.804026
2020-07-03T15:49:01
2020-07-03T15:49:01
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,819
py
# Copyright 2020 MONAI Consortium # 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. from typing import Callable import torch from monai.utils import exact_version, optional_import from monai.engines.utils import get_devices_spec create_supervised_trainer, _ = optional_import("ignite.engine", "0.3.0", exact_version, "create_supervised_trainer") create_supervised_evaluator, _ = optional_import("ignite.engine", "0.3.0", exact_version, "create_supervised_evaluator") _prepare_batch, _ = optional_import("ignite.engine", "0.3.0", exact_version, "_prepare_batch") def _default_transform(_x, _y, _y_pred, loss): return loss.item() def _default_eval_transform(x, y, y_pred): return y_pred, y def create_multigpu_supervised_trainer( net: torch.nn.Module, optimizer, loss_fn, devices=None, non_blocking: bool = False, prepare_batch: Callable = _prepare_batch, output_transform: Callable = _default_transform, ): """ Derived from `create_supervised_trainer` in Ignite. Factory function for creating a trainer for supervised models. Args: net (`torch.nn.Module`): the network to train. optimizer (`torch.optim.Optimizer`): the optimizer to use. loss_fn (`torch.nn` loss function): the loss function to use. devices (list, optional): device(s) type specification (default: None). Applies to both model and batches. None is all devices used, empty list is CPU only. non_blocking: if True and this copy is between CPU and GPU, the copy may occur asynchronously with respect to the host. For other cases, this argument has no effect. prepare_batch: function that receives `batch`, `device`, `non_blocking` and outputs tuple of tensors `(batch_x, batch_y)`. output_transform: function that receives 'x', 'y', 'y_pred', 'loss' and returns value to be assigned to engine's state.output after each iteration. Default is returning `loss.item()`. Returns: Engine: a trainer engine with supervised update function. Note: `engine.state.output` for this engine is defined by `output_transform` parameter and is the loss of the processed batch by default. """ devices = get_devices_spec(devices) if len(devices) > 1: net = torch.nn.parallel.DataParallel(net) return create_supervised_trainer(net, optimizer, loss_fn, devices[0], non_blocking, prepare_batch, output_transform) def create_multigpu_supervised_evaluator( net: torch.nn.Module, metrics=None, devices=None, non_blocking: bool = False, prepare_batch: Callable = _prepare_batch, output_transform: Callable = _default_eval_transform, ): """ Derived from `create_supervised_evaluator` in Ignite. Factory function for creating an evaluator for supervised models. Args: net (`torch.nn.Module`): the model to train. metrics (dict of str - :class:`~ignite.metrics.Metric`): a map of metric names to Metrics. devices (list, optional): device(s) type specification (default: None). Applies to both model and batches. None is all devices used, empty list is CPU only. non_blocking: if True and this copy is between CPU and GPU, the copy may occur asynchronously with respect to the host. For other cases, this argument has no effect. prepare_batch: function that receives `batch`, `device`, `non_blocking` and outputs tuple of tensors `(batch_x, batch_y)`. output_transform: function that receives 'x', 'y', 'y_pred' and returns value to be assigned to engine's state.output after each iteration. Default is returning `(y_pred, y,)` which fits output expected by metrics. If you change it you should use `output_transform` in metrics. Note: `engine.state.output` for this engine is defined by `output_transform` parameter and is a tuple of `(batch_pred, batch_y)` by default. Returns: Engine: an evaluator engine with supervised inference function. """ devices = get_devices_spec(devices) if len(devices) > 1: net = torch.nn.parallel.DataParallel(net) return create_supervised_evaluator(net, metrics, devices[0], non_blocking, prepare_batch, output_transform)
[ "noreply@github.com" ]
noreply@github.com
edc76c891adea130c96d0cc048da2c771c18b92a
4dda597dac544b237cf8f8b04b3c9e662b988a92
/moot/moot/urls.py
8bbcabe60d7122ead34e89c6f5032e63ab65b2e7
[]
no_license
beriuta/history
02ac9414c0475fde59f6a455c23c56235fe3c4bc
026c965f694e84120825069bedf7bfac235318b5
refs/heads/master
2020-04-11T17:24:39.558174
2018-12-16T02:08:18
2018-12-16T02:08:18
161,959,735
0
0
null
null
null
null
UTF-8
Python
false
false
863
py
"""moot URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.conf.urls import url, include 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) """ from django.conf.urls import url from app01 import views from django.contrib import admin urlpatterns = [ url(r'^login/', views.login), url(r'^index', views.indexView.as_view()), url(r'^upload/$',views.upload) ]
[ "2457409765@qq.com" ]
2457409765@qq.com
21683f1fe8ec91e7c283eec2141feb0fe2382f3a
4d7decff1ed5fc6664fdeedf518ec95690c30a90
/lesson-2/geekshop/geekshop/settings.py
d739ea29d5f0ad7587f70635000744fd485454b9
[]
no_license
kkulikoff/Course_Django-2
67087981b2ad146740b4f51c67e0660c4bdd5271
34bfea63c35ddd2f717da61503607d6828e61eb1
refs/heads/main
2023-06-11T18:47:37.729923
2021-07-06T12:23:45
2021-07-06T12:23:45
378,244,772
0
0
null
2021-07-06T12:23:46
2021-06-18T19:14:21
Python
UTF-8
Python
false
false
4,901
py
""" Django settings for geekshop project. Generated by 'django-admin startproject' using Django 1.10.5. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.10/ref/settings/ """ import json import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'xxac+ln+74ue7w1tj7%l3kw)9ygh893s6q$g)5ps4c#s!=19yk' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'mainapp', 'authapp', 'basketapp', 'adminapp', 'social_django', ] AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'social_core.backends.vk.VKOAuth2', ) with open('geekshop/vk.json', 'r') as f: VK = json.load(f) SOCIAL_AUTH_VK_OAUTH2_KEY = VK['SOCIAL_AUTH_VK_OAUTH2_KEY'] SOCIAL_AUTH_VK_OAUTH2_SECRET = VK['SOCIAL_AUTH_VK_OAUTH2_SECRET'] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', ] ROOT_URLCONF = 'geekshop.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'mainapp.context_processors.basket', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], }, }, ] WSGI_APPLICATION = 'geekshop.wsgi.application' # Database # https://docs.djangoproject.com/en/1.10/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/1.10/topics/i18n/ LANGUAGE_CODE = 'ru-ru' # TIME_ZONE = 'UTC' TIME_ZONE = 'Asia/Yekaterinburg' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), ) MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' AUTH_USER_MODEL = 'authapp.ShopUser' LOGIN_URL = '/auth/login/' EMAIL_HOST = 'localhost' EMAIL_PORT = 25 EMAIL_HOST_USER = 'django@gb.local' EMAIL_HOST_PASSWORD = 'geekbrains' EMAIL_USE_SSL = False # EMAIL_HOST_USER, EMAIL_HOST_PASSWORD = None, None EMAIL_BACKEND = 'django.core.mail.backends.filebased.EmailBackend' EMAIL_FILE_PATH = 'tmp/emails' DOMAIN_NAME = 'http://localhost:8000' LOGIN_ERROR_URL = '/' SOCIAL_AUTH_VK_OAUTH2_IGNORE_DEFAULT_SCOPE = True SOCIAL_AUTH_VK_OAUTH2_SCOPE = ['email'] SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.create_user', 'authapp.pipeline.save_user_profile', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', )
[ "kulikoff.ab@yandex.ru" ]
kulikoff.ab@yandex.ru
59f10070262e7b34c102704b264e5dea5ff8b7da
6482ba06c67f03ff4ea72fb7a5fc8d70f42cfaca
/metodo write y nl.py
34fb68dade1a550c62fa9e02278862f660a43244
[]
no_license
YulaySC/TareaProgramada2
283d51f7323e0e77f18126a5fc682a776e296f8a
b89eb224dda251a218406d08bd22380b9647913b
refs/heads/master
2021-01-15T11:12:11.372600
2014-10-12T11:22:28
2014-10-12T11:22:28
null
0
0
null
null
null
null
UTF-8
Python
false
false
902
py
def inicio(): #Modo consulta (Inicio de programa) global ListaRes global l_vars estado = 1 while estado: string = input("?- ") val = inicio_verificaciones(string) if string == '': pass elif string == "<define>": consulta() elif string == "Exit": estado = 0 elif string == "nl": print() elif string == "i_BC": print(BC) elif val[0:5] == "Error": print(val) else: string = fragmenta(string) if string[0] == "write": escribe(string[1]) else: new_str = hecho(string[0],string[1]) l_vars = {} if comp_hecho_predicado(new_str) == True: print("YES") else: print("NO") print("Finalizaste")
[ "suramirez92@gmail.com" ]
suramirez92@gmail.com
e571b0c8c0f613927774a5236f43c636e0fdeaf8
dfe32af54fc69b37148b86cfa9ffddf7c2662f69
/cadnano25/cadnano/decorators/insertion.py
ded9eb1f5d6f8ded14d585634f4e8bfadba3df9c
[ "MIT" ]
permissive
amylittleyang/OtraCAD
c52801d67b337bfe2fce588c29783580615a1cd2
126360719704caf6850d42565fe96be53b66a22d
refs/heads/master
2021-01-17T15:31:18.227351
2016-05-19T21:57:34
2016-05-19T21:57:34
43,393,625
0
0
null
null
null
null
UTF-8
Python
false
false
759
py
#!/usr/bin/env python # encoding: utf-8 class Insertion(object): """ Insertions do affect an applied sequence and do not store a sequence themselves. They are a skip if the length is less than 0 """ def __init__(self, index, length): self._length = length self._index = index # end def def length(self): """ This is the length of a sequence that is immutable by the strand """ return self._length def setLength(self, length): self._length = length # end def def updateIdx(self, delta): self._index += delta # end def def idx(self): return self._index # end def def isSkip(self): return self.length() < 0 # end class
[ "jy152@duke.edu" ]
jy152@duke.edu
8ccce85d3c7968272528a0cfe84d03b2f59d4dbe
fc1743a5be91598d33033250cd0b41eda733bdd6
/Exams/forms.py
7a0469825e9445624936cf1ca4416ab6abaabb86
[]
no_license
1DONit1/rexam
113bc1dc7d4c6eb63f62e2eebae63796d533811b
c0c64509f920d9e3c0154177636d67fd56cb106b
refs/heads/master
2022-12-23T01:46:53.620941
2019-12-01T22:23:37
2019-12-01T22:23:37
225,240,334
0
0
null
2022-12-08T06:58:36
2019-12-01T22:28:00
HTML
UTF-8
Python
false
false
3,128
py
from django import forms from django.forms import ModelForm, TextInput, Textarea, Select from django.shortcuts import get_object_or_404 from django.template.defaultfilters import safe from Exams.models import Exam, Subject, Question, Answer class ExamsCreateForm(ModelForm): class Meta: model = Exam fields = ('exam_subject', 'exam_header', 'exam_description') widgets = { 'exam_header': TextInput(attrs={'class': 'form-control', 'placeholder': 'Заголовок'}), 'exam_description': Textarea(attrs={'class': 'form-control', 'placeholder': 'Описание'}), 'exam_subject': Select(attrs={'class': 'form-control col-5 d-inline', 'placeholder': 'Предмет'}) } class SubjectCreateForm(ModelForm): class Meta: model = Subject fields = '__all__' widgets = { 'name': TextInput(attrs={'class': 'form-control', 'placeholder': 'Имя предмета'}) } class QuestionCreateForm(ModelForm): class Meta: model = Question exclude = ['question_exam'] widgets = { 'question_text': Textarea(attrs={'class': 'form-control', 'placeholder': 'Текст вопроса'}), } class AnswerCreateForm(ModelForm): class Meta: model = Answer exclude = ['answer_question'] widgets = { 'answer_text': Textarea(attrs={'class': 'form-control', 'placeholder': 'Текст ответа'}), } class ExamAttemptForm(forms.Form): def __init__(self, *args, **kwargs): attempted_exam = get_object_or_404(Exam, pk=kwargs.pop('exam_id', None)) questions = attempted_exam.get_question_set() super(ExamAttemptForm, self).__init__(*args, **kwargs) for question in questions: choices = [] answers_set = question.get_answers_set() question_label = question.question_text if question.question_image: question_label += safe( '<a target="_blank" rel="noopener noreferrer" href="' + question.question_image.url + '"><img class="d-block img-thumbnail rounded" width="500px" height="500px" src="' + question.question_image.url + '"/></a>') for answer in answers_set: answer_choice = answer.answer_text if answer.answer_image: answer_choice += '<a target="_blank" rel="noopener noreferrer" href="' + answer.answer_image.url + '"><img class="d-block img-thumbnail rounded" width="300px" height="300px" src="' + answer.answer_image.url + '"/></a>' choices.append((answer.pk, safe(answer_choice))) self.fields['question_%d' % question.pk] = forms.MultipleChoiceField(label=question_label, required=True, choices=choices, widget=forms.CheckboxSelectMultiple)
[ "donimsi@mail.ru" ]
donimsi@mail.ru
cdc47a5cea9696e18e22ca2cd4c10e0af54f718f
eea0b330a06b8e28c36e44256e74b4f8718b62fc
/sendemail/forms.py
56bab5832457d715c8a18d4b9c12eb550a4dc182
[]
no_license
anjali142/Robotronics-Club-Website
a1cad6aad601570c2a1bcf01099305e9394c4aea
90c90c800a5b0f8c6e38d12f9db828f806c330bd
refs/heads/master
2020-06-12T13:04:36.733208
2019-08-10T10:59:20
2019-08-10T10:59:20
194,308,189
0
0
null
2019-06-28T17:06:43
2019-06-28T17:06:43
null
UTF-8
Python
false
false
259
py
from django import forms class ContactForm(forms.Form): from_email = forms.EmailField(required=True) first = forms.CharField(required=True) last = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea, required=True)
[ "varunjustrocks@gmail.com" ]
varunjustrocks@gmail.com
405530803fec0cadc01ebcb0fa2c1f53d630fa56
dd80a584130ef1a0333429ba76c1cee0eb40df73
/external/chromium_org/chrome/chrome_common.gypi
a8ee3297b5a77f90ca6ad3a7c2b54682254341f2
[ "MIT", "BSD-3-Clause" ]
permissive
karunmatharu/Android-4.4-Pay-by-Data
466f4e169ede13c5835424c78e8c30ce58f885c1
fcb778e92d4aad525ef7a995660580f948d40bc9
refs/heads/master
2021-03-24T13:33:01.721868
2017-02-18T17:48:49
2017-02-18T17:48:49
81,847,777
0
2
MIT
2020-03-09T00:02:12
2017-02-13T16:47:00
null
UTF-8
Python
false
false
33,680
gypi
# Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'targets': [ { 'target_name': 'common', 'type': 'static_library', 'variables': { 'chrome_common_target': 1, 'enable_wexit_time_destructors': 1, }, 'include_dirs': [ '..', '<(SHARED_INTERMEDIATE_DIR)', # Needed by chrome_content_client.cc. ], 'direct_dependent_settings': { 'include_dirs': [ '..', ], }, 'dependencies': [ # TODO(gregoryd): chrome_resources and chrome_strings could be # shared with the 64-bit target, but it does not work due to a gyp # issue. 'common_net', 'common_version', 'installer_util', 'metrics_proto', '<(DEPTH)/base/base.gyp:base', '<(DEPTH)/base/base.gyp:base_i18n', '<(DEPTH)/base/base.gyp:base_prefs', '<(DEPTH)/base/base.gyp:base_static', '<(DEPTH)/chrome/chrome_resources.gyp:chrome_resources', '<(DEPTH)/chrome/chrome_resources.gyp:chrome_strings', '<(DEPTH)/chrome/chrome_resources.gyp:theme_resources', '<(DEPTH)/chrome/common_constants.gyp:common_constants', '<(DEPTH)/components/components.gyp:json_schema', '<(DEPTH)/components/components.gyp:policy_component', '<(DEPTH)/components/components.gyp:variations', '<(DEPTH)/content/content.gyp:content_common', '<(DEPTH)/net/net.gyp:net', '<(DEPTH)/skia/skia.gyp:skia', '<(DEPTH)/third_party/icu/icu.gyp:icui18n', '<(DEPTH)/third_party/icu/icu.gyp:icuuc', '<(DEPTH)/third_party/libxml/libxml.gyp:libxml', '<(DEPTH)/third_party/sqlite/sqlite.gyp:sqlite', '<(DEPTH)/third_party/zlib/google/zip.gyp:zip', '<(DEPTH)/ui/resources/ui_resources.gyp:ui_resources', '<(DEPTH)/url/url.gyp:url_lib', '<(DEPTH)/webkit/common/user_agent/webkit_user_agent.gyp:user_agent', ], 'sources': [ '../apps/app_shim/app_shim_launch.h', '../apps/app_shim/app_shim_messages.h', 'common/all_messages.h', 'common/attrition_experiments.h', 'common/auto_start_linux.cc', 'common/auto_start_linux.h', 'common/autocomplete_match_type.cc', 'common/autocomplete_match_type.h', 'common/automation_constants.cc', 'common/automation_constants.h', 'common/automation_messages.cc', 'common/automation_messages.h', 'common/automation_messages_internal.h', 'common/badge_util.cc', 'common/badge_util.h', 'common/cancelable_task_tracker.cc', 'common/cancelable_task_tracker.h', 'common/child_process_logging.h', 'common/child_process_logging_win.cc', 'common/chrome_content_client.cc', 'common/chrome_content_client.h', 'common/chrome_content_client_constants.cc', 'common/chrome_content_client_ios.mm', 'common/chrome_result_codes.h', 'common/chrome_utility_messages.h', 'common/chrome_version_info.cc', 'common/chrome_version_info_android.cc', 'common/chrome_version_info_chromeos.cc', 'common/chrome_version_info_posix.cc', 'common/chrome_version_info_mac.mm', 'common/chrome_version_info_win.cc', 'common/chrome_version_info.h', 'common/cloud_print/cloud_print_class_mac.h', 'common/cloud_print/cloud_print_class_mac.mm', 'common/cloud_print/cloud_print_constants.cc', 'common/cloud_print/cloud_print_constants.h', 'common/cloud_print/cloud_print_helpers.cc', 'common/cloud_print/cloud_print_helpers.h', 'common/cloud_print/cloud_print_proxy_info.cc', 'common/cloud_print/cloud_print_proxy_info.h', 'common/common_message_generator.cc', 'common/common_message_generator.h', 'common/common_param_traits.cc', 'common/common_param_traits.h', 'common/common_param_traits_macros.h', 'common/content_restriction.h', 'common/content_settings.cc', 'common/content_settings.h', 'common/content_settings_helper.cc', 'common/content_settings_helper.h', 'common/content_settings_pattern.cc', 'common/content_settings_pattern.h', 'common/content_settings_pattern_parser.cc', 'common/content_settings_pattern_parser.h', 'common/content_settings_types.h', 'common/crash_keys.cc', 'common/crash_keys.h', 'common/custom_handlers/protocol_handler.cc', 'common/custom_handlers/protocol_handler.h', 'common/descriptors_android.h', 'common/dump_without_crashing.cc', 'common/dump_without_crashing.h', 'common/encrypted_media_messages_android.h', 'common/extensions/api/commands/commands_handler.cc', 'common/extensions/api/commands/commands_handler.h', 'common/extensions/api/extension_action/action_info.cc', 'common/extensions/api/extension_action/action_info.h', 'common/extensions/api/extension_action/browser_action_handler.cc', 'common/extensions/api/extension_action/browser_action_handler.h', 'common/extensions/api/extension_action/page_action_handler.cc', 'common/extensions/api/extension_action/page_action_handler.h', 'common/extensions/api/extension_action/script_badge_handler.cc', 'common/extensions/api/extension_action/script_badge_handler.h', 'common/extensions/api/file_browser_handlers/file_browser_handler.cc', 'common/extensions/api/file_browser_handlers/file_browser_handler.h', 'common/extensions/api/file_handlers/file_handlers_parser.cc', 'common/extensions/api/file_handlers/file_handlers_parser.h', 'common/extensions/api/i18n/default_locale_handler.cc', 'common/extensions/api/i18n/default_locale_handler.h', 'common/extensions/api/identity/oauth2_manifest_handler.cc', 'common/extensions/api/identity/oauth2_manifest_handler.h', 'common/extensions/api/input_ime/input_components_handler.cc', 'common/extensions/api/input_ime/input_components_handler.h', 'common/extensions/api/managed_mode_private/managed_mode_handler.cc', 'common/extensions/api/managed_mode_private/managed_mode_handler.h', 'common/extensions/api/media_galleries_private/media_galleries_handler.h', 'common/extensions/api/media_galleries_private/media_galleries_handler.cc', 'common/extensions/api/messaging/message.h', 'common/extensions/api/omnibox/omnibox_handler.cc', 'common/extensions/api/omnibox/omnibox_handler.h', 'common/extensions/api/plugins/plugins_handler.cc', 'common/extensions/api/plugins/plugins_handler.h', 'common/extensions/api/sockets/sockets_manifest_handler.cc', 'common/extensions/api/sockets/sockets_manifest_handler.h', 'common/extensions/api/sockets/sockets_manifest_data.cc', 'common/extensions/api/sockets/sockets_manifest_data.h', 'common/extensions/api/sockets/sockets_manifest_permission.cc', 'common/extensions/api/sockets/sockets_manifest_permission.h', 'common/extensions/api/speech/tts_engine_manifest_handler.cc', 'common/extensions/api/speech/tts_engine_manifest_handler.h', 'common/extensions/api/spellcheck/spellcheck_handler.cc', 'common/extensions/api/spellcheck/spellcheck_handler.h', 'common/extensions/api/storage/storage_schema_manifest_handler.cc', 'common/extensions/api/storage/storage_schema_manifest_handler.h', 'common/extensions/api/system_indicator/system_indicator_handler.cc', 'common/extensions/api/system_indicator/system_indicator_handler.h', 'common/extensions/api/url_handlers/url_handlers_parser.cc', 'common/extensions/api/url_handlers/url_handlers_parser.h', 'common/extensions/chrome_extensions_client.cc', 'common/extensions/chrome_extensions_client.h', 'common/extensions/chrome_manifest_handlers.cc', 'common/extensions/chrome_manifest_handlers.h', 'common/extensions/command.cc', 'common/extensions/command.h', 'common/extensions/dom_action_types.h', 'common/extensions/extension_constants.cc', 'common/extensions/extension_constants.h', 'common/extensions/extension_file_util.cc', 'common/extensions/extension_file_util.h', 'common/extensions/extension_icon_set.cc', 'common/extensions/extension_icon_set.h', 'common/extensions/extension_l10n_util.cc', 'common/extensions/extension_l10n_util.h', 'common/extensions/extension_messages.cc', 'common/extensions/extension_messages.h', 'common/extensions/extension_process_policy.cc', 'common/extensions/extension_process_policy.h', 'common/extensions/extension_set.cc', 'common/extensions/extension_set.h', 'common/extensions/features/api_feature.cc', 'common/extensions/features/api_feature.h', 'common/extensions/features/base_feature_provider.cc', 'common/extensions/features/base_feature_provider.h', 'common/extensions/features/complex_feature.cc', 'common/extensions/features/complex_feature.h', 'common/extensions/features/feature_channel.cc', 'common/extensions/features/feature_channel.h', 'common/extensions/features/manifest_feature.cc', 'common/extensions/features/manifest_feature.h', 'common/extensions/features/permission_feature.cc', 'common/extensions/features/permission_feature.h', 'common/extensions/features/simple_feature.cc', 'common/extensions/features/simple_feature.h', 'common/extensions/manifest_handler_helpers.cc', 'common/extensions/manifest_handler_helpers.h', 'common/extensions/manifest_handlers/app_isolation_info.cc', 'common/extensions/manifest_handlers/app_isolation_info.h', 'common/extensions/manifest_handlers/app_launch_info.cc', 'common/extensions/manifest_handlers/app_launch_info.h', 'common/extensions/manifest_handlers/content_scripts_handler.cc', 'common/extensions/manifest_handlers/content_scripts_handler.h', 'common/extensions/manifest_handlers/externally_connectable.cc', 'common/extensions/manifest_handlers/externally_connectable.h', 'common/extensions/manifest_handlers/icons_handler.cc', 'common/extensions/manifest_handlers/icons_handler.h', 'common/extensions/manifest_handlers/minimum_chrome_version_checker.cc', 'common/extensions/manifest_handlers/minimum_chrome_version_checker.h', 'common/extensions/manifest_handlers/nacl_modules_handler.cc', 'common/extensions/manifest_handlers/nacl_modules_handler.h', 'common/extensions/manifest_handlers/settings_overrides_handler.cc', 'common/extensions/manifest_handlers/settings_overrides_handler.h', 'common/extensions/manifest_handlers/theme_handler.cc', 'common/extensions/manifest_handlers/theme_handler.h', 'common/extensions/manifest_url_handler.cc', 'common/extensions/manifest_url_handler.h', 'common/extensions/message_bundle.cc', 'common/extensions/message_bundle.h', 'common/extensions/mime_types_handler.cc', 'common/extensions/mime_types_handler.h', 'common/extensions/permissions/bluetooth_permission.cc', 'common/extensions/permissions/bluetooth_permission.h', 'common/extensions/permissions/bluetooth_permission_data.cc', 'common/extensions/permissions/bluetooth_permission_data.h', 'common/extensions/permissions/chrome_api_permissions.cc', 'common/extensions/permissions/chrome_api_permissions.h', 'common/extensions/permissions/chrome_permission_message_provider.cc', 'common/extensions/permissions/chrome_permission_message_provider.h', 'common/extensions/permissions/media_galleries_permission.cc', 'common/extensions/permissions/media_galleries_permission.h', 'common/extensions/permissions/media_galleries_permission_data.cc', 'common/extensions/permissions/media_galleries_permission_data.h', 'common/extensions/permissions/permission_message_util.cc', 'common/extensions/permissions/permission_message_util.h', 'common/extensions/permissions/set_disjunction_permission.h', 'common/extensions/permissions/settings_override_permission.cc', 'common/extensions/permissions/settings_override_permission.h', 'common/extensions/permissions/socket_permission.cc', 'common/extensions/permissions/socket_permission.h', 'common/extensions/permissions/socket_permission_data.cc', 'common/extensions/permissions/socket_permission_data.h', 'common/extensions/permissions/socket_permission_entry.cc', 'common/extensions/permissions/socket_permission_entry.h', 'common/extensions/permissions/usb_device_permission.cc', 'common/extensions/permissions/usb_device_permission.h', 'common/extensions/permissions/usb_device_permission_data.cc', 'common/extensions/permissions/usb_device_permission_data.h', 'common/extensions/sync_helper.cc', 'common/extensions/sync_helper.h', 'common/extensions/update_manifest.cc', 'common/extensions/update_manifest.h', 'common/extensions/value_counter.cc', 'common/extensions/value_counter.h', 'common/extensions/web_accessible_resources_handler.cc', 'common/extensions/web_accessible_resources_handler.h', 'common/extensions/webview_handler.cc', 'common/extensions/webview_handler.h', 'common/favicon/favicon_types.cc', 'common/favicon/favicon_types.h', 'common/favicon/favicon_url_parser.cc', 'common/favicon/favicon_url_parser.h', 'common/icon_with_badge_image_source.cc', 'common/icon_with_badge_image_source.h', 'common/importer/firefox_importer_utils.cc', 'common/importer/firefox_importer_utils.h', 'common/importer/firefox_importer_utils_linux.cc', 'common/importer/firefox_importer_utils_mac.mm', 'common/importer/firefox_importer_utils_win.cc', 'common/importer/ie_importer_test_registry_overrider_win.cc', 'common/importer/ie_importer_test_registry_overrider_win.h', 'common/importer/ie_importer_utils_win.cc', 'common/importer/ie_importer_utils_win.h', 'common/importer/imported_bookmark_entry.cc', 'common/importer/imported_bookmark_entry.h', 'common/importer/imported_favicon_usage.cc', 'common/importer/imported_favicon_usage.h', 'common/importer/importer_bridge.cc', 'common/importer/importer_bridge.h', 'common/importer/importer_data_types.cc', 'common/importer/importer_data_types.h', 'common/importer/importer_type.h', 'common/importer/importer_url_row.cc', 'common/importer/importer_url_row.h', 'common/importer/profile_import_process_messages.cc', 'common/importer/profile_import_process_messages.h', 'common/importer/safari_importer_utils.h', 'common/importer/safari_importer_utils.mm', 'common/instant_restricted_id_cache.h', 'common/instant_types.cc', 'common/instant_types.h', 'common/localized_error.cc', 'common/localized_error.h', 'common/local_discovery/service_discovery_client.cc', 'common/local_discovery/service_discovery_client.h', 'common/logging_chrome.cc', 'common/logging_chrome.h', 'common/mac/app_mode_common.h', 'common/mac/app_mode_common.mm', 'common/mac/cfbundle_blocker.h', 'common/mac/cfbundle_blocker.mm', 'common/mac/launchd.h', 'common/mac/launchd.mm', 'common/mac/objc_method_swizzle.h', 'common/mac/objc_method_swizzle.mm', 'common/mac/objc_zombie.h', 'common/mac/objc_zombie.mm', 'common/media/webrtc_logging_messages.h', 'common/metrics/caching_permuted_entropy_provider.cc', 'common/metrics/caching_permuted_entropy_provider.h', 'common/metrics/metrics_log_base.cc', 'common/metrics/metrics_log_base.h', 'common/metrics/metrics_log_manager.cc', 'common/metrics/metrics_log_manager.h', 'common/metrics/metrics_service_base.cc', 'common/metrics/metrics_service_base.h', 'common/metrics/variations/experiment_labels.cc', 'common/metrics/variations/experiment_labels.h', 'common/metrics/variations/uniformity_field_trials.cc', 'common/metrics/variations/uniformity_field_trials.h', 'common/metrics/variations/variations_util.cc', 'common/metrics/variations/variations_util.h', 'common/multi_process_lock.h', 'common/multi_process_lock_linux.cc', 'common/multi_process_lock_mac.cc', 'common/multi_process_lock_win.cc', 'common/omaha_query_params/omaha_query_params.cc', 'common/omaha_query_params/omaha_query_params.h', 'common/omnibox_focus_state.h', 'common/partial_circular_buffer.cc', 'common/partial_circular_buffer.h', 'common/pepper_flash.cc', 'common/pepper_flash.h', 'common/pepper_permission_util.cc', 'common/pepper_permission_util.h', 'common/pref_names_util.cc', 'common/pref_names_util.h', 'common/print_messages.cc', 'common/print_messages.h', 'common/profiling.cc', 'common/profiling.h', 'common/ref_counted_util.h', 'common/render_messages.cc', 'common/render_messages.h', 'common/safe_browsing/download_protection_util.cc', 'common/safe_browsing/download_protection_util.h', 'common/safe_browsing/safebrowsing_messages.h', 'common/safe_browsing/zip_analyzer.cc', 'common/safe_browsing/zip_analyzer.h', 'common/search_provider.h', 'common/search_types.h', 'common/search_urls.cc', 'common/search_urls.h', 'common/service_messages.h', 'common/service_process_util.cc', 'common/service_process_util.h', 'common/service_process_util_linux.cc', 'common/service_process_util_mac.mm', 'common/service_process_util_posix.cc', 'common/service_process_util_posix.h', 'common/service_process_util_win.cc', 'common/spellcheck_common.cc', 'common/spellcheck_common.h', 'common/spellcheck_marker.h', 'common/spellcheck_messages.h', 'common/spellcheck_result.h', 'common/switch_utils.cc', 'common/switch_utils.h', 'common/thumbnail_score.cc', 'common/thumbnail_score.h', 'common/translate/language_detection_details.cc', 'common/translate/language_detection_details.h', 'common/translate/translate_errors.h', 'common/tts_messages.h', 'common/tts_utterance_request.cc', 'common/tts_utterance_request.h', 'common/url_constants.cc', 'common/url_constants.h', 'common/web_application_info.cc', 'common/web_application_info.h', 'common/worker_thread_ticker.cc', 'common/worker_thread_ticker.h', ], 'conditions': [ ['enable_extensions==1', { 'dependencies': [ '../device/bluetooth/bluetooth.gyp:device_bluetooth', '../device/usb/usb.gyp:device_usb', ], }, { # enable_extensions == 0 'sources/': [ ['exclude', '^common/extensions/api/'], ['include', 'common/extensions/api/extension_action/action_info.cc'], ['include', 'common/extensions/api/extension_action/action_info.h'], ['include', 'common/extensions/api/i18n/default_locale_handler.cc'], ['include', 'common/extensions/api/i18n/default_locale_handler.h'], ['include', 'common/extensions/api/identity/oauth2_manifest_handler.cc'], ['include', 'common/extensions/api/identity/oauth2_manifest_handler.h'], ['include', 'common/extensions/api/managed_mode_private/managed_mode_handler.cc'], ['include', 'common/extensions/api/managed_mode_private/managed_mode_handler.h'], ['include', 'common/extensions/api/plugins/plugins_handler.cc'], ['include', 'common/extensions/api/plugins/plugins_handler.h'], ['include', 'common/extensions/api/storage/storage_schema_manifest_handler.cc'], ['include', 'common/extensions/api/storage/storage_schema_manifest_handler.h'], ], }], ['OS=="win" or OS=="mac"', { 'sources': [ 'common/media_galleries/itunes_library.cc', 'common/media_galleries/itunes_library.h', 'common/media_galleries/picasa_types.cc', 'common/media_galleries/picasa_types.h', 'common/media_galleries/pmp_constants.h', ], }], ['OS=="mac"', { 'sources': [ 'common/media_galleries/iphoto_library.cc', 'common/media_galleries/iphoto_library.h', ], }], ['OS != "ios"', { 'dependencies': [ '<(DEPTH)/chrome/common/extensions/api/api.gyp:api', '<(DEPTH)/components/components.gyp:autofill_core_common', '<(DEPTH)/components/components.gyp:autofill_content_common', '<(DEPTH)/components/nacl.gyp:nacl_common', '<(DEPTH)/components/components.gyp:visitedlink_common', '<(DEPTH)/extensions/extensions.gyp:extensions_common', '<(DEPTH)/ipc/ipc.gyp:ipc', '<(DEPTH)/third_party/adobe/flash/flash_player.gyp:flapper_version_h', '<(DEPTH)/third_party/re2/re2.gyp:re2', '<(DEPTH)/third_party/widevine/cdm/widevine_cdm.gyp:widevine_cdm_version_h', ], }, { # OS == ios 'sources/': [ ['exclude', '^common/child_process_'], ['exclude', '^common/chrome_content_client\\.cc$'], ['exclude', '^common/chrome_version_info_posix\\.cc$'], ['exclude', '^common/common_message_generator\\.cc$'], ['exclude', '^common/common_param_traits'], ['exclude', '^common/custom_handlers/'], ['exclude', '^common/extensions/'], ['exclude', '^common/logging_chrome\\.'], ['exclude', '^common/multi_process_'], ['exclude', '^common/nacl_'], ['exclude', '^common/pepper_flash\\.'], ['exclude', '^common/profiling\\.'], ['exclude', '^common/service_process_util_'], ['exclude', '^common/spellcheck_'], ['exclude', '^common/validation_message_'], ['exclude', '^common/web_apps\\.'], # TODO(ios): Include files here as they are made to work; once # everything is online, remove everything below here and just # use the exclusions above. ['exclude', '\\.(cc|mm)$'], ['include', '_ios\\.(cc|mm)$'], ['include', '(^|/)ios/'], ['include', '^common/chrome_version_info\\.cc$'], ['include', '^common/translate'], ['include', '^common/zip'], ], 'include_dirs': [ '<(DEPTH)/breakpad/src', ], }], ['enable_printing!=0', { 'dependencies': [ '<(DEPTH)/printing/printing.gyp:printing', ], }], ['OS!="ios" and chrome_multiple_dll!=1', { 'dependencies': [ '<(DEPTH)/webkit/glue/webkit_glue.gyp:glue', ], }], ['OS=="android"', { 'sources/': [ ['exclude', '^common/chrome_version_info_posix.cc'], ['exclude', '^common/service_'], ], 'sources!': [ 'common/badge_util.cc', 'common/extensions/api/extension_action/browser_action_handler.cc', 'common/extensions/api/extension_action/page_action_handler.cc', 'common/extensions/api/spellcheck/spellcheck_handler.cc', 'common/extensions/manifest_handlers/minimum_chrome_version_checker.cc', 'common/extensions/manifest_handlers/nacl_modules_handler.cc', 'common/icon_with_badge_image_source.cc', 'common/importer/imported_bookmark_entry.cc', 'common/importer/importer_bridge.cc', 'common/importer/importer_data_types.cc', 'common/importer/importer_url_row.cc', 'common/net/url_util.cc', 'common/spellcheck_common.cc', ], }], ['OS=="win"', { 'include_dirs': [ '<(DEPTH)/breakpad/src', '<(DEPTH)/third_party/wtl/include', ], }], ['enable_mdns == 1', { 'sources': [ 'common/local_discovery/local_discovery_messages.h', ] }], ['toolkit_uses_gtk == 1', { 'dependencies': [ '../build/linux/system.gyp:gtk', ], 'export_dependent_settings': [ '../third_party/sqlite/sqlite.gyp:sqlite', ], 'link_settings': { 'libraries': [ '-lX11', '-lXrender', '-lXss', '-lXext', ], }, }], ['chromeos==1', { 'sources!': [ 'common/chrome_version_info_linux.cc', ], }], ['OS=="mac"', { 'dependencies': [ '../third_party/mach_override/mach_override.gyp:mach_override', ], 'include_dirs': [ '<(DEPTH)/breakpad/src', '../third_party/GTM', ], 'sources!': [ 'common/child_process_logging_posix.cc', 'common/chrome_version_info_posix.cc', ], }], ['remoting==1', { 'dependencies': [ '../remoting/remoting.gyp:remoting_client_plugin', ], }], ['enable_automation==0', { 'sources/': [ ['exclude', '^common/automation_'] ] }], ['enable_plugins==0', { 'source!' : [ 'common/pepper_permission_util.cc', ], }], ['use_system_nspr==1', { 'dependencies': [ '<(DEPTH)/base/third_party/nspr/nspr.gyp:nspr', ], }], ['enable_webrtc==0', { 'sources!': [ 'common/media/webrtc_logging_messages.h', ] }], ['enable_printing==0', { 'sources!': [ 'common/print_messages.cc', 'common/print_messages.h', ] }], ['configuration_policy==1', { 'dependencies': [ '<(DEPTH)/components/components.gyp:policy', ], }], ], 'target_conditions': [ ['OS == "ios"', { 'sources/': [ # Pull in specific Mac files for iOS (which have been filtered out # by file name rules). ['include', '^common/chrome_version_info_mac\\.mm$'], ], }], ], 'export_dependent_settings': [ '../base/base.gyp:base', 'metrics_proto', ], }, { 'target_name': 'common_version', 'type': 'none', 'conditions': [ ['os_posix == 1 and OS != "mac" and OS != "ios"', { 'direct_dependent_settings': { 'include_dirs': [ '<(SHARED_INTERMEDIATE_DIR)', ], }, # Because posix_version generates a header, we must set the # hard_dependency flag. 'hard_dependency': 1, 'actions': [ { 'action_name': 'posix_version', 'variables': { 'lastchange_path': '<(DEPTH)/build/util/LASTCHANGE', 'version_py_path': 'tools/build/version.py', 'version_path': 'VERSION', 'template_input_path': 'common/chrome_version_info_posix.h.version', }, 'conditions': [ [ 'branding == "Chrome"', { 'variables': { 'branding_path': 'app/theme/google_chrome/BRANDING', }, }, { # else branding!="Chrome" 'variables': { 'branding_path': 'app/theme/chromium/BRANDING', }, }], ], 'inputs': [ '<(template_input_path)', '<(version_path)', '<(branding_path)', '<(lastchange_path)', ], 'outputs': [ '<(SHARED_INTERMEDIATE_DIR)/chrome/common/chrome_version_info_posix.h', ], 'action': [ 'python', '<(version_py_path)', '-f', '<(version_path)', '-f', '<(branding_path)', '-f', '<(lastchange_path)', '<(template_input_path)', '<@(_outputs)', ], 'message': 'Generating version information', }, ], }], ], }, { 'target_name': 'common_net', 'type': 'static_library', 'sources': [ 'common/net/net_error_info.cc', 'common/net/net_error_info.h', 'common/net/net_resource_provider.cc', 'common/net/net_resource_provider.h', 'common/net/predictor_common.h', 'common/net/url_fixer_upper.cc', 'common/net/url_fixer_upper.h', 'common/net/url_util.cc', 'common/net/url_util.h', 'common/net/x509_certificate_model.cc', 'common/net/x509_certificate_model_nss.cc', 'common/net/x509_certificate_model_openssl.cc', 'common/net/x509_certificate_model.h', ], 'dependencies': [ '<(DEPTH)/base/base.gyp:base', '<(DEPTH)/chrome/chrome_resources.gyp:chrome_resources', '<(DEPTH)/chrome/chrome_resources.gyp:chrome_strings', '<(DEPTH)/crypto/crypto.gyp:crypto', '<(DEPTH)/net/net.gyp:net_resources', '<(DEPTH)/net/net.gyp:net', '<(DEPTH)/third_party/icu/icu.gyp:icui18n', '<(DEPTH)/third_party/icu/icu.gyp:icuuc', ], 'conditions': [ ['OS != "ios"', { 'dependencies': [ '<(DEPTH)/gpu/gpu.gyp:gpu_ipc', ], }, { # OS == ios 'sources!': [ 'common/net/net_resource_provider.cc', 'common/net/x509_certificate_model.cc', ], }], ['os_posix == 1 and OS != "mac" and OS != "ios" and OS != "android"', { 'dependencies': [ '../build/linux/system.gyp:ssl', ], }, ], ['os_posix != 1 or OS == "mac" or OS == "ios"', { 'sources!': [ 'common/net/x509_certificate_model_nss.cc', 'common/net/x509_certificate_model_openssl.cc', ], }, ], ['OS == "android"', { 'dependencies': [ '../third_party/openssl/openssl.gyp:openssl', ], }, ], ['use_openssl==1', { 'sources!': [ 'common/net/x509_certificate_model_nss.cc', ], }, { # else !use_openssl: remove the unneeded files 'sources!': [ 'common/net/x509_certificate_model_openssl.cc', ], }, ], ['OS=="win"', { # TODO(jschuh): crbug.com/167187 fix size_t to int truncations. 'msvs_disabled_warnings': [4267, ], }, ], ], }, { # Protobuf compiler / generator for the safebrowsing client # model proto and the client-side detection (csd) request # protocol buffer. 'target_name': 'safe_browsing_proto', 'type': 'static_library', 'sources': [ 'common/safe_browsing/client_model.proto', 'common/safe_browsing/csd.proto' ], 'variables': { 'proto_in_dir': 'common/safe_browsing', 'proto_out_dir': 'chrome/common/safe_browsing', }, 'includes': [ '../build/protoc.gypi' ], }, { # Protobuf compiler / generator for UMA (User Metrics Analysis). 'target_name': 'metrics_proto', 'type': 'static_library', 'sources': [ 'common/metrics/proto/chrome_experiments.proto', 'common/metrics/proto/chrome_user_metrics_extension.proto', 'common/metrics/proto/histogram_event.proto', 'common/metrics/proto/omnibox_event.proto', 'common/metrics/proto/perf_data.proto', 'common/metrics/proto/permuted_entropy_cache.proto', 'common/metrics/proto/profiler_event.proto', 'common/metrics/proto/system_profile.proto', 'common/metrics/proto/user_action_event.proto', ], 'variables': { 'proto_in_dir': 'common/metrics/proto', 'proto_out_dir': 'chrome/common/metrics/proto', }, 'includes': [ '../build/protoc.gypi' ], }, ], }
[ "karun.matharu@gmail.com" ]
karun.matharu@gmail.com
365b30e755275b51ea756b459b30ccf909f26f4f
17ae1b4195e16f00209bc06e605eb48ad7d4f3a0
/snowflake.py
2cac8d318876f6a95f3f381f7b415548adcccbae
[]
no_license
alizaheda/TurtleSnowflakes
e8a0525ce97d8a225e459d5a66671c1144915b90
38310536e759e5e7b17b822b63a6b4965afa281c
refs/heads/main
2023-01-02T07:15:14.822940
2020-10-29T14:32:42
2020-10-29T14:32:42
null
0
0
null
null
null
null
UTF-8
Python
false
false
599
py
#!/bin/python3 import turtle import random shelly = turtle.Turtle() turtle.Screen().bgcolor("white") colors = ["blue", "cyan", "purple", "grey", "pink", "violet", "black"] shelly.color("cyan") def branch(): for i in range(3): shelly.color(random.choice(colors)) for j in range(3): shelly.forward(30) shelly.backward(30) shelly.right(45) shelly.left(90) shelly.backward(30) shelly.left(45) shelly.right(90) shelly.forward(90) for k in range(8): branch() shelly.left(45)
[ "noreply@github.com" ]
noreply@github.com
679cfdd0365a647b8e7a4315c23c688e6dd127a1
408491958cece161e3f7b27d10926b5cd80b4b14
/Mathematics/Number Theory/Breaking Sticks/Breaking Sticks.py
042d8916718a219b47c55f65ae0809631828edd8
[]
no_license
Snoblomma/HackerRank
279212173fbe0024ecb5e34fdbacc1c01faad7f5
1547913ada66d13fd59b06bc2781911c0895fbbf
refs/heads/master
2021-07-11T09:16:43.323607
2021-03-23T22:52:11
2021-03-23T22:52:11
70,170,819
0
0
null
null
null
null
UTF-8
Python
false
false
590
py
#!/bin/python3 import math def divisor(number): for i in range(2, math.ceil(math.sqrt(number))+1): if (number % i == 0): return number // i return 1 def breaks(n): if n == 1: return 1 count = n a = n while a > 1: d = divisor(a) count += d a = d return count def longestSequence(a): s = 0 for item in a: s += breaks(item) return s if __name__ == '__main__': n = int(input()) a = list(map(int, input().rstrip().split())) result = longestSequence(a) print(result)
[ "snoblomma@gmail.com" ]
snoblomma@gmail.com
a25f717347636e8373ba3c99cfd0b09fcab0b1a0
3d3c0605a96f314c6d71f0c79f2da37ca1ab8545
/Python/ejercicioFunciones/ejercicio6Funciones.py
c60467c668685a9ad3efa4a780cb5fbe7d737042
[]
no_license
dascastrillo/lenguajemarca.guthub.io
77432e1d7c2c300b4ed3b4c9a8a5585b75c47241
1b8c34d157c66dd33e6d8f98853601aceb968a0b
refs/heads/master
2020-08-30T07:16:24.361223
2020-05-23T17:49:27
2020-05-23T17:49:27
218,302,860
0
1
null
null
null
null
UTF-8
Python
false
false
2,534
py
import os def area_rectangulo(): print("Introduce la base : ") base=pedirNumeroEntero() print("Introduce la altura : ") altura=pedirNumeroEntero() area_rectangulo=base*altura print("El area de un Rectangulo es : ",area_rectangulo) input("Presione una tecla para continuar...") def pedirNumeroEntero(): while True: try: num = int(input()) break except ValueError: print('Error, al introducir los datos') print ("Intentalo de nuevo") return num def area_circulo(): pi=3.14159265359 print('introduce el numero del radio: ') radio=pedirNumerosReales() r= pi * (radio ** 2) print('El area del Circulo es: ', r) input('Presiona cualquier tecla para continuar...') def pedirNumerosReales(): while True: try: NumReal = float(input()) break except ValueError: print('Error al introducir numero') print('Vuelve a introducir numero ') return NumReal def VolClindro(): pi=3.14159265359 print('introduce el valor de radio: ') r=pedirNumerosReales() #radio print(('introduce la altura: ')) h=pedirNumerosReales() #altura Volumen= pi * (r ** 2) * (h) print('El volumen del cilindro es: ', Volumen) input('Presiona cualquier tecla para continuar...') def ElevaPotencia(): print('introduce la base: ') base=pedirNumerosReales() print('introduce el exponenete: ') exponente= pedirNumerosReales() resultado= base ** exponente print('El resultado es: ', resultado) input('Presiona cualquier tecla para continuar...') while True: #borrar la pantalla Para DOS/Windows os.system ("cls") print ("1. Calcular el area del rectangulo") # Area Circulo= π r² print ("2. Calcular el Area de un circulo") # debe calcule el volumen de un cilindro usando el dato que # le devuelva la funcion del Area de Circulo. # Volumen Cilindro = π r² h print ("3. Calcular el Volumen de un Cilindro") print ("4. Elevar un número a una potencia ") print ("5. Salir") print ("Elige una opcion") opcion = pedirNumeroEntero() if opcion == 1: area_rectangulo() elif opcion == 2: area_circulo() elif opcion == 3: VolClindro() elif opcion == 4: ElevaPotencia() elif opcion == 5: break else: print ("Introduce un numero entre 1 y 3") print ("Fin del Programa")
[ "dascastrillo@gmail.com" ]
dascastrillo@gmail.com
d03578c423b75b0a881d10b32f169ad9a5075cbb
f445450ac693b466ca20b42f1ac82071d32dd991
/generated_tempdir_2019_09_15_163300/generated_part005394.py
e5781c7991690423aaa123393d0e5d46def81e37
[]
no_license
Upabjojr/rubi_generated
76e43cbafe70b4e1516fb761cabd9e5257691374
cd35e9e51722b04fb159ada3d5811d62a423e429
refs/heads/master
2020-07-25T17:26:19.227918
2019-09-15T15:41:48
2019-09-15T15:41:48
208,357,412
4
1
null
null
null
null
UTF-8
Python
false
false
3,559
py
from sympy.abc import * from matchpy.matching.many_to_one import CommutativeMatcher from matchpy import * from matchpy.utils import VariableWithCount from collections import deque from multiset import Multiset from sympy.integrals.rubi.constraints import * from sympy.integrals.rubi.utility_function import * from sympy.integrals.rubi.rules.miscellaneous_integration import * from sympy import * class CommutativeMatcher33668(CommutativeMatcher): _instance = None patterns = { 0: (0, Multiset({0: 1, 1: 1}), [ ]) } subjects = {} subjects_by_id = {} bipartite = BipartiteGraph() associative = Mul max_optional_count = 0 anonymous_patterns = set() def __init__(self): self.add_subject(None) @staticmethod def get(): if CommutativeMatcher33668._instance is None: CommutativeMatcher33668._instance = CommutativeMatcher33668() return CommutativeMatcher33668._instance @staticmethod def get_match_iter(subject): subjects = deque([subject]) if subject is not None else deque() subst0 = Substitution() # State 33667 if len(subjects) >= 1 and isinstance(subjects[0], Pow): tmp1 = subjects.popleft() subjects2 = deque(tmp1._args) # State 33669 if len(subjects2) >= 1: tmp3 = subjects2.popleft() subst1 = Substitution(subst0) try: subst1.try_add_variable('i2.2.1.2.2.2.1', tmp3) except ValueError: pass else: pass # State 33670 if len(subjects2) >= 1: tmp5 = subjects2.popleft() subst2 = Substitution(subst1) try: subst2.try_add_variable('i2.2.1.2.2.2.2', tmp5) except ValueError: pass else: pass # State 33671 if len(subjects2) == 0: pass # State 33672 if len(subjects) == 0: pass # 0: x**m yield 0, subst2 subjects2.appendleft(tmp5) subjects2.appendleft(tmp3) subjects.appendleft(tmp1) if len(subjects) >= 1 and isinstance(subjects[0], Add): tmp7 = subjects.popleft() associative1 = tmp7 associative_type1 = type(tmp7) subjects8 = deque(tmp7._args) matcher = CommutativeMatcher33674.get() tmp9 = subjects8 subjects8 = [] for s in tmp9: matcher.add_subject(s) for pattern_index, subst1 in matcher.match(tmp9, subst0): pass if pattern_index == 0: pass # State 33691 if len(subjects) == 0: pass # 1: f + e*x**r yield 1, subst1 subjects.appendleft(tmp7) return yield from matchpy.matching.many_to_one import CommutativeMatcher from collections import deque from .generated_part005395 import * from matchpy.utils import VariableWithCount from multiset import Multiset
[ "franz.bonazzi@gmail.com" ]
franz.bonazzi@gmail.com
f6f69bd11a57079c1e860e060690db08820b94e3
67553d46a257631810f394908013b82c337e0fbd
/goat/chapter05/5.2/globals_test.py
cc3a84eb474eb4feacb54ede07ac205a359b442a
[]
no_license
bopopescu/goat-python
3f9d79eb1a9c2733345d699c98d82f91968ca5fa
c139488e2b5286033954df50ae1ca834144446f5
refs/heads/master
2022-11-21T11:25:27.921210
2020-03-06T01:02:57
2020-03-06T01:02:57
281,066,748
0
0
null
2020-07-20T09:00:08
2020-07-20T09:00:08
null
UTF-8
Python
false
false
154
py
# coding: utf-8 name = 'Charlie' def test (): # 直接访问name全局变量 print(name) # Charlie name = '孙悟空' test() print(name)
[ "34465021+jwfl724168@users.noreply.github.com" ]
34465021+jwfl724168@users.noreply.github.com
56007829d8e7c2a81edbbc469fc3a411453e739f
146dbf759064000e579985b9f4a2b98d08640380
/week4/day23/main.py
0e09501ee061ad47b0a93cdc3c884e19ffb1f3d4
[]
no_license
CW-MD/100daysofpython
8bf0d05e24c0267150a8a59da8c8684b3ac846c3
c256242d1778a036fbd5d70357b4a96d0febe6bf
refs/heads/master
2023-07-21T03:47:52.304635
2021-09-03T04:36:18
2021-09-03T04:36:18
374,596,262
2
0
null
null
null
null
UTF-8
Python
false
false
814
py
from turtle import Screen from car import Car from player import Player from time import sleep from score import Score screen = Screen() screen.setup(width=600, height=600) screen.bgcolor('white') screen.tracer(0) game_running = True screen.listen() player = Player() score = Score() carManager = Car() screen.onkey(player.move_up, 'Up') loop_counter = 0 while game_running: carManager.create_car() if player.ycor() >= 280: score.update_score() player.reset_pos() carManager.increase_speed() carManager.move_car() for x in carManager.car_list: if player.distance(x) < 20: print('Game Over') game_running = False print(len(carManager.car_list)) sleep(.1) loop_counter+=1 screen.update() screen.exitonclick()
[ "cdayton96@gmail.com" ]
cdayton96@gmail.com
b1b907960a85336e25b798a3aa7047ff700dbb33
86ed9f6558517ef490e4d187db478c0334320d74
/DeepLearningA-ZUDEMY/AutoEncoders/ae_dl.py
7ddd1e4483485010765a7119fd74ada82773540b
[]
no_license
lucigrigo/UdemyCourses
435192eb6dafde0ed0f391e9616562ebaee7f494
e50feae6a26be50299cdeffd2f16498d4684ada3
refs/heads/master
2023-04-23T14:44:36.500647
2021-05-07T22:10:47
2021-05-07T22:10:47
278,051,106
0
0
null
2020-10-13T23:50:55
2020-07-08T09:47:29
Jupyter Notebook
UTF-8
Python
false
false
3,505
py
# AutoEncoders # Importing libraries import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.parallel import torch.optim as optim import torch.utils.data from torch.autograd import Variable # Importing the dataset movies = pd.read_csv('ml-1m/movies.dat', sep = '::', header = None, engine = 'python', encoding = 'latin-1') users = pd.read_csv('ml-1m/users.dat', sep = '::', header = None, engine = 'python', encoding = 'latin-1') ratings = pd.read_csv('ml-1m/ratings.dat', sep = '::', header = None, engine = 'python', encoding = 'latin-1') # Preparing the train test and the test set training_set = pd.read_csv('ml-100k/u1.base', delimiter = '\t') training_set = np.array(training_set, dtype = 'int') test_set = pd.read_csv('ml-100k/u1.test', delimiter = '\t') test_set = np.array(test_set, dtype = 'int') # Getting the number of users and movies nb_users = int(max(max(training_set[:, 0]), max(test_set[:, 0]))) nb_movies = int(max(max(training_set[:, 1]), max(test_set[:, 1]))) # Converting the data into an array with users as lines and movies as columns def conv(data): new_data = [] for id_user in range(1, nb_users + 1): id_movies = data[:, 1][data[:, 0] == id_user] id_ratings = data[:, 2][data[:, 0] == id_user] ratings = np.zeros(nb_movies) ratings[id_movies - 1] = id_ratings new_data.append(list(ratings)) return new_data training_set = conv(training_set) test_set = conv(test_set) # Converting the data into Torch tensors training_set = torch.FloatTensor(training_set) test_set = torch.FloatTensor(test_set) # Creating the architecture of the Neural Network class SAE(nn.Module): def __init__(self): super(SAE, self).__init__() self.fc1 = nn.Linear(nb_movies, 20) self.fc2 = nn.Linear(20, 10) self.fc3 = nn.Linear(10, 20) self.fc4 = nn.Linear(20, nb_movies) self.activation = nn.Sigmoid() def forward(self, x): x = self.activation(self.fc1(x)) x = self.activation(self.fc2(x)) x = self.activation(self.fc3(x)) x = self.fc4(x) return x sae = SAE() criterion = nn.MSELoss() optimizer = optim.RMSprop(sae.parameters(), lr = 0.01, weight_decay = 0.5) # Training the SAE nb_epoch = 200 for epoch in range(1, nb_epoch + 1): train_loss = 0 s = 0. for id_user in range(nb_users): input = Variable(training_set[id_user]).unsqueeze(0) target = input.clone() if torch.sum(target.data > 0) > 0: output = sae(input) target.require_grad = False output[target == 0] = 0 loss = criterion(output, target) mean_corrector = nb_movies/float(torch.sum(target.data > 0) + 1e-10) loss.backward() train_loss += np.sqrt(loss.data * mean_corrector) s += 1. optimizer.step() print('epoch: ' + str(epoch) + ' train_loss: ' + str(train_loss / s)) # Testing the SAE test_loss = 0 s = 0. for id_user in range(nb_users): input = Variable(training_set[id_user]).unsqueeze(0) target = Variable(test_set[id_user]) if torch.sum(target.data > 0) > 0: output = sae(input) target.require_grad = False output[target == 0] = 0 loss = criterion(output, target) mean_corrector = nb_movies/float(torch.sum(target.data > 0) + 1e-10) test_loss += np.sqrt(loss.data*mean_corrector) s += 1. print('test loss: '+str(test_loss/s))
[ "lucigrigo@yahoo.com" ]
lucigrigo@yahoo.com
f9b7d16b06f903f74cb2eeb8c5aa03d5381e9ed8
b56715d8c602d14da793bb3a25433663d4f31fbd
/invoice/migrations/0004_auto_20170519_1322.py
97b671415359851c052466f6df329ccfdf5abc73
[]
no_license
mincaeuro/faktury
0fd35c0f1d0c7c76331a51f3303af4135d660160
970c91e7caa068d7576ce4434bb277006f6fdfa6
refs/heads/master
2022-09-19T04:40:58.196916
2022-09-03T14:42:08
2022-09-03T14:42:08
42,316,831
0
0
null
null
null
null
UTF-8
Python
false
false
863
py
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-05-19 11:22 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('invoice', '0003_auto_20170519_1312'), ] operations = [ migrations.AlterField( model_name='firma', name='cislo_swift', field=models.CharField(choices=[('', 'vyberte'), ('SUBASKBX', 'Všeobecná úverová banka, a. s.'), ('GIBASKBX', 'Slovenská sporiteľňa, a. s.'), ('TATRSKBX', 'Tatra banka, a. s.'), ('BREXSKBX', 'MBANK – BRE Bank SA, pobočka zahraničnej banky mBank v SR'), ('UNCRSKBX', 'UniCredit Bank Czech Republic and Slovakia, a. s., pobočka zahr. banky'), ('CEKOSKBX', 'ČSOB – Československá obchodná banka, a.s.')], default='', max_length=8), ), ]
[ "noreply@github.com" ]
noreply@github.com
2dc917a66e8ef838946a5fcb757890bce77a7963
9405aa570ede31a9b11ce07c0da69a2c73ab0570
/aliyun-python-sdk-kms/aliyunsdkkms/request/v20160120/GenerateDataKeyWithoutPlaintextRequest.py
681ae27d16cff738aea6473faf406f81efbeea7d
[ "Apache-2.0" ]
permissive
liumihust/aliyun-openapi-python-sdk
7fa3f5b7ea5177a9dbffc99e73cf9f00e640b72b
c7b5dd4befae4b9c59181654289f9272531207ef
refs/heads/master
2020-09-25T12:10:14.245354
2019-12-04T14:43:27
2019-12-04T14:43:27
226,002,339
1
0
NOASSERTION
2019-12-05T02:50:35
2019-12-05T02:50:34
null
UTF-8
Python
false
false
2,008
py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. from aliyunsdkcore.request import RpcRequest from aliyunsdkkms.endpoint import endpoint_data class GenerateDataKeyWithoutPlaintextRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Kms', '2016-01-20', 'GenerateDataKeyWithoutPlaintext','kms') self.set_protocol_type('https') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_EncryptionContext(self): return self.get_query_params().get('EncryptionContext') def set_EncryptionContext(self,EncryptionContext): self.add_query_param('EncryptionContext',EncryptionContext) def get_KeyId(self): return self.get_query_params().get('KeyId') def set_KeyId(self,KeyId): self.add_query_param('KeyId',KeyId) def get_KeySpec(self): return self.get_query_params().get('KeySpec') def set_KeySpec(self,KeySpec): self.add_query_param('KeySpec',KeySpec) def get_NumberOfBytes(self): return self.get_query_params().get('NumberOfBytes') def set_NumberOfBytes(self,NumberOfBytes): self.add_query_param('NumberOfBytes',NumberOfBytes)
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com
0e7ff815cea27a8a05cb59b0e158e66ee68977ce
1896685500833ba2e4e25400a03e10536dc57ad5
/apimpe/wsgi.py
7ebc7b896b1a99ceded6af9f77e7fbd203d23e58
[]
no_license
Oswaldinho24k/MPE-API
04e5d134199083300c2eac2b2d21e206e4306eeb
2e1d7b282f994867c04d31b09395785d73d90b9d
refs/heads/master
2020-06-21T14:53:18.903127
2016-12-02T18:57:25
2016-12-02T18:57:25
74,783,930
0
0
null
null
null
null
UTF-8
Python
false
false
482
py
""" WSGI config for apimpe project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise os.environ.setdefault("DJANGO_SETTINGS_MODULE", "apimpe.settings") application = get_wsgi_application() application = DjangoWhiteNoise(application)
[ "oswalfut_96@hotmail.com" ]
oswalfut_96@hotmail.com
a9a35564056a41b3c08ac75c0aab061160226698
0873dc132ebdb02b42564341ab7ccd979e8a3b54
/Numpy/numpy string.py
fce884f2f266c7518c4268eac710cca4946804af
[]
no_license
kamal-ops/Data_Science_practics
cd8d555dae51136f9a8532bfdcca176ae5f00565
68cd8d618a18904d9d7c5134a6ad3ffc99503cec
refs/heads/master
2023-03-31T00:23:11.834005
2021-03-20T10:10:33
2021-03-20T10:10:33
349,689,034
0
0
null
null
null
null
UTF-8
Python
false
false
543
py
#!/usr/bin/env python # coding: utf-8 # In[1]: import numpy as np # In[2]: str1 = "kamal kishor swami" str2 = "asiistant pipline developer" # In[3]: np.char.add(str1, str2) # In[4]: np.char.lower(str1) # In[5]: np.char.upper(str1) # In[8]: np.char.center(str1, 60) # In[9]: np.char.center(str1, 60, fillchar="*") # In[11]: np.char.replace(str1,"kamal kishor swami", "Palak Swami") # In[12]: np.char.count(str1, "a") # In[14]: np.char.find(str1, "kamal") # In[16]: np.char.title(str1) # In[ ]:
[ "agrawatkamal@gmail.com" ]
agrawatkamal@gmail.com
87ce0d254c7914887459b87b8d9e12b078769298
d43c0ac4f3e707693c839687cc502282146cbf39
/leetcode/linked-list-cycle-ii/test_.py
380f7e7c9b5e9fff509b1398eebb3755c8396a5e
[]
no_license
ftlka/problems
d64a9b07767c40fa959487c9c23e54b5f4714439
e1fc8dad3a881d4f2e2d9e871b33d7f817683734
refs/heads/master
2020-04-27T20:54:40.950133
2019-04-02T15:14:04
2019-04-02T15:14:04
174,675,505
0
0
null
null
null
null
UTF-8
Python
false
false
628
py
from solution import ListNode, Solution s = Solution() # test 1 root = cur = ListNode(3) loop_node = cur.next = ListNode(2) cur = cur.next cur.next = ListNode(0) cur = cur.next cur.next = ListNode(-4) cur = cur.next cur.next = loop_node assert s.detectCycle(root).val == 2 # test 2 root = cur = ListNode(1) cur.next = ListNode(2) cur.next.next = cur assert s.detectCycle(root).val == 1 # test 3 root = ListNode(1) assert not s.detectCycle(root) # test 4 assert not s.detectCycle(None) # test 5 root = cur = ListNode(1) for i in range(2, 6): cur.next = ListNode(i) cur = cur.next assert not s.detectCycle(root)
[ "smart.Julia@yandex.ru" ]
smart.Julia@yandex.ru
59cee6f8de1719cbc71645dcc02d79317246d9ea
ce083128fa87ca86c65059893aa8882d088461f5
/python/python-salad-bdd/.venv/bin/subunit-filter
317293fe0fb7c7007d0cf0b7e77ec7d6c6da347c
[]
no_license
marcosptf/fedora
581a446e7f81d8ae9a260eafb92814bc486ee077
359db63ff1fa79696b7bc803bcfa0042bff8ab44
refs/heads/master
2023-04-06T14:53:40.378260
2023-03-26T00:47:52
2023-03-26T00:47:52
26,059,824
6
5
null
2022-12-08T00:43:21
2014-11-01T18:48:56
null
UTF-8
Python
false
false
7,071
#!/home/marcosptf/developer/python-bdd/.venv/bin/python2 # subunit: extensions to python unittest to get test results from subprocesses. # Copyright (C) 200-2013 Robert Collins <robertc@robertcollins.net> # (C) 2009 Martin Pool # # Licensed under either the Apache License, Version 2.0 or the BSD 3-clause # license at the users choice. A copy of both licenses are available in the # project source as Apache-2.0 and BSD. You may not use this file except in # compliance with one of these two licences. # # Unless required by applicable law or agreed to in writing, software # distributed under these licenses is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # license you chose for the specific language governing permissions and # limitations under that license. # """Filter a subunit stream to include/exclude tests. The default is to strip successful tests. Tests can be filtered by Python regular expressions with --with and --without, which match both the test name and the error text (if any). The result contains tests which match any of the --with expressions and none of the --without expressions. For case-insensitive matching prepend '(?i)'. Remember to quote shell metacharacters. """ from optparse import OptionParser import sys import re from testtools import ExtendedToStreamDecorator, StreamToExtendedDecorator from subunit import ( DiscardStream, ProtocolTestCase, StreamResultToBytes, read_test_list, ) from subunit.filters import filter_by_result, find_stream from subunit.test_results import ( and_predicates, make_tag_filter, TestResultFilter, ) def make_options(description): parser = OptionParser(description=__doc__) parser.add_option("--error", action="store_false", help="include errors", default=False, dest="error") parser.add_option("-e", "--no-error", action="store_true", help="exclude errors", dest="error") parser.add_option("--failure", action="store_false", help="include failures", default=False, dest="failure") parser.add_option("-f", "--no-failure", action="store_true", help="exclude failures", dest="failure") parser.add_option("--passthrough", action="store_false", help="Forward non-subunit input as 'stdout'.", default=False, dest="no_passthrough") parser.add_option("--no-passthrough", action="store_true", help="Discard all non subunit input.", default=False, dest="no_passthrough") parser.add_option("-s", "--success", action="store_false", help="include successes", dest="success") parser.add_option("--no-success", action="store_true", help="exclude successes", default=True, dest="success") parser.add_option("--no-skip", action="store_true", help="exclude skips", dest="skip") parser.add_option("--xfail", action="store_false", help="include expected failures", default=True, dest="xfail") parser.add_option("--no-xfail", action="store_true", help="exclude expected failures", default=True, dest="xfail") parser.add_option( "--with-tag", type=str, help="include tests with these tags", action="append", dest="with_tags") parser.add_option( "--without-tag", type=str, help="exclude tests with these tags", action="append", dest="without_tags") parser.add_option("-m", "--with", type=str, help="regexp to include (case-sensitive by default)", action="append", dest="with_regexps") parser.add_option("--fixup-expected-failures", type=str, help="File with list of test ids that are expected to fail; on failure " "their result will be changed to xfail; on success they will be " "changed to error.", dest="fixup_expected_failures", action="append") parser.add_option("--without", type=str, help="regexp to exclude (case-sensitive by default)", action="append", dest="without_regexps") parser.add_option("-F", "--only-genuine-failures", action="callback", callback=only_genuine_failures_callback, help="Only pass through failures and exceptions.") parser.add_option("--rename", action="append", nargs=2, help="Apply specified regex subsitutions to test names.", dest="renames", default=[]) return parser def only_genuine_failures_callback(option, opt, value, parser): parser.rargs.insert(0, '--no-passthrough') parser.rargs.insert(0, '--no-xfail') parser.rargs.insert(0, '--no-skip') parser.rargs.insert(0, '--no-success') def _compile_re_from_list(l): return re.compile("|".join(l), re.MULTILINE) def _make_regexp_filter(with_regexps, without_regexps): """Make a callback that checks tests against regexps. with_regexps and without_regexps are each either a list of regexp strings, or None. """ with_re = with_regexps and _compile_re_from_list(with_regexps) without_re = without_regexps and _compile_re_from_list(without_regexps) def check_regexps(test, outcome, err, details, tags): """Check if this test and error match the regexp filters.""" test_str = str(test) + outcome + str(err) + str(details) if with_re and not with_re.search(test_str): return False if without_re and without_re.search(test_str): return False return True return check_regexps def _compile_rename(patterns): def rename(name): for (from_pattern, to_pattern) in patterns: name = re.sub(from_pattern, to_pattern, name) return name return rename def _make_result(output, options, predicate): """Make the result that we'll send the test outcomes to.""" fixup_expected_failures = set() for path in options.fixup_expected_failures or (): fixup_expected_failures.update(read_test_list(path)) return StreamToExtendedDecorator(TestResultFilter( ExtendedToStreamDecorator( StreamResultToBytes(output)), filter_error=options.error, filter_failure=options.failure, filter_success=options.success, filter_skip=options.skip, filter_xfail=options.xfail, filter_predicate=predicate, fixup_expected_failures=fixup_expected_failures, rename=_compile_rename(options.renames))) def main(): parser = make_options(__doc__) (options, args) = parser.parse_args() regexp_filter = _make_regexp_filter( options.with_regexps, options.without_regexps) tag_filter = make_tag_filter(options.with_tags, options.without_tags) filter_predicate = and_predicates([regexp_filter, tag_filter]) filter_by_result( lambda output_to: _make_result(sys.stdout, options, filter_predicate), output_path=None, passthrough=(not options.no_passthrough), forward=False, protocol_version=2, input_stream=find_stream(sys.stdin, args)) sys.exit(0) if __name__ == '__main__': main()
[ "marcosptf@yahoo.com.br" ]
marcosptf@yahoo.com.br
bbd4ab02b1742430ca058c70e177f838b5038b08
4474a063ce2c68afac0ccbcee87248b8aa55782d
/entregables/sin_categoria/617A.py
ad4d74d9db7ca43ffbd237e4f9b54a4229e9d867
[]
no_license
danielTeniente/codeForces
c16dd636a2243597dff5cb4e1e9bd7c3a2d1b510
889616477e2f2478e1816f752588cdafd44a9b82
refs/heads/master
2023-07-25T02:24:03.795222
2021-09-03T23:06:05
2021-09-03T23:06:05
275,078,167
1
0
null
null
null
null
UTF-8
Python
false
false
97
py
# A. Elephant x = int(input()) paso = 5 pasos = x//5 if(pasos*5<x): pasos+=1 print(pasos)
[ "daniel.diaz.bedoya@outlook.com" ]
daniel.diaz.bedoya@outlook.com
bbfc3ac9fe50c2e27f5a47e2084a42c2474f0030
6b75ed02526ad0f2e654bf7cdaba71c70bd9481d
/merchant.py
74728d6964f4a50d0150c011d260b80dfc69f343
[]
no_license
Benosu998/Fair-Exchange-e-Commerce
0686de9304e34668c7c40bbe01fa661ecb8ae43b
57d748d0e914853442e7cc3c6be7165bacdac48d
refs/heads/master
2021-02-13T00:30:27.741387
2020-03-08T17:48:29
2020-03-08T17:48:29
244,645,478
0
0
null
null
null
null
UTF-8
Python
false
false
2,029
py
import socket import sec from Crypto.PublicKey import RSA from Crypto.Random import get_random_bytes import pickle client_public = None # Load Merchant Private Key merchant_private = RSA.import_key(open("merchant_private.pem").read()) # Load Payment Gateway Public Key payment_gateway_public = RSA.import_key(open("payment_gateway_receiver.pem").read()) Sid = get_random_bytes(16) def Setup(socket_client): global merchant_private global client_public # 1.Read Client Public key and load it data = socket_client.recv(1024) client_public = RSA.import_key(sec.decrypt_data(data, merchant_private)) # 2.Send to Client Sid+Sig(Sid) data = [Sid, sec.sign(Sid, merchant_private)] socket_client.send(sec.encrypt_data(pickle.dumps(data), client_public)) def Exchange(socket_client, socket_PG): # 3.Read {PM,PO} data = sec.decrypt_data(socket_client.recv(2048), merchant_private) PM, PO = pickle.loads(data) dataPO, signPO = PO if sec.checksign(dataPO, client_public, signPO): dataPO = pickle.loads(dataPO) signature = sec.sign(pickle.dumps([dataPO[1], client_public.export_key(), dataPO[2]]), merchant_private) sendData = pickle.dumps((PM, signature)) # 4. Send {PM,SigM{..}} to PG socket_PG.send(sec.encrypt_data(sendData, payment_gateway_public)) # 5. Recieve Response from PG dataCr = socket_PG.recv(2048) data = sec.decrypt_data(dataCr, merchant_private) # 6. Send Response to CLinet socket_client.send(sec.encrypt_data(data, client_public)) if __name__ == "__main__": with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind(("127.0.0.1", 1234)) s.listen(1) (connection, address) = s.accept() print("Connected address:", address) sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sk.connect(("127.0.0.1", 4321)) Setup(connection) Exchange(connection, sk) connection.close() print("Server closed") sk.close()
[ "46503231+Benosu998@users.noreply.github.com" ]
46503231+Benosu998@users.noreply.github.com
51719366dd3b45e9da2070caf4e1ca0906df0c1b
24d8cf871b092b2d60fc85d5320e1bc761a7cbe2
/eXe/rev2283-2409/base-trunk-2283/prototype/pyfox/setup.py
58da3fb0318bb0b263de8f582d9d2d07804158ca
[]
no_license
joliebig/featurehouse_fstmerge_examples
af1b963537839d13e834f829cf51f8ad5e6ffe76
1a99c1788f0eb9f1e5d8c2ced3892d00cd9449ad
refs/heads/master
2016-09-05T10:24:50.974902
2013-03-28T16:28:47
2013-03-28T16:28:47
9,080,611
3
2
null
null
null
null
UTF-8
Python
false
false
1,325
py
import os from distutils.core import setup, Extension Moz="/home/djm/work/firefox/mozilla" MozDist=Moz+"/dist" setup(name='pyfoxutil', version='1.0', ext_modules=[Extension('_pyfoxutil', ['pyfoxutil.cpp'], include_dirs=[MozDist+"/include/embed_base", MozDist+"/include/string", MozDist+"/include/xpcom", MozDist+"/include/widget", MozDist+"/include/nspr", MozDist+"/include/gfx", MozDist+"/include/webbrwsr", MozDist+"/include/uriloader", Moz+"/extensions/python/xpcom/src", ], library_dirs = [Moz+"/extensions/python/xpcom/src", MozDist+"/lib"], libraries = ["nspr4", "plc4", "plds4", "xpcomcomponents_s", "embed_base_s", "_xpcom", ]) ], )
[ "joliebig@fim.uni-passau.de" ]
joliebig@fim.uni-passau.de
6e68dfdd9028316f5f6c125e3df226f54f2e192e
8f865c2d5e6c44692d7405a17990509b299a0a4c
/libs/labyrinthe/labyrinthe.py
78ab1af33ed42dd895b5cb9c82b9b15f1b906cf4
[]
no_license
de-Pret-Mikael/Projet
549464a3bd6e4deb209d4192fc89b07512269078
94d70cbd56ec9f13f2e9cf378f82c9e63d202f26
refs/heads/master
2023-01-29T18:02:46.271704
2020-12-08T15:28:29
2020-12-08T15:28:29
307,124,452
0
0
null
null
null
null
UTF-8
Python
false
false
9,518
py
# ▲▶▼◀■□● import random # import de la librairie random class Cell: # creation de la clss Cell qui sera utiliser par la class Labyrinthe """class qui genere les cellule que labyrinthe utilisera""" count = 0 # donnera le numero de la cellule pour la creation du futur chemin du lanyrinthe def __init__(self, x, y, wall=False): self.__id = "{},{}".format(x, y) # id de la cellule self.__x = x # position x de la cellule self.__y = y # position y de la cellule self.wall = wall # si la cellule est un mur (True ou Flase) self.hero = False # la cellule possede t elle le hero (True ou False) self.end = False # la cellule est la fin du Labyrinthe (True ou False) if not self.wall: # seraa utiliser pour l'agorithme de generation de Labyrinthe self.numb = self.__class__.count self.__class__.count += 1 else: self.numb = -1 @property def x(self): return self.__x @property def y(self): return self.__y @property def id(self): return self.__id def cell_adj(self, xMax, yMax): """ Fonction qui renvoie un dictionnnaire composée des position des cellule adjacente a la posiotn donnée en paramètre :param xMax: valeur max de x :param yMax: valeur max de y :return envoie un dictionnaire de dictionnnaire composé des cellule adjacente """ dic = {} xMax = 2 * xMax yMax = 2 * yMax if self.y - 1 >= 0: dic["top"] = {"x": self.x, "y": self.y - 1} if self.x + 1 <= xMax: dic["right"] = {"x": self.x + 1, "y": self.y} if self.y + 1 <= yMax: dic["down"] = {"x": self.x, "y": self.y + 1} if self.x - 1 >= 0: dic["left"] = {"x": self.x - 1, "y": self.y} return dic class Labyrinthe: # creation du Labyrinthe """class qui genere tout le labyrinthe de façon aléatoire""" def __init__(self, height=3, width=3): self.__height = round(height) # hauteur du Labyrinthe self.__width = round(width) # largeur du Labyrinthe self.start = {"x": None, "y": None} # position du debut self.end = {"x": None, "y": None} # position de la fin self.laby = [] # tableau qui sera compose de tout les cellule du Labyrinthe self.wall = [] # tableau qui sera compose de tout les murs du Labyrinthe self.build_grid() # creation de tout les cellule self.build_way() # creation du chemin graace a l'algorithme self.start_and_end() # positionnement du debut e de la fin @property def height(self): return self.__height @property def width(self): return self.__width def get_cell(self, x, y): return self.laby[y][x] def build_grid(self): """ fonction qui cree toute les cellule du Labyrinthe """ line = self.height # hauteur du Labyrinthe rows = self.width # largeur du Labyrinthe for y in range(0, 2 * line + 1): self.laby.append([]) for x in range(0, 2 * rows + 1): if x % 2 == 0 or y % 2 == 0: # self.laby[y].append(Cell(x, y, True)) if (x != 0) and (y != 0) and (x != rows * 2) and ( y != line * 2): # vrai que si les cellule sont des mur interieur (pas les mur qui sont le contour du Labyrinthe) if not (x % 2 == 0 and y % 2 == 0): self.wall.append( self.laby[y][-1].id) # ajoute de id de ceullue qui sont des mur dans la variable wall else: self.laby[y].append(Cell(x, y)) # ajout de la cellule dans le varible laby def build_way(self): """fonction qui, via l'algorithme de creation de chemin, vas cree le chemin aleatoirement""" while self.val_verif(): if len(self.wall): rand = random.randrange(0, len(self.wall)) else: break coord = list(map(lambda y: int(y), self.wall[rand].split(","))) del self.wall[rand] cell = self.get_cell(coord[0], coord[1]) dic = cell.cell_adj(self.width, self.height) if not coord[0] % 2: vRigth = self.get_cell(**dic["right"]).numb vLeft = self.get_cell(**dic["left"]).numb if not (vRigth == vLeft): cell.wall = False if (vRigth > vLeft): self.new_val(vRigth, vLeft) else: self.new_val(vLeft, vRigth) if not coord[1] % 2: vDown = self.get_cell(**dic["down"]).numb vTop = self.get_cell(**dic["top"]).numb if not (vDown == vTop): cell.wall = False if (vDown > vTop): self.new_val(vDown, vTop) else: self.new_val(vTop, vDown) def new_val(self, val, nVal): """ fonction utiliser par buildWay qui permet de changer la valeur de certaine cellule lors de l execution de la fonction :param val: ancienne valeur de la cellule :param nVal: nouvelle valeur de la cellule """ for y in self.laby: for x in y: if x.numb == val: x.numb = nVal def val_verif(self): """fonction qui verifie si la valeur de 2 cellule sont les meme""" for y in self.laby: for x in y: if x.numb != 0 or x.numb != -1: return True return False def hero_move(self, lastx, lasty, newx, newy): """ fonction qui vas permettre de changer la position du hero en changeant la valeur hero dans les cellules :param lastx: ancienne position x du hero :param lasty: ancienne position y du hero :param newx: nouvelle postion x du hero :param newy: nouvelle postion y du hero """ self.get_cell(lastx, lasty).hero = False self.get_cell(newx, newy).hero = True def pop_hero(self): """fonction qui ajoute le hero dans le labyrinthe a la position voulu""" self.get_cell(**self.start).hero = True def start_and_end(self): """fonction qui vas generer le debut et la fin du labyrinthe aleatoirement""" listOfCell = [] for y in self.laby: for x in y: if not x.wall: listOfCell.append(x) # genere un nombre aleatoire entre 0 et la longeur max du tableau listOfCell rand = random.randrange(0, len(listOfCell)) celluleRandom = listOfCell[rand] # selectionne l objet dans le tableau self.set_start(celluleRandom.x, celluleRandom.y) # attribut les valeur x et y a start del celluleRandom # retire la cellule du tableau pour ne pas la reutiliser # genere un nombre aleatoire entre 0 et la longeur max du tableau listOfCell rand = random.randrange(0, len(listOfCell)) celluleRandom = listOfCell[rand] # selectionne l objet dans le tableau celluleRandom.end = True self.set_end(celluleRandom.x, celluleRandom.y) # attribut les valeur x et y a end self.pop_hero() # appel la fonction pop_hero() def set_start(self, x, y): """ cree le dictionnaire qui sera introduit dans la variable start :param x: position x du début du labyrinthe :param y: position y du début du labyrinthe """ self.start = {"x": x, "y": y} def set_end(self, x, y): """ cree le dictionnaire qui sera introduit dans la variable end :param x: position x de la fin du labyrinthe :param y: position y de la fin du labyrinthe """ self.end = {"x": x, "y": y} def show(self): """permet de montrer le labyrinthe en console""" for j in self.laby: t = [] for i in j: if i.wall: t.append("■") elif i.hero: t.append("●") elif i.end: t.append("▼") else: t.append("□") print("".join(t)) def wall_around(self, x, y): """ fonction qui return les positions des differents mur qu'il y a autour de la cellules :param x: position x de la cellule :param y: position y de la cellule :return: retourne une liste de l emplacement d'un mur par apport a une cellule """ list = [] dic = self.get_cell(x, y).cell_adj(self.width, self.height) for i in dic: if self.get_cell(**dic[i]).wall: list.append(i) return list def heroMove(self, lastx, lasty, newx, newy): """ fonction qui vas changer le hero de cellule :param lastx: ancienne position x du hero :param lasty: ancienne position y du hero :param newx: nouvelle position x du hero :param newy: nouvelle position y du hero """ self.get_cell(lastx, lasty).hero = False self.get_cell(newx, newy).hero = True if __name__ == "__main__": l = Labyrinthe(3, 6) l.show()
[ "64021617+cyrilGrandjean@users.noreply.github.com" ]
64021617+cyrilGrandjean@users.noreply.github.com
c88fedcb928281468b4a8c2347f4094580c9b61a
125d236ac7ac78d89fe555c4205b09ddb0b04d22
/file_service.py
27acb22ce0cff694919e9fc53891d8e6d9dae4c8
[ "MIT" ]
permissive
donnisu/multitext-server
d8ab912ab9088382eb6b77c02f59ec45e435a54e
38417a8ae3b8cae5674936eca19371119d40bc92
refs/heads/master
2022-11-11T00:06:14.056710
2020-07-01T16:09:50
2020-07-01T16:09:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
4,314
py
import hashlib import logging from pathlib import Path from typing import List, Tuple from docengine import Doc class FileService: """ Performs all operations with files - loads, saves, applies patches """ def __init__(self, users_dir): self.users_dir = users_dir self.patch_history = {} def register_patch(self, file_id, raw_patch) -> None: """ Register document patch in patch history of the file with specified file id :param file_id: unique id of the file :param raw_patch: encoded patch :type file_id: str :type raw_patch: str """ if file_id in self.patch_history: self.patch_history[file_id].append(raw_patch) def get_patches(self, username, filename) -> Tuple[str, List[str]] or None: """ Load all patches for file of user from history. If no patches in history, try to load from disk. If there still no file patches available, return None. :param username: user login :param filename: file name :type username: str :type filename: str :return: unique file id and file patch history """ file_id = self.get_file_id(username, filename) if file_id not in self.patch_history: file_path = self.users_dir / username / filename file_patches = self.try_load_file(file_path) if file_patches is not None: self.patch_history[file_id] = file_patches else: return None return file_id, self.patch_history[file_id] def save_file(self, username, filename) -> bool: """ Save file of user to disk. :type username: str :type filename: str :return: True if success, if no file history loaded, or failed to save on disk, return False. """ file_id = self.get_file_id(username, filename) file_path = self.users_dir / username / filename return (file_id in self.patch_history) and self.try_save_file( file_path, self.patch_history[file_id]) @staticmethod def try_save_file(path, history) -> bool: """ Try to save file of the user to the filesystem. Creates a new document, applies all the patches, then saves the resulting document's text to file. :param path: path to save :param history: patch history :type path: Path :type history: List[str] :return: True if successful, otherwise False """ file_doc = Doc() file_doc.site = 0 for patch in history: file_doc.apply_patch(patch) try: with open(path, 'w') as file: file.write(file_doc.text) return True except (OSError, IOError, FileNotFoundError): logging.info(f"Requested [{path}] was not found!") return False @staticmethod def try_load_file(path) -> List[str] or None: """ Try to load file and return it as list of encoded patches :param path: path to file :type path: Path :return: list of file patches encoded to string """ try: with open(path, 'r') as file: file_doc = Doc() file_doc.site = 0 pos = 0 result = [] for line in file: for char in line: result.append(file_doc.insert(pos, char)) pos += 1 return result except (OSError, IOError, FileNotFoundError): logging.info(f"Requested [{path}] was not found!") return None @staticmethod def get_file_id(username, filename) -> str: """ Get unique id of user's file (user should be file owner) :param username: user login :param filename: file name :type username: str :type filename: str :return: Unique id of user's file """ unique_name = username + "/#/" + filename return hashlib.sha224(unique_name.encode("utf-8")).hexdigest()
[ "usernamedt@protonmail.ch" ]
usernamedt@protonmail.ch
45e2d3551118930f0d1e222bbd9ce48b275436bc
022761172e7f6a1fc220152b123abf0dea98f6b4
/app/core/models.py
2fc5239f5599e4ba571feda22167da86a97cf0b8
[ "MIT" ]
permissive
surajk998/recipe-app-api
0beefcf2d3c8eb59822f8796d826703108ad74db
bdac67907295054cb49aff71f8ddd56a42905859
refs/heads/main
2023-06-28T20:20:15.614222
2021-07-28T15:55:26
2021-07-28T15:55:26
388,129,031
0
0
null
null
null
null
UTF-8
Python
false
false
938
py
from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError("User must have an email address") user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(self._db) return user def create_superuser(self, email, password): user = self.create_user(email, password) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email'
[ "[surajkadel1998@gmail.com]" ]
[surajkadel1998@gmail.com]
c8c81f96120216a2f3d9b77c7661a26bff53a64f
587e8f07c6dfb758e6fb5dfd50a9b4db07eb1236
/cx_Oracle/environment.py
1a4d7617f53e1072febc3a6d30a3e017d7b9b12c
[ "BSD-3-Clause", "LicenseRef-scancode-other-permissive" ]
permissive
smallfz/cx_oracle_on_ctypes
c3c192f7093f9b54b824bf4c5c17037309bbfe31
5e9f772fd48f8ee5c109e33dec5b4050c22b626a
refs/heads/master
2021-09-14T19:46:25.948504
2018-05-18T09:22:15
2018-05-18T09:22:15
null
0
0
null
null
null
null
UTF-8
Python
false
false
6,545
py
from ctypes import byref import ctypes from cx_Oracle import oci from cx_Oracle.buffer import cxBuffer from cx_Oracle.error import Error from cx_Oracle.custom_exceptions import IntegrityError, OperationalError, DatabaseError, InterfaceError from cx_Oracle.utils import MAX_STRING_CHARS, python3_or_better class Environment(object): def __init__(self, handle): self.handle = handle self.fixedWidth = self.maxBytesPerCharacter = 1 self.maxStringBytes = MAX_STRING_CHARS self.cloneEnv = None # used for connection pooling, but that is still TODO self.numberToStringFormatBuffer = cxBuffer.new_null() self.numberFromStringFormatBuffer = cxBuffer.new_null() self.nlsNumericCharactersBuffer = cxBuffer.new_null() # create the error handle error_handle_as_void_p = ctypes.c_void_p() argtypes = oci.OCIHandleAlloc.argtypes status = oci.OCIHandleAlloc(handle, byref(error_handle_as_void_p), oci.OCI_HTYPE_ERROR, 0, argtypes[4]()) self.check_for_error(status, "Environment_New(): create error handle") self.error_handle = ctypes.cast(error_handle_as_void_p, oci.POINTER(oci.OCIError)) @staticmethod def new_from_scratch(threaded, events, encoding, nencoding): mode = oci.OCI_OBJECT if threaded: mode |= oci.OCI_THREADED #TODO: if EVENTS_SUPPORTED: # if events: # mode |= ociap.OCI_EVENTS argtypes = oci.OCIEnvNlsCreate.argtypes handle = oci.POINTER(oci.OCIEnv)() status = oci.OCIEnvNlsCreate(byref(handle), mode, argtypes[2](), argtypes[3](), argtypes[4](), argtypes[5](), 0, None, 0, 0) if not handle or (status != oci.OCI_SUCCESS and status != oci.OCI_SUCCESS_WITH_INFO): raise InterfaceError("Unable to acquire Oracle environment handle") env = Environment(handle) c_maxBytesPerCharacter = oci.sb4() status = oci.OCINlsNumericInfoGet(handle, env.error_handle, byref(c_maxBytesPerCharacter), oci.OCI_NLS_CHARSET_MAXBYTESZ) env.check_for_error(status, "Environment_New(): get max bytes per character") env.maxBytesPerCharacter = c_maxBytesPerCharacter.value env.maxStringBytes = MAX_STRING_CHARS * env.maxBytesPerCharacter # acquire whether character set is fixed width c_fixedWidth = oci.sb4() status = oci.OCINlsNumericInfoGet(handle, env.error_handle, byref(c_fixedWidth), oci.OCI_NLS_CHARSET_FIXEDWIDTH) env.check_for_error(status, "Environment_New(): determine if charset fixed width") env.fixedWidth = c_fixedWidth.value # determine encodings to use for Unicode values encoding_bytes = env.get_characterset_name(oci.OCI_ATTR_ENV_CHARSET_ID, encoding) nencoding_bytes = env.get_characterset_name(oci.OCI_ATTR_ENV_NCHARSET_ID, nencoding) # cx_Oracle on ctypes only. Needed because all encoding/decoding operations require a str in Py3, not bytes if python3_or_better(): env.encoding = encoding_bytes.decode('utf-8') env.nencoding = nencoding_bytes.decode('utf-8') else: env.encoding = encoding_bytes env.nencoding = nencoding_bytes # fill buffers for number formats env.numberToStringFormatBuffer = Environment.set_buffer("TM9", env.encoding) env.numberFromStringFormatBuffer = Environment.set_buffer("999999999999999999999999999999999999999999999999999999999999999", env.encoding) env.nlsNumericCharactersBuffer = Environment.set_buffer("NLS_NUMERIC_CHARACTERS='.,'", env.encoding) return env @staticmethod def set_buffer(value, encoding): if value is None: raise # TODO: what? return cxBuffer.new_from_object(value, encoding) def check_for_error(self, status, context): if status != oci.OCI_SUCCESS and status != oci.OCI_SUCCESS_WITH_INFO: if status != oci.OCI_INVALID_HANDLE: self.raise_error(context) error = Error(self, context, 0) error.code = 0 error.message = "Invalid handle!" raise DatabaseError(error) def raise_error(self, context): error = Error(self, context, 1) if error.code in (1, 1400, 2290, 2291, 2292): raise IntegrityError(error) elif error.code in (22, 378, 602, 603, 604, 609, 1012, 1013, 1033, 1034, 1041, 1043, 1089, 1090, 1092, 3113, 3114, 3122, 3135, 12153, 12203, 12500, 12571, 27146, 28511): raise OperationalError(error) else: raise DatabaseError(error) def get_characterset_name(self, attribute, override_value): """Retrieve and store the IANA character set name for the attribute.""" # if override value specified, use it if override_value: return override_value # get character set id c_charset_id = oci.ub2() # not using pythonic OCIAttrGet on purpose here. status = oci.OCIAttrGet(self.handle, oci.OCI_HTYPE_ENV, byref(c_charset_id), None, attribute, self.error_handle) self.check_for_error(status, "Environment_GetCharacterSetName(): get charset id") # get character set name c_charset_name_array = ctypes.create_string_buffer(oci.OCI_NLS_MAXBUFSZ) c_charset_name_pointer = ctypes.cast(c_charset_name_array, oci.OCINlsCharSetIdToName.argtypes[1]) status = oci.OCINlsCharSetIdToName(self.handle, c_charset_name_pointer, oci.OCI_NLS_MAXBUFSZ, c_charset_id) self.check_for_error(status, "Environment_GetCharacterSetName(): get Oracle charset name") # get IANA character set name c_iana_charset_name_array = ctypes.create_string_buffer(oci.OCI_NLS_MAXBUFSZ) c_iana_charset_name_pointer = ctypes.cast(c_iana_charset_name_array, oci.OCINlsNameMap.argtypes[1]) status = oci.OCINlsNameMap(self.handle, c_iana_charset_name_pointer, oci.OCI_NLS_MAXBUFSZ, c_charset_name_pointer, oci.OCI_NLS_CS_ORA_TO_IANA) self.check_for_error(status, "Environment_GetCharacterSetName(): translate NLS charset") return c_iana_charset_name_array.value def __del__(self): if self.error_handle: oci.OCIHandleFree(self.error_handle, oci.OCI_HTYPE_ERROR) if self.handle and not self.cloneEnv: oci.OCIHandleFree(self.handle, oci.OCI_HTYPE_ENV) self.cloneEnv = None # break GC cycles
[ "lameiro@gmail.com" ]
lameiro@gmail.com
a1961952d05137ae84f53c5707558d0b5b88ef32
e6100c6bc7c3a02f9f707cc83e0526226bd504e4
/test/test_users_api.py
3837aa9c74f4c75f33ac3708df079adddbd2c255
[ "Apache-2.0" ]
permissive
bombbomb/bombbomb-python-openapi
dcad421abb7f93e57094e3f3cff025dd050a9912
83d71b51b7c6222d5aca5112a724198c4fb762c3
refs/heads/master
2023-06-09T01:12:19.537616
2023-06-05T22:13:42
2023-06-05T22:13:42
67,756,474
0
0
Apache-2.0
2023-06-05T22:13:43
2016-09-09T02:02:26
Python
UTF-8
Python
false
false
1,006
py
# coding: utf-8 """ BombBomb We make it easy to build relationships using simple videos. # noqa: E501 OpenAPI spec version: 2.0.831 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest import bombbomb from bombbomb.api.users_api import UsersApi # noqa: E501 from bombbomb.rest import ApiException class TestUsersApi(unittest.TestCase): """UsersApi unit test stubs""" def setUp(self): self.api = bombbomb.api.users_api.UsersApi() # noqa: E501 def tearDown(self): pass def test_get_client_contact_information(self): """Test case for get_client_contact_information Get client contact information. # noqa: E501 """ pass def test_get_user_profile_info(self): """Test case for get_user_profile_info Get user profile information. # noqa: E501 """ pass if __name__ == '__main__': unittest.main()
[ "patrick@bombbomb.com" ]
patrick@bombbomb.com
7f0f26b3058b8aa43ad3e97007363688b9f95386
5dbe03bdfe42ea197447abd0a42ce497d29d5efe
/kettle/tests/test_rollout.py
be634c293931bbd8d29bf08d9ad3c000c389ec68
[]
no_license
c-oreills/kettle
a4a8f3a0fc8cd5a1cf794ebb67d543780109e9a6
00be11111ec7788db4ae86aba8eba4a9ff47407b
refs/heads/master
2020-12-24T05:09:59.165477
2016-07-04T12:59:08
2016-07-04T12:59:08
3,593,362
5
5
null
2016-07-04T12:59:08
2012-03-01T15:54:38
Python
UTF-8
Python
false
false
5,626
py
from threading import Event from kettle.rollout import Rollout from kettle.tasks import ParallelExecTask, SequentialExecTask, Task from kettle.tests import KettleTestCase, create_task, TestTask class TestTaskFail(TestTask): @classmethod def _run(cls, state, children, abort, term): raise Exception class TestRollout(KettleTestCase): def test_init(self): rollout = Rollout({}) rollout.save() def test_generate_tasks_clears(self): class GenTasksRollout(Rollout): def _generate_tasks(self): create_task(self) rollout = GenTasksRollout({}) rollout.save() rollout.generate_tasks() self.assertEqual(len(rollout.tasks), 1) rollout.generate_tasks() self.assertEqual(len(rollout.tasks), 1) def test_generate_tasks_after_run(self): rollout = Rollout({}) rollout.save() create_task(rollout) rollout.rollout() self.assertRaises(Exception, rollout.generate_tasks) def test_single_task_rollout(self): rollout = Rollout({}) rollout.save() root = create_task(rollout) rollout.rollout() self.assertRun(root) self.assertNotReverted(root) def test_single_task_rollback(self): rollout = Rollout({}) rollout.save() root = create_task(rollout, TestTaskFail) rollout.rollout() self.assertRun(root) self.assertReverted(root) def _test_exec_rollout(self, exec_cls): rollout = Rollout({}) rollout.save() task1 = create_task(rollout) task2 = create_task(rollout) task3 = create_task(rollout) task4 = create_task(rollout) root = create_task(rollout, exec_cls, [task1, task2, task3, task4]) rollout.rollout() # Do not assert parents or root is run since otherwise we'd have to # override their call methods for task in task1, task2, task3, task4: self.assertRun(task) self.assertNotReverted(task) def _test_exec_rollout_nested(self, exec_cls): rollout = Rollout({}) rollout.save() task1 = create_task(rollout) task2 = create_task(rollout) task3 = create_task(rollout) task4 = create_task(rollout) parent1 = create_task(rollout, exec_cls, [task1, task2]) parent2 = create_task(rollout, exec_cls, [task3, task4]) root = create_task(rollout, exec_cls, [parent1, parent2]) rollout.rollout() # Do not assert parents or root is run since otherwise we'd have to # override their call methods for task in task1, task2, task3, task4: self.assertRun(task) self.assertNotReverted(task) def test_sequential_exec_rollout(self): self._test_exec_rollout(SequentialExecTask) def test_parallel_exec_rollout(self): self._test_exec_rollout(ParallelExecTask) def test_sequential_exec_rollout_nested(self): self._test_exec_rollout_nested(SequentialExecTask) def test_parallel_exec_rollout_nested(self): self._test_exec_rollout_nested(ParallelExecTask) def test_sequential_quit_and_rollback_on_failure(self): class RecordedRollout(Rollout): rollback_calls = [] def rollback(self): self.rollback_calls.append(self) super(RecordedRollout, self).rollback() rollout = RecordedRollout({}) rollout.save() task1 = create_task(rollout) task_error = create_task(rollout, TestTaskFail) task2 = create_task(rollout) root = create_task(rollout, SequentialExecTask, [task1, task_error, task2]) rollout.rollout() self.assertRun(task1) self.assertRun(task_error) self.assertNotRun(task2) self.assertEqual(RecordedRollout.rollback_calls, [rollout]) self.assertReverted(task_error) self.assertReverted(task1) self.assertNotReverted(task2) def test_monitor_rolls_back(self): monitor_wake_event = Event() finish_step_event = Event() def monitor(monitor_event, abort_event): monitor_wake_event.wait() abort_event.set() finish_step_event.set() class MonitoredRollout(Rollout): monitors = { 'mon': monitor, } rollback_calls = [] def rollback(self): self.rollback_calls.append(self) super(MonitoredRollout, self).rollback() rollout = MonitoredRollout({'monitors': ['mon']}) rollout.save() def wake_monitor_then_wait(): monitor_wake_event.set() finish_step_event.wait() self.assertFalse(MonitoredRollout.rollback_calls) class WakeMonitorWaitTask(TestTask): @classmethod def _run(cls, state, children, abort, term): wake_monitor_then_wait() task_run = create_task(rollout) task_wake_monitor_wait = create_task(rollout, WakeMonitorWaitTask) task_not_called = create_task(rollout) root = create_task(rollout, SequentialExecTask, [task_run, task_wake_monitor_wait, task_not_called]) rollout.rollout() self.assertRun(task_run) self.assertRun(task_wake_monitor_wait) self.assertNotRun(task_not_called) self.assertEqual(MonitoredRollout.rollback_calls, [rollout]) self.assertReverted(task_run) self.assertReverted(task_wake_monitor_wait)
[ "christy@oreills.co.uk" ]
christy@oreills.co.uk
aa7968e19e64f3da03490a1bd8b36ae04f204359
94c4be2c29c2799b6b764885bb918f66a0639e6a
/Project 8/MWS_corrected.py
ae92769042821d33889ec9d892d1577538ec46d9
[]
no_license
sbkumar1/x9115SHA
dfde32f309d237301af40c042351ac4c90c9a375
cc749d5d731d9c708f6878048910f7e666b14aef
refs/heads/master
2021-01-10T19:53:43.983073
2015-12-16T01:41:03
2015-12-16T01:41:03
41,257,905
0
1
null
null
null
null
UTF-8
Python
false
false
5,573
py
#!/usr/bin/python -b from __future__ import division import sys import random,math import copy import sk random.seed(100) MWS_MIN=MWS_MAX=0 def randomlist(): randList=[] randList.append(random.uniform(0,10)) randList.append(random.uniform(0,10)) randList.append(random.uniform(1,5)) randList.append(random.uniform(0,6)) randList.append(random.uniform(1,5)) randList.append(random.uniform(0,10)) return randList def check_constraint(randList): if (((randList[0]+randList[1]-2)>=0) and ((6-randList[0]-randList[1])>=0) and ((2-randList[1]+randList[0])>=0) and ((2-randList[0]+(3*randList[1]))>=0) and ((4-((randList[2]-3)**2)-randList[3])>=0) and (((randList[4]-3)**3)+randList[5]-4)>=0): return True else: return False """ def normalized(y): base_rand=y normalized_rand=(base_rand-MINIMUM)/(MAXIMUM-MINIMUM) return normalized_rand """ def newPerson(object1,model,i): newList=model() newList=copy.deepcopy(object1) while True: newList.decisionList[i]=random.uniform(newList.minRange[i],newList.maxRange[i]) if newList.ok(): return newList break def corrected_list(): correct_list=randomlist() while (check_constraint(correct_list)!=True): #print correct_list correct_list=randomlist() #print "correct" return correct_list def objective_function(list2): f1=(((-1)*(25*((list2[0]-2)**2)))+((list2[1]-2)**2)+(((list2[2]-1)**2)*((list2[3]-4)**2))+((list2[4]-1)**2)) f2=((list2[0]**2)+(list2[1]**2)+(list2[2]**2)+(list2[3]**2)+(list2[4]**2)+(list2[5]**2)) #print "obj" return (f1+f2) def energy(list2): global MWS_MIN global MWS_MAX list2=corrected_list() energy1=objective_function(list2) #energy1= a+b return ((energy1-MWS_MIN)/(MWS_MAX-MWS_MIN)) def baseline(): global MWS_MAX global MWS_MIN #MWS_MAX=objective_function(list1) #MWS_MIN=objective_function(list1) #print MWS_MAX,MWS_MIN for index in xrange(1000): list1=corrected_list() x=objective_function(list1) #x =energy(list1) if (x < MWS_MIN): MWS_MIN = x if ( x> MWS_MAX): MWS_MAX = x return (MWS_MIN,MWS_MAX) def mutate(mutation_list,index): top=[0,0,1,0,1,0] bottom=[10,10,5,6,5,10] while (1): mutation_list[index]=random.uniform(top[index],bottom[index]) if (check_constraint(mutation_list)==True): return mutation_list def max_score(mutation_list,index): top=[0,0,1,0,1,0] bottom=[10,10,5,6,5,10] max_solution=list(mutation_list) min1=top[index] max1=bottom[index] steps=(max1-min1)/10.0 start=min1/10.0 end=max1/10.0 while min1<=end: treat=list(mutation_list) #print "treat" treat[index]=min1 if check_constraint(treat): if (objective_function(max_solution)<objective_function(treat)): best=list(treat) min1=min1+steps return max_solution def normalized(y,MINIMUM,MAXIMUM): base_rand=y normalized_rand=(base_rand-MINIMUM)/(MAXIMUM-MINIMUM) return normalized_rand def gt(model1,modet2): if (model1>model2): return True else: return False def lt(model1,model2): if model1<model2: return True else: return False def type1(model1,model2): k=1 for i,(j,k) in enumerate(zip(model1.objectiveScore(),model2.objectiveScore())): if lt(j,k): k=0 else: return False return True def type2(model1,model2): if (sk.a12(model1,model2) <= 0.6): return -1 else: return 5 def MaxWalkSat(mws1): trials=1000 changes=10 p=0.5 threshold=-10000 step=10 lives=5 lp=1 era=25 eval1=0 evalx=0 best=mws1() MWS_MIN,MWS_MAX=baseline() bestEnergy=normalized(best.eval(),MWS_MIN,MWS_MAX) Past,Current,Future=[],[],[] for i in range(trials): new_list=mws1() if (i==0): sBest=mws1() sBest=copy.deepcopy(new_list) for i in range(len(new_list.objectiveScore())): Current.append([]) Past.append([]) for j in range(changes): lp=1 if ((normalized(new_list.eval(),MWS_MIN,MWS_MAX))>threshold and len(Past)==era): return sBest.decisionList,sBest.eval() #if (normalized(new_list.eval()MWS_MIN<MWS_MAX)>normalized(best.eval()MWS_MIN<MWS_MAX)): # #print "if2" # best=list(new_list) # formatList.append('!') if (p<random.uniform(0,1)): #print "if3" #formatList.append('?') new_list=newPerson(new_list,mws1,random.randint(0,len(new_list.decisionList)-1)) #print "random" else: new_list=newPerson(new_list,mws1,random.randint(0,len(new_list.decisionList)-1)) #print "else" if (type1(new_list,sBest)): sBest=copy.deepcopy(new_list) evalx=eval1 if (len(Current[0])<era): x=list(new_list.objectiveScore()) for i in range(len(x)): Current[i].append(x[i]) else: if (Past[0]!=[]): for j in range(len(Past)): lives=lives+type2(Past[j],Current[j]) if (lives<=0): break for i in range(len(Current)): Past[i]=list(Current[i]) Current=[] for i in range(len(Past)): Current.append([]) return sBest.decisionList,sBest.eval()
[ "sbkumar@ncsu.edu" ]
sbkumar@ncsu.edu
56543401f8fff6de82cf72f6710a4d11cd322f0f
265a07a2becd232b292872d1d7136789463874be
/lei练习/child.py
a18eb14e18c20325173e5d20365a90e17db5663c
[]
no_license
Lz0224/Python-exercise
f4918b8cd5f7911f0c35c0458c2269959937d07d
3d09f54aebc653f4a5b36765b25c7241e3960764
refs/heads/master
2020-12-24T22:20:55.573019
2017-08-11T07:18:16
2017-08-11T07:18:16
100,005,776
1
1
null
null
null
null
UTF-8
Python
false
false
686
py
#!/usr/bin/python #coding=utf-8 class ParentClass(object): """docstring for ParentClass.""" name = "老张" # def __init__(self, arg): # super(ParentClass, self).__init__() # self.arg = arg def fun(self): print "老子有钱" class ChildClass(ParentClass): """这是什么玩意。。。。""" # def __init__(self, arg): # super(, self).__init__() # self.arg = arg def fun1(self): print "哥也有钱" class GrentChildClass(ChildClass): pass child = ChildClass() print child.name child.fun() grent_child = GrentChildClass() print grent_child.name print dir(ParentClass) print ChildClass.__doc__
[ "Lz0o_o0@outlook.com" ]
Lz0o_o0@outlook.com
0018d3f20bbe862f6a808be039294d11e214adbe
113be8952d81eb446095287572970be7e755cecf
/data_tools/coco_tools.py
bbb75f24809e5221a9f1a53c8dc86bf587619b0c
[ "MIT" ]
permissive
isabella232/retinanet_for_redaction_with_deepstream
ea6361839c076768ba624264aec94a1e540671b6
dbe39d0739ebb57e781201f26372a6aa96be39db
refs/heads/master
2023-03-18T14:22:26.954161
2020-02-24T22:45:39
2020-02-24T22:45:39
null
0
0
null
null
null
null
UTF-8
Python
false
false
9,630
py
""" Tools for manipulating coco annotaitons """ import os import json from PIL import Image import random import shutil def resize(img_folder, annotations, resize_factor, output_img_folder, output_annotations): """ Resize images to (original size * resize_factor) :param img_folder: Folder containing original images :param annotations: File containing COCO style annotations :param resize_factor: factor to increase each dim size by. 0.25 = shrink by 4 x :param output_img_folder: Folder that will contain the new images :param output_annotations: File that will contain the new annotations. :return: """ # Check all files and directories exist assert os.path.isdir(img_folder), "Directory %s does not exist" % img_folder assert os.path.isdir(output_img_folder), "Directory %s does not exist" % output_img_folder assert os.path.isdir(os.path.split(output_annotations)[0]), "Directory %s does not exist" % os.path.split(output_annotations)[0] assert os.path.isfile(annotations), "File %s does not exist" % annotations # Read in annotations print("Reading annotaitons from", annotations) with open(annotations) as f: anns = json.load(f) if not anns: raise IOError("The annotation file is empty.") new_images = [] old_images = anns['images'] # Work through each image in annotations, resizing height & width attributes and resizing and copying image. for img in old_images: old_filepath = os.path.join(img_folder, img['file_name']) new_filepath = os.path.join(output_img_folder, img['file_name']) new_w = int(resize_factor * img['width']) new_h = int(resize_factor * img['height']) img['width'] = new_w img['height'] = new_h new_images.append(img) # Now resize try: image = Image.open(old_filepath).convert("RGB") except FileNotFoundError: print("Image not found:", old_filepath) continue except OSError: print("Image damaged:", old_filepath) continue new_image = image.resize((new_w, new_h), Image.BILINEAR) new_image.save(new_filepath, quality=95) # print("DEBUG: Image size requested:", new_w, new_h) # print("DEBUG: new_image.size", new_image.size) # print("DEBUG: new_image location", new_filepath) # # raise NotImplementedError("TEST RESIZE)") anns['images'] = new_images # Work through annotations, resizing xmin, ymin, w, h. old_anns = anns['annotations'] new_anns = [] for ann in old_anns: [xmin, ymin, w, h] = ann['bbox'] xmin = int(xmin * resize_factor) ymin = int(ymin * resize_factor) w = int(w * resize_factor) h = int(h * resize_factor) xmax = xmin + w ymax = ymin + h ann['bbox'] = [xmin, ymin, w, h] ann['area'] = w * h ann['seg'] = [xmin, ymin, xmin, ymax, xmax, ymax, xmax, ymin] new_anns.append(ann) anns['annotations'] = new_anns # Save out new annotations. print("All images resized and copied.") with open(output_annotations, 'w') as outfile: json.dump(anns, outfile) def split_dataset(input_annotations, frac_split_a, a_output_path, b_output_path): """ Split the dataset into two fractions, a and b. :param input_annotations: :param frac_split_a: 0.8 = 80% of data goes to a, 20% to b :param a_output_path: :param b_output_path: :return: """ # Check all files and directories exist assert os.path.isdir(os.path.split(a_output_path)[0]), "Directory %s does not exist" % os.path.split(a_output_path)[0] assert os.path.isdir(os.path.split(b_output_path)[0]), "Directory %s does not exist" % os.path.split(b_output_path)[0] assert os.path.isfile(input_annotations), "File %s does not exist" % input_annotations assert 0 < frac_split_a < 1, "frac_split must be between 0 and 1" # Read in annotations print("Reading annotaitons from", input_annotations) with open(input_annotations) as f: input_anns = json.load(f) if not input_anns: raise IOError("The annotation file is empty.") # Loop through images, assigning each to either 'a' or 'b'. image_split_dict = {} for im in input_anns['images']: if random.random() < frac_split_a: image_split_dict[im['id']] = 'a' else: image_split_dict[im['id']] = 'b' # Now create two outputs and assign image and annotations to each. output_a = {'info': input_anns['info'] + ' Split ' + str(frac_split_a), 'licenses': input_anns['licenses'], 'images': [], 'annotations': [], 'categories': input_anns['categories']} # Prepare output output_b = {'info': input_anns['info'] + ' Split ' + str(1 - frac_split_a), 'licenses': input_anns['licenses'], 'images': [], 'annotations': [], 'categories': input_anns['categories']} # Prepare output output_a_raw_images = [] output_b_raw_images = [] for im in input_anns['images']: if image_split_dict[im['id']] == 'a': output_a_raw_images.append(im) elif image_split_dict[im['id']] == 'b': output_b_raw_images.append(im) else: raise SyntaxError('im not assigned to a nor b.', im) output_a_raw_anns = [] output_b_raw_anns = [] for ann in input_anns['annotations']: if image_split_dict[ann['image_id']] == 'a': output_a_raw_anns.append(ann) elif image_split_dict[ann['image_id']] == 'b': output_b_raw_anns.append(ann) else: raise SyntaxError('ann not assigned to a nor b.', ann) # Now renumber the annotations and images in each output_a_images = [] a_oldimgid2newimgid = {} # to use to convert annotations for indx, aa in enumerate(output_a_raw_images): a_oldimgid2newimgid[aa['id']] = indx aa['id'] = indx output_a_images.append(aa) output_b_images = [] b_oldimgid2newimgid = {} # to use to convert annotations for indx, bb in enumerate(output_b_raw_images): b_oldimgid2newimgid[bb['id']] = indx bb['id'] = indx output_b_images.append(bb) output_a_annotations = [] for indx, aa in enumerate(output_a_raw_anns): new_image_id = a_oldimgid2newimgid[aa['image_id']] aa['image_id'] = new_image_id aa['id'] = indx output_a_annotations.append(aa) output_b_annotations = [] for indx, bb in enumerate(output_b_raw_anns): new_image_id = b_oldimgid2newimgid[bb['image_id']] bb['image_id'] = new_image_id bb['id'] = indx output_b_annotations.append(bb) output_a['images'] = output_a_images output_a['annotations'] = output_a_annotations output_b['images'] = output_b_images output_b['annotations'] = output_b_annotations # Write some info print("Split A contains %i images and %i annotations." % (len(output_a['images']), len(output_a['annotations']))) print("Split B contains %i images and %i annotations." % (len(output_b['images']), len(output_b['annotations']))) # Write each out with open(a_output_path, 'w') as outfile: json.dump(output_a, outfile) with open(b_output_path, 'w') as outfile: json.dump(output_b, outfile) def copy_images(all_img_dir, new_img_dir, ann_file): """ Copy all images mentioned in ann_file from all_img_dir to new_img_dir """ assert os.path.isdir(all_img_dir), "Directory %s does not exist" % all_img_dir assert os.path.isdir(new_img_dir), "Directory %s does not exist" % new_img_dir assert os.path.isfile(ann_file), "File %s does not exist" % ann_file print("Reading annotaitons from", ann_file) with open(ann_file) as f: input_anns = json.load(f) if not input_anns: raise IOError("The annotation file is empty.") # Get list of images img_list = [im['file_name'] for im in input_anns['images']] # Work through list for im in img_list: old_path = os.path.join(all_img_dir, im) new_path = os.path.join(new_img_dir, im) shutil.copy(old_path, new_path) def read_json(coco_annotation, verbose=False): if verbose: print("Reading annotaitons from", coco_annotation) with open(coco_annotation) as f: anns = json.load(f) if not anns: raise IOError("The annotation file is empty.") return anns def write_json(data, filepath): """Write JSON file""" dir_ = os.path.split(filepath)[0] assert os.path.isdir(dir_), "Directory %s does not exist" % dir_ with open(filepath, 'w') as outfile: json.dump(data, outfile) def get_filename2imgid(annfile, verbose=False): anns = read_json(annfile, verbose=verbose) filename2imgid = {} for img in anns['images']: filename2imgid[img['file_name']] = img['id'] return filename2imgid def get_imgid2anns(annfile, verbose=False): anns = read_json(annfile, verbose=verbose) imgid2anns = {} for ann in anns['annotations']: imgid = ann['image_id'] if imgid not in imgid2anns: imgid2anns[imgid] = [] imgid2anns[imgid].append(ann) return imgid2anns def get_imgid2img(annfile, verbose=False): anns = read_json(annfile, verbose=verbose) imgid2img = {} for img in anns['images']: imgid2img[img['id']] = img return imgid2img
[ "jskinner@nvidia.com" ]
jskinner@nvidia.com
0ad5e4e350a40761eeb725392b057018a318a896
fc624d36245b1695a15941d4aeb24b4f4e762ab5
/77.py
d1c8c06c1af960eea8c142c30ab474eff0fe2125
[]
no_license
Talha2000/PythonExercises
efbcb760d6da71dc5c60452ac5a190f5588e9640
4f76a88acee79095ed41205a997eb539f80bf97f
refs/heads/main
2023-01-08T09:29:59.924226
2020-10-30T22:48:43
2020-10-30T22:48:43
308,697,175
0
0
null
null
null
null
UTF-8
Python
false
false
113
py
import time a = time.time() for i in range(0, 100001): x = 1+1 b = time.time() result = b - a print(result)
[ "amjad_maqsood90@hotmail.com" ]
amjad_maqsood90@hotmail.com
374a204faa07f80ad6187a04e03dc1f385ef9168
7619aed8a311e2832634379762c373886f4354fb
/trace_pox_eel_l2_multi-BinaryLeafTreeTopology1-steps200/interactive_replay_config.py
642e4a4db5b05f5ecefc4f4ffd682ee68f5bc5b3
[]
no_license
jmiserez/sdnracer-traces
b60f8588277c4dc2dad9fe270c05418c47d229b3
8991eee19103c8ebffd6ffe15d88dd8c25e1aad5
refs/heads/master
2021-01-21T18:21:32.040221
2015-12-15T14:34:46
2015-12-15T14:34:46
39,391,225
2
1
null
null
null
null
UTF-8
Python
false
false
1,097
py
from config.experiment_config_lib import ControllerConfig from sts.topology import * from sts.control_flow.interactive_replayer import InteractiveReplayer from sts.simulation_state import SimulationConfig from sts.input_traces.input_logger import InputLogger simulation_config = SimulationConfig(controller_configs=[ControllerConfig(start_cmd=' ./pox.py --verbose openflow.of_01 --address=__address__ --port=__port__ openflow.discovery forwarding.l2_multi_orig', label='c1', address='127.0.0.1', cwd='/home/ahassany/repos/pox/')], topology_class=BinaryLeafTreeTopology, topology_params="num_levels=1", patch_panel_class=BufferedPatchPanel, multiplex_sockets=False, ignore_interposition=False, kill_controllers_on_exit=True) control_flow = InteractiveReplayer(simulation_config, "traces/trace_pox_eel_l2_multi-BinaryLeafTreeTopology1-steps200/events.trace") # wait_on_deterministic_values=False # delay_flow_mods=False # Invariant check: 'InvariantChecker.check_liveness' # Bug signature: ""
[ "eahmed@ethz.ch" ]
eahmed@ethz.ch
28af2f205ead785ee570ffa916f56f4b6b753c5c
e10f0b4f081e182e8fb1e5ed55a30241b42c8608
/src/Blog/urls.py
9db32a2786436d752b4047f7ff03f6ee8b923820
[]
no_license
nald0422/django-blog
ba6e28e711bb042109d909530c6e20b3826a0765
5cb1e6ba52c5a98812d9e4d66841137d30443f0b
refs/heads/master
2023-03-01T11:13:38.055277
2021-02-08T11:17:38
2021-02-08T11:17:38
336,566,020
0
0
null
null
null
null
UTF-8
Python
false
false
633
py
from django.urls import path, include from . import views from rest_framework import routers # urlpatterns = [ # path('', views.blogApiOverview, name="blog-overview"), # path('list/', views.blogList, name="blog-list"), # path('detail/<str:pk>/', views.blogDetail, name="blog-detail"), # path('create/', views.blogCreate, name="blog-create"), # path('update/<str:pk>/', views.blogUpdate, name="blog-update"), # path('delete/<str:pk>/', views.blogDelete, name="blog-delete"), # ] router = routers.DefaultRouter() router.register('blogs', views.BlogView) urlpatterns = [ path('', include(router.urls)), ]
[ "nald04.db@gmail.com" ]
nald04.db@gmail.com
180ad8b089bf6257e39e3edfab64474f209d9f06
b39f7a85a98fe356c9f4677bafe1ec07480bfae1
/ChessAI_alphabeta.py
ecf403a6c6a8b42fdc0675d4fafac8fa2834217a
[]
no_license
TheMagicalPlace/DepthSearchStuff
8aeed613df45582cdb6445587700446d34949147
501edb24de7cc1bb9d9be6a917c195e343f1cb59
refs/heads/master
2020-06-26T06:21:32.208129
2019-11-23T03:03:26
2019-11-23T03:03:26
199,558,461
0
0
null
null
null
null
UTF-8
Python
false
false
5,952
py
import copy from collections import defaultdict from ChessBoard import Chessgame from Player_Base import * from ChessPieces import * from multiprocessing import Queue,Pool from queue import Queue class vars: player = 'White' depth = 3 def child_process(node,player=vars.player): abspawn = AlphaBeta(player) return abspawn.call_multiprocess(node,maxing=False) class ChessNode(Chessgame): def __init__(self,depth,board,value=None,parent=None): self.parent = parent self.depth = depth self.value = value self.board = board self.index = 0 self.children = None #self.get_current_state(board) def __ge__(self, other): return self.value >= other def __le__(self, other): return self.value <= other def __lt__(self, other): return self.value < other def __gt__(self, other): return self.value > other def __call__(self): return self.board def __iter__(self): return next(self) def items(self): return self.board.items() def __getitem__(self, key): return self.board[key] def __setitem__(self, key, value): self.board[key] = value def __next__(self): subs = (value for _, value in self.board.items()) while True: try: yield next(subs) except StopIteration: break class AlphaBeta(ChessTurnABC,Chessgame): type = 'alpha-beta' opponent = {'Black': 'White', 'White': 'Black'} def __init__(self,player): super(ChessTurnABC).__init__() self.player = player def call_multiprocess(self,node,maxing): depth = node.depth - 1 self.root_node = node self.alphabeta(self.root_node, depth, maxing, -100000, 100000) optimal_node = max([child for child in self.root_node.children if child.value is not None]) return optimal_node.parent def __call__(self,root,depth=3,maxing=True): self.root_node = ChessNode(depth,root) self.alphabeta(self.root_node,depth,maxing,-100000,100000) self._current_state_raw = max([child for child in self.root_node.children if child.value is not None]).board return self._current_state_raw def child_node_finder(self, node, depth,is_maxing): self.current_working_node = node child_nodes = [] moves = defaultdict(list) if is_maxing: current_player = self.player else: current_player=self.opponent[self.player] for piece in self.current_working_node: piece.getpos(self.current_working_node) if piece.owner == current_player: piece.move_range(self.current_working_node) [moves[piece].append(x) for x in [*piece.avalible_moves.keys()]] for piece, moves in moves.items(): self.current_piece = piece for move in moves: workingboard = copy.copy(self.current_working_node.board) workingboard[piece.position],workingboard[move] = Dummy(),piece child_nodes.append(ChessNode(depth,workingboard,parent=node)) return tuple(child_nodes) def node_evaluation_heuristic(self, node): value = 0 for piece in node: if piece.owner == self.player: value += piece.value if piece.move_range(node) != []: value += len([*piece.avalible_moves.keys()])*0.1 if piece.owner == self.opponent[self.player]: value -= piece.value if piece.move_range(node) != []: value -= len([*piece.avalible_moves.keys()])*0.1 return value def alphabeta(self, node, depth, maxing_player, alpha, beta): if depth == 0: value = self.node_evaluation_heuristic(node) node.value = value return value if maxing_player: value = -100000 subnodes = self.child_node_finder(node,depth,maxing_player) node.children = subnodes for nodes in subnodes: val = self.alphabeta(nodes, depth - 1, False, alpha, beta) try: value = max(value,val) except TypeError: value = max(value, val[0]) alpha = max(alpha, value) node.value = value if alpha >= beta: break else: continue return value else: value = 100000 subnodes = self.child_node_finder(node, depth,maxing_player) node.children = subnodes for nodes in subnodes: val = self.alphabeta(nodes, depth - 1, True, alpha, beta) value = min(value, val) beta = min(beta, value) node.value = value if alpha >= beta: break else: continue return value class MultiprocessAB(AlphaBeta): def __init__(self, player, root,depth=4): super().__init__(player) self.root_node = ChessNode(depth,root) self.mp_childs = self.child_node_finder(self.root_node,depth-1,True) self.root_node.children = tuple(self.mp_childs) def __call__(self): with Pool(5) as p: data = p.map(child_process, self.mp_childs) self._current_state_raw=max(data) if __name__ == '__main__': import time t = Chessgame() initial = time.time() for i in range(5,6): t0 = time.time() a = MultiprocessAB('Black',t._current_state_raw,depth=i) yepis = a() yepis.get_current_state(yepis.board) elapsed = time.time() - t0 total = time.time()-initial print(f'depth: {i} run-time: {elapsed} total time : {total}')
[ "chris621@msu.edu" ]
chris621@msu.edu
ad222390e157befaf7c30cf95ec6cca7957e8664
6ebcb208eefc536f02378e186dc14a9dc3ee3c20
/1779.py
1fa2c68f1a89617291883c0c7503ac9bfe8876c4
[ "MIT" ]
permissive
sinasiruosnejad/leetcode
e9bb599ebf0c5837067e454c3d03241c1156de20
8fe5a400bc03a5e129835e380ff9fe72af681d8a
refs/heads/main
2023-08-01T18:05:16.872554
2021-09-15T17:43:44
2021-09-15T17:43:44
340,697,379
0
0
null
null
null
null
UTF-8
Python
false
false
1,798
py
import math def string_to_list(value): x=value result=[] i=1 while x[i]!=']': if x[i]!=',': j=i temp='' while x[j]!=',': if x[j]==']': break temp+=x[j] j+=1 i=j result.append(int(temp)) else: i+=1 return result tt=input('please enter the x and y value: ') xy=string_to_list(tt) t=input('please enter the list of points: ') temp='' other_temp=[] for i in range(1,len(t)-1): if t[i]==',' and t[i+1]=='[': temp='' elif t[i]!=']': temp+=t[i] else: temp+=t[i] other_temp.append(temp) temp='' points=[] for i in range(len(other_temp)): temp=string_to_list(other_temp[i]) points.append(temp) qualified=[] distance=[] qualify=[] finall_qualification=[] for i in range(len(points)): if xy[0]==points[i][0] or xy[1]==points[i][1]: qualified.append([points[i],i]) for i in range(len(qualified)): temp=math.sqrt(((xy[0]-qualified[i][0][0])**2)+((xy[1]-qualified[i][0][1])**2)) distance.append(temp) for i in range(len(distance)): if i==0: temp=distance[i] temp_i=i qualify.append(temp_i) elif temp>distance[i]: temp=distance[i] temp_i=i qualify.append(temp_i) qualify.pop(0) elif temp==distance[i]: qualify.append(i) for i in range(len(qualified)): for j in range(len(qualify)): if qualify[j]==i: finall_qualification.append(qualified[i][1]) result=-1 for i in range(len(finall_qualification)): if i==0: result=finall_qualification[i] elif result>finall_qualification[i]: result=finall_qualification[i] print(result)
[ "sina.sirousnejad@gmail.com" ]
sina.sirousnejad@gmail.com
f3ccca6b0866a92e2954ff24bc5f435351cdfb75
62d5cd801e7e5c94f091accd7e7ac4410c16deb4
/mysite/urls.py
4819731e9a98f90646a88322f1bedde4b9ec0afe
[]
no_license
hirootokushima/my-first-blog
0d814538ee70a4f30716b0e1c15c7b2a4060d2aa
46e289d905d136c04344b2f6f83cff032398ba90
refs/heads/master
2020-04-03T01:32:09.348893
2018-11-05T08:51:06
2018-11-05T08:51:06
154,933,666
0
0
null
null
null
null
UTF-8
Python
false
false
827
py
"""mysite URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path, include from django.contrib import admin urlpatterns = [ path('admin/', admin.site.urls), path('', include('blog.urls')), ]
[ "manadoresu@gmail.com" ]
manadoresu@gmail.com
062d5e995b67d4166739a0c02d72ade641723dc3
e953398d1205d11b3ced77589bc208af5b780d0e
/menu.py
da46ced901911c8da867897fc97a2c65a27cd290
[]
no_license
PacosLelouch/pygame2048
077b2c9b35afea4cc585d88399603c9d00510dc1
831cb9859e45fb62a9998949c0f105512cd7f439
refs/heads/master
2020-05-24T08:57:04.757203
2019-05-17T10:20:35
2019-05-17T10:20:35
187,194,579
0
1
null
null
null
null
UTF-8
Python
false
false
2,397
py
from ui_menu import Ui_MainWindow from scoreboard import Scoreboard from game import Game from PyQt5 import QtCore, QtWidgets, QtGui from PyQt5.QtWidgets import * class Menu(QMainWindow): def __init__(self): super().__init__() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.dialog = None self.game = None self.ui.scoreboard.triggered.connect(self.scoreBoard) #self.ui.help.triggered.connect(self.help) self.ui.pushButton.pressed.connect(self.buttonPress) self.ui.pushButton.released.connect(self.buttonRelease) self.ui.pushButton.clicked.connect(self.start) def scoreBoard(self): try: if self.dialog: self.dialog.close() #下一行测试用的 #self.dialog = Scoreboard(use_zip=True, write=True, name0='江沢', score0=817) self.dialog = Scoreboard(use_zip=True, size_str=self.ui.comboBox.currentText()) self.dialog.show() except Exception as e: print("Scoreboard error.") print(str(e)) def help(self): print("还有什么功能需要加?")#TODO try: pass except Exception as e: print(str(e)) def start(self): if self.ui.lineEdit.text() == '': return try: if self.game: del(self.game) print(self.ui.comboBox.currentText()) self.game = Game(self.ui.lineEdit.text().replace(' ', '_'), 400, 600, int(self.ui.comboBox.currentText())) self.game.run() except Exception as e: print("Game error.") print(str(e)) def buttonPress(self): self.ui.pushButton.setStyleSheet("QPushButton{border-radius: 5px;border-bottom: 0px solid;border-top: 1px solid;border-top-color: rgb(75, 175, 125);background-color: qlineargradient(spread:pad, x1:0.5, y1:1, x2:0.5, y2:0, stop:0.0845771 rgba(13, 204, 88, 255), stop:0.60199 rgba(153, 224, 198, 200));}") def buttonRelease(self): self.ui.pushButton.setStyleSheet("QPushButton{border-radius: 5px;border-bottom: 1px solid;border-top: 0px solid;border-bottom-color: rgb(75, 175, 125);background-color: qlineargradient(spread:pad, x1:0.5, y1:1, x2:0.5, y2:0, stop:0.0845771 rgba(32, 228, 128, 255), stop:0.60199 rgba(195, 251, 229, 200));}")
[ "276613158@qq.com" ]
276613158@qq.com
912555da0fdc5347a5e1f9803c5d152c6523fb9e
06443415baafed408d493610ae07987b5c681cb5
/SW Expert Academy/D3/4466. 최대 성적표 만들기.py
5cc7c22ca1cc856cdd44e48bd5074631b5a051a1
[]
no_license
rheehot/Algorithm-33
251aa2ea9b15ef6bde53443b7ff26e599f7a6bdd
7878713ab716b5365a8f71a1c8b2e370f9ee5039
refs/heads/master
2023-01-24T02:56:18.411717
2020-11-29T12:31:51
2020-11-29T12:31:51
null
0
0
null
null
null
null
UTF-8
Python
false
false
279
py
import sys sys.stdin = open('4466. 최대 성적표 만들기.txt','r') T = int(input()) for tc in range(T): N, K = map(int,input().split()) scores = list(map(int,input().split())) scores.sort() result = sum(scores[-K:]) print('#{} {}'.format(tc+1,result))
[ "djagmlrhks3@naver.com" ]
djagmlrhks3@naver.com
87a59bc42433821ff6c353a9e24ee2417a5de00f
a6fae33cdf3d3cb0b0d458c2825a8d8cc010cd25
/l3/z3/.history/population_20200522014505.py
3e8108e382a859c114f46c50cbcf52c462b42894
[]
no_license
Qabrix/optimization_amh
12aab7c7980b38812ec38b7e494e82452a4176b4
6a4f5b897a4bef25f6e2acf535ba20ace7351689
refs/heads/main
2022-12-28T10:57:00.064130
2020-10-17T22:57:27
2020-10-17T22:57:27
304,983,340
0
0
null
null
null
null
UTF-8
Python
false
false
6,540
py
import random import numpy as np from utils import calculate_value, decision class Inhabitant: def __init__(self, gene, value=0): self.gene = gene self.value = 0 def __iter__(self): for char in self.gene: yield char def __len__(self): return len(self.gene) def __getitem__(self, item): return self.gene[item] def get_str_gene(self, up): return "".join(self.gene[:up]) class Population: def __init__(self, population_size, all_puzzle_keys, starter_words): self.all_puzzle_keys = all_puzzle_keys self.best_res = None self.population_size = population_size self.generation = self._gen_generation(starter_words) def __iter__(self): for inhabitant in self.generation: yield inhabitant def _random_word(self): return random.sample(self.all_puzzle_keys, len(self.all_puzzle_keys)) def _gen_generation(self, starter_words): min_size = min([len(word) for word in starter_words]) max_size = max([len(word) for word in starter_words]) generation = [] for word in starter_words: generation.append(Inhabitant(list(word))) for _ in range(len(starter_words), self.population_size): word = self._random_word()[: random.randint(min_size, max_size)] generation.append(Inhabitant(word)) return generation def sorted_generation(self): return sorted(self.generation, key=lambda x: x.value, reverse=True) def make_selection(self, elite_percentage, percentage=0.75): selection = [] sorted_generation = self.sorted_generation() selection_size = int(self.population_size * percentage) elite_size = int(elite_percentage * selection_size) for inhabitant in sorted_generation[:elite_size]: selection.append(inhabitant) if elite_size - selection_size < 0: for inhabitant in sorted_generation[elite_size - selection_size :]: selection.append(inhabitant) return selection def _check_if_correct(self, word): possible_chars = self.all_puzzle_keys.copy() for char in word: if char in possible_chars: possible_chars.remove(char) else: return False return True def recombinate(self, elite_percentage=0.6): selection = self.make_selection(elite_percentage) permutation = np.random.permutation(len(selection)) new_generation = [] new_generation.append(Inhabitant(selection[0].gene.copy())) new_generation.append(Inhabitant(selection[1].gene.copy())) for i in range(1, len(permutation)): pivot = random.randint( 0, min( len(selection[permutation[i % len(permutation)]]), len(selection[permutation[(i + 1) % len(permutation)]]), ) // 2, ) new_word = ( selection[permutation[i % len(permutation)]][:pivot] + selection[permutation[(i + 1) % len(permutation)]][pivot:] ) if self._check_if_correct(new_word): new_generation.append(Inhabitant(new_word)) else: new_generation.append( Inhabitant(selection[permutation[i % len(permutation)]].gene) ) new_word = ( selection[permutation[(i + 1) % len(permutation)]][:pivot] + selection[permutation[i % len(permutation)]][pivot:] ) if self._check_if_correct(new_word): new_generation.append(Inhabitant(new_word)) else: new_generation.append( Inhabitant(selection[permutation[(i + 1) % len(permutation)]].gene) ) self.generation = new_generation def mutate( self, min_swap_probability=0.2, max_swap_probability=0.7, inverse_probability=0.001, random_probability=0.05, shift_probability=0.001, insert_probability=0.9, ): swap_probability = random.uniform(min_swap_probability, max_swap_probability) for inhabitant in self.generation[1:]: if decision(insert_probability): insert_amount = random.randint(1, 2) if decision(0.5): # remove decision if(len(inhabitant)+insert_amount < len(self.all_puzzle_keys)): possible_chars = self._random_word() for char in inhabitant.gene: if char in possible_chars: possible_chars.remove(char) if decision(0.33): inhabitant.gene += possible_chars[:insert_amount] elif decision(0.5): inhabitant.gene = possible_chars[:insert_amount] + inhabitant.gene else: insert_index = random.randint(1, len(inhabitant.gene)) inhabitant.gene = inhabitant.gene[:insert_index] + possible_chars[:insert_amount] + inhabitant.gene[insert_index:] else: if(len(inhabitant)-insert_amount > 0): if decision(0.5): inhabitant.gene = inhabitant.gene[insert_amount:] else: inhabitant.gene = inhabitant.gene[:-insert_amount] elif decision(random_probability): inhabitant.gene = self._random_word() else: if decision(shift_probability): shift_range = random.randint(1, 3) for _ in range(shift_range + 1): inhabitant.gene = [inhabitant.gene[-1]] + inhabitant.gene[:-1] for i in range(len(inhabitant.gene) // 2): if decision(swap_probability): random_id = random.randint(0, len(inhabitant) - 1) inhabitant.gene[i], inhabitant.gene[random_id] = ( inhabitant.gene[random_id], inhabitant.gene[i], ) if decision(inverse_probability): inhabitant.gene = inhabitant.gene[::-1]
[ "kubabalicki@gmail.com" ]
kubabalicki@gmail.com
6b92fa590207e262bb21ce2d163a28f41fcac644
21c7776c735f0dccc8694fa67b336b9266b7f9ce
/moss-submit
fcf3dc5d436ee5ef5d9992354f8c50448cb81d74
[ "MIT" ]
permissive
narenakash/nerfherder
0fd15269de632baa8fff0d744430d8dc81689f6d
57edd25872acda7346b386ee56c8f607f9aa0d59
refs/heads/master
2022-08-25T18:33:29.406151
2020-05-18T19:54:54
2020-05-18T19:54:54
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,107
#! /usr/bin/env python3 # -*-Python-*- import argparse, logging, os.path, signal, subprocess, sys def ctrl_c_handler(signum, frame): logging.info('received SIGINT, exiting') sys.exit(0) def fail(message): logging.error(message) sys.exit(1) def main(): parser = argparse.ArgumentParser(description='submit repositories to MOSS for plagiarism detection') parser.add_argument('--filename', required=True, help='name of the single source file within a repo that is checked for plagiarism') parser.add_argument('--skeleton', required=True, help='path to a repo that contains the skeleton/starter code') parser.add_argument('--dir', type=str, default='.', help='directory holding the repos, as downloaded by GitHub Classroom Assistant, defaults to .') parser.add_argument('--language', type=str, default='cc', help='programming language passed to MOSS, defaults to cc') parser.add_argument('--moss', type=str, default='./moss', help='path to the MOSS Perl script, defaults to ./moss') args = parser.parse_args() filename = args.filename skeleton = args.skeleton dir = args.dir language = args.language moss_script_path = args.moss skeleton_file_path = os.path.join(skeleton, filename) if len(language) == 0: fail('not a valid MOSS language: "' + language + '"') if not os.path.isdir(os.path.join(dir, skeleton)): fail('no such skeleton directory: "' + skeleton + '"') if not os.path.isfile(skeleton_file_path): fail('cannot find source file "' + filename + '" in skeleton repo ' + skeleton) if not os.path.isdir(dir): fail('no such directory "' + dir + '"') if not os.path.isfile(moss_script_path): fail('no such script file "' + moss_script_path + '"') if not os.access(moss_script_path, os.R_OK | os.X_OK): fail('script file "' + moss_script_path + '" is not executable') paths = [] logging.info('gathering files:') for subdir in os.listdir(dir): subdir_path = os.path.join(dir, subdir) if not os.path.isdir(subdir_path): logging.info(' skipping non-directory: ' + subdir) continue source_path = os.path.join(subdir_path, filename) if not os.path.isfile(source_path): logging.info(' skipping directory that does not contain ' + filename + ': ' + subdir) continue paths.append(source_path) logging.info('found ' + str(len(paths)) + ' submissions:') for path in paths: logging.info(' ' + path) subprocess.run(([moss_script_path, # script to run '-l', language, # specified programming language '-d', # each submission in its own directory '-b', skeleton_file_path]) # basefile (skeleton code) + paths) # list all source file paths if __name__ == '__main__': logger = logging.getLogger() logger.setLevel(logging.INFO) signal.signal(signal.SIGINT, ctrl_c_handler) main()
[ "kwortman@gmail.com" ]
kwortman@gmail.com
64255b923effc6b87ec7c8fb68ca711c3cc8c91e
6c4d3b0c86e39a474dc00696c765d2a66cbef536
/wbfl10.py
dc749d2278c8e17385b6f5a79852ba4c9a2cce57
[]
no_license
RogerJTX/gensim_splic_sententces_and_words
6e32ac562c11eaa49a3ca3eb21aa4a60227a82ad
416ad34c8c0c45c70da7f75df30998afc4c8fbda
refs/heads/main
2023-03-02T01:33:52.374906
2021-02-15T16:51:38
2021-02-15T16:51:38
332,004,703
0
0
null
null
null
null
UTF-8
Python
false
false
836
py
import jieba import jieba.posseg as pseg from gensim import corpora, models, similarities def StopWordsList(filepath): wlst = [w.strip() for w in open(filepath, 'r', encoding='utf8').readlines()] return wlst def seg_sentence(sentence, stop_words): # stop_flag = ['x', 'c', 'u', 'd', 'p', 't', 'uj', 'm', 'f', 'r']#过滤数字m stop_flag = ['x', 'c', 'u', 'd', 'p', 't', 'uj', 'f', 'r'] sentence_seged = pseg.cut(sentence) # sentence_seged = set(sentence_seged) outstr = [] for word, flag in sentence_seged: # if word not in stop_words: if word not in stop_words and flag not in stop_flag: outstr.append(word) return outstr if __name__ == '__main__': spPath = 'stopwords.txt' tpath = 'test.txt' stop_words = StopWordsList(spPath) keyword = '吃鸡'
[ "jtxia@quant-chi.com" ]
jtxia@quant-chi.com
2ff9a663293f091e9bf221faa038734befb2cf43
1be42b99e0decc4366e9ffacf03ca0169fac1a43
/restie/cli/run.py
49a0ad7d69baf3839dfb3880d401c36777652bb0
[ "Apache-2.0" ]
permissive
NJoyX/nameko-restie
d2b44d57c87e847227149a4319c32698f7ce6598
a7e7cc2e5eb7dc2fc07426b6b68a64da09f66914
refs/heads/master
2021-01-12T01:47:19.526154
2017-06-29T22:03:11
2017-06-29T22:03:11
78,431,507
0
0
null
null
null
null
UTF-8
Python
false
false
1,009
py
from __future__ import print_function import eventlet eventlet.monkey_patch() # noqa (code before rest of imports) import logging import logging.config import sys import yaml from nameko.constants import AMQP_URI_CONFIG_KEY, WEB_SERVER_CONFIG_KEY from nameko.cli.run import import_service, run logger = logging.getLogger(__name__) def main(args): if '.' not in sys.path: sys.path.insert(0, '.') if args.config: with open(args.config) as fle: config = yaml.load(fle) else: config = { AMQP_URI_CONFIG_KEY: args.broker } if args.listen: config[WEB_SERVER_CONFIG_KEY] = args.listen if "LOGGING" in config: logging.config.dictConfig(config['LOGGING']) else: logging.basicConfig(level=logging.INFO, format='%(message)s') services = [] for path in args.services: services.extend( import_service(path) ) run(services, config, backdoor_port=args.backdoor_port)
[ "admin@njoyx.net" ]
admin@njoyx.net
ccdc0dc65bef25e42f74374ec5e25a753c698b45
2c4e38480f522f3762b6967d7cfbf8aae0a948aa
/inst/scripts/create_nullable_arrays.py
f81f6b28c7b0ccc315b3e3b746f6683b268aef14
[]
no_license
grimbough/rhdf5
097f8c48f322172415308491b603ff5b6cb4521a
4d430edf2a95cc9a2e4dfbf857ff6ff41cdef61d
refs/heads/devel
2023-07-27T14:14:36.645790
2023-07-12T09:09:12
2023-07-12T09:09:12
101,306,379
51
24
null
2023-04-05T08:13:17
2017-08-24T14:51:27
R
UTF-8
Python
false
false
378
py
import numpy as np import pandas as pd import anndata as ad import h5py h5_file = h5py.File("/data/nullable_examples.h5", "a") int_array = pd.array([1, None, 3, 4], dtype="Int32") ad.experimental.write_elem(h5_file, "nullable_integer", int_array) bool_array = pd.array([True, False, pd.NA], dtype="boolean") ad.experimental.write_elem(h5_file, "nullable_boolean", bool_array)
[ "grimbough@gmail.com" ]
grimbough@gmail.com
c38608c7409d6365b3229e43371d09039a319f06
4dc690069009216991a70d5525ef07cf1f2d790d
/综合实验/mns_python_sdk/sample/sendmessage.py
f9f45a13db3c64d14ee9282ed871ed07c5111c84
[ "MIT" ]
permissive
michwh/parallel-computing-exercise
f01c814e503f1fbbdd8bc6da0e4fd1055ba5c5c9
96040423a706741c2a5fa2723d357d3a77039312
refs/heads/master
2020-03-29T13:42:18.298809
2018-12-10T15:20:28
2018-12-10T15:20:28
149,977,450
6
2
null
null
null
null
UTF-8
Python
false
false
1,202
py
#!/usr/bin/env python #coding=utf8 import sys import os sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)) + "/..") import time from sample_common import MNSSampleCommon from mns.account import Account from mns.queue import * def my_send_msg(num): # 从sample.cfg中读取基本配置信息 ## WARNING: Please do not hard code your accessId and accesskey in next line.(more information: https://yq.aliyun.com/articles/55947) accid, acckey, endpoint, token = MNSSampleCommon.LoadConfig() # 初始化 my_account, my_queue my_account = Account(endpoint, accid, acckey, token) queue_name = "MyQueue1" my_queue = my_account.get_queue(queue_name) try: # msg_body = "I am test message %s." % i msg_body = num msg = Message(msg_body) re_msg = my_queue.send_message(msg) # print # "Send Message Succeed! MessageBody:%s MessageID:%s" % (msg_body, re_msg.message_id) except MNSExceptionBase, e: if e.type == "QueueNotExist": print "Queue not exist, please create queue before send message." sys.exit(0) print "Send Message Fail! Exception:%s\n" % e
[ "fjsxhwh@163.com" ]
fjsxhwh@163.com
176869291f6071bba98ea44848936d7ceec24616
9b3abcd9c207a015ed611da2a22b48957e46c22d
/18_Django框架网站/dailyfresh/apps/user/models.py
7d2b0e2c38e7610873de8a89d398099678359f03
[]
no_license
it-zyk/PythonCode
6e22aff6705d0e66df74a7c43f62f8a3a8f3f70f
1ee51edad768ff01ba8542b1ddea05aee533524b
refs/heads/master
2020-04-23T05:47:33.691995
2019-05-08T14:07:34
2019-05-08T14:07:34
170,951,360
0
0
null
null
null
null
UTF-8
Python
false
false
1,596
py
from django.db import models from django.contrib.auth.models import AbstractUser from db.base_model import BaseModel # Create your models here. class User(AbstractUser, BaseModel): '''用户模型类''' class Meta: db_table = 'df_user' verbose_name = '用户' verbose_name_plural = verbose_name class AddressManager(models.Manager): '''地址模型管理器类''' # 1.改变原有查询的结果集:all() # 2.封装方法:用户操作模型类对应的数据表(增删改查) def get_default_address(self, user): '''获取用户默认收货地址''' # self.model:获取self对象所在的模型类 try: address = self.get(user=user, is_default=True) # models.Manager except self.model.DoesNotExist: # 不存在默认收货地址 address = None return address class Address(BaseModel): '''地址模型类''' user = models.ForeignKey('User', verbose_name='所属账户') receiver = models.CharField(max_length=20, verbose_name='收件人') addr = models.CharField(max_length=256, verbose_name='收件地址') zip_code = models.CharField(max_length=6, null=True, verbose_name='邮政编码') phone = models.CharField(max_length=11, verbose_name='联系电话') is_default = models.BooleanField(default=False, verbose_name='是否默认') # 自定义一个模型管理器对象 objects = AddressManager() class Meta: db_table = 'df_address' verbose_name = '地址' verbose_name_plural = verbose_name
[ "it-zyk@outlook.com" ]
it-zyk@outlook.com
040e64992a894eb3273cafd53f78ba3efeb4a6be
c963ea584665bf81646b9a333fdbf10a52e8e273
/arithmetic/PrintKNum.py
1a07f0188f4947cba81b0936dbe58f68d2b5c4a4
[]
no_license
LuGuangWang/python
bcf4db388b600e0620c3bd993c7b4645e6a96a29
d38c220b5cc5375308570351c92d4ce5ab59fe88
refs/heads/master
2021-06-09T10:29:27.304553
2021-05-13T11:22:41
2021-05-13T11:22:41
163,352,739
0
0
null
null
null
null
UTF-8
Python
false
false
1,386
py
# coding=utf-8 # 链表中倒数第k个结点 # (1)第一个指针从链表的头指针开始遍历向前走k-1,第二个指针保持不动; # (2)从第k步开始,第二个指针也开始从链表的头指针开始遍历; # (3)由于两个指针的距离保持在k-1,当第一个(走在前面的)指针到达链表的尾结点时,第二个指针(走在后面的)指针正好是倒数第k个结点。 class Node(object): def __init__(self,x): self.val = x self.next = None def sprint(self): tmp = self while tmp is not None: print(tmp.val) tmp = tmp.next def printKNum(list,k): if list is None or k < 0: raise Exception('invalid parameters.') fast = slow = list while fast is not None and k>1: fast = fast.next k -= 1 print('fast:',fast.val) if fast is None: return None while fast.next is not None: fast = fast.next slow = slow.next return slow list = Node(1) list.next=Node(2) list.next.next=Node(3) list.next.next.next=Node(4) list.next.next.next.next=Node(5) list.next.next.next.next.next=Node(6) list.next.next.next.next.next.next=Node(7) list.next.next.next.next.next.next.next=Node(8) list.next.next.next.next.next.next.next.next=Node(9) res = printKNum(list,9) print(res.val) #list.sprint()
[ "wang20081129" ]
wang20081129
01ce29ccc41608e7b9ab3c3e53c70e7465104cb8
fd67592b2338105e0cd0b3503552d188b814ad95
/egoi_api/paths/lists/post.pyi
e1cd61175409ba8d08a6a2aaadd81bc677ac36da
[]
no_license
E-goi/sdk-python
175575fcd50bd5ad426b33c78bdeb08d979485b7
5cba50a46e1d288b5038d18be12af119211e5b9f
refs/heads/master
2023-04-29T20:36:02.314712
2023-04-18T07:42:46
2023-04-18T07:42:46
232,095,340
5
2
null
null
null
null
UTF-8
Python
false
false
16,249
pyi
# coding: utf-8 """ Generated by: https://openapi-generator.tech """ from dataclasses import dataclass import typing_extensions import urllib3 from urllib3._collections import HTTPHeaderDict from egoi_api import api_client, exceptions from datetime import date, datetime # noqa: F401 import decimal # noqa: F401 import functools # noqa: F401 import io # noqa: F401 import re # noqa: F401 import typing # noqa: F401 import typing_extensions # noqa: F401 import uuid # noqa: F401 import frozendict # noqa: F401 from egoi_api import schemas # noqa: F401 from egoi_api.model.request_timeout import RequestTimeout from egoi_api.model.unauthorized import Unauthorized from egoi_api.model.service_unavailable import ServiceUnavailable from egoi_api.model.post_lists_conflict import PostListsConflict from egoi_api.model.post_request_list import PostRequestList from egoi_api.model.bad_request import BadRequest from egoi_api.model.unprocessable_entity import UnprocessableEntity from egoi_api.model.model_list import ModelList from egoi_api.model.internal_server_error import InternalServerError from egoi_api.model.too_many_requests import TooManyRequests from egoi_api.model.forbidden import Forbidden # body param SchemaForRequestBodyApplicationJson = PostRequestList request_body_post_request_list = api_client.RequestBody( content={ 'application/json': api_client.MediaType( schema=SchemaForRequestBodyApplicationJson), }, required=True, ) SchemaFor201ResponseBodyApplicationJson = ModelList @dataclass class ApiResponseFor201(api_client.ApiResponse): response: urllib3.HTTPResponse body: typing.Union[ SchemaFor201ResponseBodyApplicationJson, ] headers: schemas.Unset = schemas.unset _response_for_201 = api_client.OpenApiResponse( response_cls=ApiResponseFor201, content={ 'application/json': api_client.MediaType( schema=SchemaFor201ResponseBodyApplicationJson), }, ) SchemaFor400ResponseBodyApplicationJson = BadRequest @dataclass class ApiResponseFor400(api_client.ApiResponse): response: urllib3.HTTPResponse body: typing.Union[ SchemaFor400ResponseBodyApplicationJson, ] headers: schemas.Unset = schemas.unset _response_for_400 = api_client.OpenApiResponse( response_cls=ApiResponseFor400, content={ 'application/json': api_client.MediaType( schema=SchemaFor400ResponseBodyApplicationJson), }, ) SchemaFor401ResponseBodyApplicationJson = Unauthorized @dataclass class ApiResponseFor401(api_client.ApiResponse): response: urllib3.HTTPResponse body: typing.Union[ SchemaFor401ResponseBodyApplicationJson, ] headers: schemas.Unset = schemas.unset _response_for_401 = api_client.OpenApiResponse( response_cls=ApiResponseFor401, content={ 'application/json': api_client.MediaType( schema=SchemaFor401ResponseBodyApplicationJson), }, ) SchemaFor403ResponseBodyApplicationJson = Forbidden @dataclass class ApiResponseFor403(api_client.ApiResponse): response: urllib3.HTTPResponse body: typing.Union[ SchemaFor403ResponseBodyApplicationJson, ] headers: schemas.Unset = schemas.unset _response_for_403 = api_client.OpenApiResponse( response_cls=ApiResponseFor403, content={ 'application/json': api_client.MediaType( schema=SchemaFor403ResponseBodyApplicationJson), }, ) SchemaFor408ResponseBodyApplicationJson = RequestTimeout @dataclass class ApiResponseFor408(api_client.ApiResponse): response: urllib3.HTTPResponse body: typing.Union[ SchemaFor408ResponseBodyApplicationJson, ] headers: schemas.Unset = schemas.unset _response_for_408 = api_client.OpenApiResponse( response_cls=ApiResponseFor408, content={ 'application/json': api_client.MediaType( schema=SchemaFor408ResponseBodyApplicationJson), }, ) SchemaFor409ResponseBodyApplicationJson = PostListsConflict @dataclass class ApiResponseFor409(api_client.ApiResponse): response: urllib3.HTTPResponse body: typing.Union[ SchemaFor409ResponseBodyApplicationJson, ] headers: schemas.Unset = schemas.unset _response_for_409 = api_client.OpenApiResponse( response_cls=ApiResponseFor409, content={ 'application/json': api_client.MediaType( schema=SchemaFor409ResponseBodyApplicationJson), }, ) SchemaFor422ResponseBodyApplicationJson = UnprocessableEntity @dataclass class ApiResponseFor422(api_client.ApiResponse): response: urllib3.HTTPResponse body: typing.Union[ SchemaFor422ResponseBodyApplicationJson, ] headers: schemas.Unset = schemas.unset _response_for_422 = api_client.OpenApiResponse( response_cls=ApiResponseFor422, content={ 'application/json': api_client.MediaType( schema=SchemaFor422ResponseBodyApplicationJson), }, ) SchemaFor429ResponseBodyApplicationJson = TooManyRequests @dataclass class ApiResponseFor429(api_client.ApiResponse): response: urllib3.HTTPResponse body: typing.Union[ SchemaFor429ResponseBodyApplicationJson, ] headers: schemas.Unset = schemas.unset _response_for_429 = api_client.OpenApiResponse( response_cls=ApiResponseFor429, content={ 'application/json': api_client.MediaType( schema=SchemaFor429ResponseBodyApplicationJson), }, ) SchemaFor500ResponseBodyApplicationJson = InternalServerError @dataclass class ApiResponseFor500(api_client.ApiResponse): response: urllib3.HTTPResponse body: typing.Union[ SchemaFor500ResponseBodyApplicationJson, ] headers: schemas.Unset = schemas.unset _response_for_500 = api_client.OpenApiResponse( response_cls=ApiResponseFor500, content={ 'application/json': api_client.MediaType( schema=SchemaFor500ResponseBodyApplicationJson), }, ) SchemaFor503ResponseBodyApplicationJson = ServiceUnavailable @dataclass class ApiResponseFor503(api_client.ApiResponse): response: urllib3.HTTPResponse body: typing.Union[ SchemaFor503ResponseBodyApplicationJson, ] headers: schemas.Unset = schemas.unset _response_for_503 = api_client.OpenApiResponse( response_cls=ApiResponseFor503, content={ 'application/json': api_client.MediaType( schema=SchemaFor503ResponseBodyApplicationJson), }, ) _all_accept_content_types = ( 'application/json', ) class BaseApi(api_client.Api): @typing.overload def _create_list_oapg( self, body: typing.Union[SchemaForRequestBodyApplicationJson,], content_type: typing_extensions.Literal["application/json"] = ..., accept_content_types: typing.Tuple[str] = _all_accept_content_types, stream: bool = False, timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, skip_deserialization: typing_extensions.Literal[False] = ..., ) -> typing.Union[ ApiResponseFor201, ]: ... @typing.overload def _create_list_oapg( self, body: typing.Union[SchemaForRequestBodyApplicationJson,], content_type: str = ..., accept_content_types: typing.Tuple[str] = _all_accept_content_types, stream: bool = False, timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, skip_deserialization: typing_extensions.Literal[False] = ..., ) -> typing.Union[ ApiResponseFor201, ]: ... @typing.overload def _create_list_oapg( self, body: typing.Union[SchemaForRequestBodyApplicationJson,], skip_deserialization: typing_extensions.Literal[True], content_type: str = ..., accept_content_types: typing.Tuple[str] = _all_accept_content_types, stream: bool = False, timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, ) -> api_client.ApiResponseWithoutDeserialization: ... @typing.overload def _create_list_oapg( self, body: typing.Union[SchemaForRequestBodyApplicationJson,], content_type: str = ..., accept_content_types: typing.Tuple[str] = _all_accept_content_types, stream: bool = False, timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, skip_deserialization: bool = ..., ) -> typing.Union[ ApiResponseFor201, api_client.ApiResponseWithoutDeserialization, ]: ... def _create_list_oapg( self, body: typing.Union[SchemaForRequestBodyApplicationJson,], content_type: str = 'application/json', accept_content_types: typing.Tuple[str] = _all_accept_content_types, stream: bool = False, timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, skip_deserialization: bool = False, ): """ Create new list :param skip_deserialization: If true then api_response.response will be set but api_response.body and api_response.headers will not be deserialized into schema class instances """ used_path = path.value _headers = HTTPHeaderDict() # TODO add cookie handling if accept_content_types: for accept_content_type in accept_content_types: _headers.add('Accept', accept_content_type) if body is schemas.unset: raise exceptions.ApiValueError( 'The required body parameter has an invalid value of: unset. Set a valid value instead') _fields = None _body = None serialized_data = request_body_post_request_list.serialize(body, content_type) _headers.add('Content-Type', content_type) if 'fields' in serialized_data: _fields = serialized_data['fields'] elif 'body' in serialized_data: _body = serialized_data['body'] response = self.api_client.call_api( resource_path=used_path, method='post'.upper(), headers=_headers, fields=_fields, body=_body, auth_settings=_auth, stream=stream, timeout=timeout, ) if skip_deserialization: api_response = api_client.ApiResponseWithoutDeserialization(response=response) else: response_for_status = _status_code_to_response.get(str(response.status)) if response_for_status: api_response = response_for_status.deserialize(response, self.api_client.configuration) else: api_response = api_client.ApiResponseWithoutDeserialization(response=response) if not 200 <= response.status <= 299: raise exceptions.ApiException(api_response=api_response) return api_response class CreateList(BaseApi): # this class is used by api classes that refer to endpoints with operationId fn names @typing.overload def create_list( self, body: typing.Union[SchemaForRequestBodyApplicationJson,], content_type: typing_extensions.Literal["application/json"] = ..., accept_content_types: typing.Tuple[str] = _all_accept_content_types, stream: bool = False, timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, skip_deserialization: typing_extensions.Literal[False] = ..., ) -> typing.Union[ ApiResponseFor201, ]: ... @typing.overload def create_list( self, body: typing.Union[SchemaForRequestBodyApplicationJson,], content_type: str = ..., accept_content_types: typing.Tuple[str] = _all_accept_content_types, stream: bool = False, timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, skip_deserialization: typing_extensions.Literal[False] = ..., ) -> typing.Union[ ApiResponseFor201, ]: ... @typing.overload def create_list( self, body: typing.Union[SchemaForRequestBodyApplicationJson,], skip_deserialization: typing_extensions.Literal[True], content_type: str = ..., accept_content_types: typing.Tuple[str] = _all_accept_content_types, stream: bool = False, timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, ) -> api_client.ApiResponseWithoutDeserialization: ... @typing.overload def create_list( self, body: typing.Union[SchemaForRequestBodyApplicationJson,], content_type: str = ..., accept_content_types: typing.Tuple[str] = _all_accept_content_types, stream: bool = False, timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, skip_deserialization: bool = ..., ) -> typing.Union[ ApiResponseFor201, api_client.ApiResponseWithoutDeserialization, ]: ... def create_list( self, body: typing.Union[SchemaForRequestBodyApplicationJson,], content_type: str = 'application/json', accept_content_types: typing.Tuple[str] = _all_accept_content_types, stream: bool = False, timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, skip_deserialization: bool = False, ): return self._create_list_oapg( body=body, content_type=content_type, accept_content_types=accept_content_types, stream=stream, timeout=timeout, skip_deserialization=skip_deserialization ) class ApiForpost(BaseApi): # this class is used by api classes that refer to endpoints by path and http method names @typing.overload def post( self, body: typing.Union[SchemaForRequestBodyApplicationJson,], content_type: typing_extensions.Literal["application/json"] = ..., accept_content_types: typing.Tuple[str] = _all_accept_content_types, stream: bool = False, timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, skip_deserialization: typing_extensions.Literal[False] = ..., ) -> typing.Union[ ApiResponseFor201, ]: ... @typing.overload def post( self, body: typing.Union[SchemaForRequestBodyApplicationJson,], content_type: str = ..., accept_content_types: typing.Tuple[str] = _all_accept_content_types, stream: bool = False, timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, skip_deserialization: typing_extensions.Literal[False] = ..., ) -> typing.Union[ ApiResponseFor201, ]: ... @typing.overload def post( self, body: typing.Union[SchemaForRequestBodyApplicationJson,], skip_deserialization: typing_extensions.Literal[True], content_type: str = ..., accept_content_types: typing.Tuple[str] = _all_accept_content_types, stream: bool = False, timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, ) -> api_client.ApiResponseWithoutDeserialization: ... @typing.overload def post( self, body: typing.Union[SchemaForRequestBodyApplicationJson,], content_type: str = ..., accept_content_types: typing.Tuple[str] = _all_accept_content_types, stream: bool = False, timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, skip_deserialization: bool = ..., ) -> typing.Union[ ApiResponseFor201, api_client.ApiResponseWithoutDeserialization, ]: ... def post( self, body: typing.Union[SchemaForRequestBodyApplicationJson,], content_type: str = 'application/json', accept_content_types: typing.Tuple[str] = _all_accept_content_types, stream: bool = False, timeout: typing.Optional[typing.Union[int, typing.Tuple]] = None, skip_deserialization: bool = False, ): return self._create_list_oapg( body=body, content_type=content_type, accept_content_types=accept_content_types, stream=stream, timeout=timeout, skip_deserialization=skip_deserialization )
[ "integrations@e-goi.com" ]
integrations@e-goi.com
da0f78f79ae6d191a86694b0fe988dbbdf697df6
a4d618fa8c1dcef1f00cf7f5ab367f4cd443b666
/scripts_py/wall_steady_state_automatization/postprocessing/heat_distribution/compute_energyRa.py
218241d24293f5449320b705325a7875cd5de870
[]
no_license
jdesmarais/dim2D_finite_volume
839e0abb42e32ea7ff5822c419e09630aee0eadb
5849979d54d464f2c95778bf73ef39987bcc9ff6
refs/heads/master
2021-05-31T01:14:58.459731
2016-01-18T08:58:53
2016-01-18T08:58:53
46,810,746
1
0
null
null
null
null
UTF-8
Python
false
false
6,097
py
#!/usr/bin/python ''' @description: compute the heat distribution, i.e. the amount of heat which is transported across the domain borders, the heat used for the phase transition and the heat used to increase the internal energy of the fluid ''' # library imports #------------------------------------------------------------ import sys import os import getopt import subprocess import shlex import numpy as np from library_messages import print_mg_error from compute_energyPh import check_inputFile # functions #------------------------------------------------------------ # display the help for the program def display_help(): ''' @description: display program help ''' print '' print 'compute the energy ratio from the energy supplied by' print 'the wall, the energy transported across the domain borders' print 'and the energy used for the phase transition' print '' print 'options:' print '--------' print '-h (--help) : display this help' print '-w (--wall=) : netcdf file whose header contains the wall energy' print '-t (--transport=) : text file with the energy transported' print '-p (--phase=) : text file with the energy for phase transition' print '-o (--output=) : text file for the output' print '' #parse the input options def parse_argv(argv): ''' @description: parse the program options ''' #default values mainDir = 'None' # store the options and the arguments # in opts, args try: opts, args = getopt.getopt(argv, "hi:w:t:p:o:", ["help", "wall=", "transport=", "phase=", "output="]) except getopt.GetoptError: display_help() sys.exit(2) if(len(opts)==0): display_help() sys.exit(2) wallFile = 'None' transportFile = 'None' phaseFile = 'None' outputFile = 'None' # options for opt, arg in opts: if opt in ("-h", "--help"): display_help() sys.exit(2) elif opt in ("-w", "--wall"): wallFile = arg elif opt in ("-t", "--transport"): transportFile = arg elif opt in ("-p", "--phase"): phaseFile = arg elif opt in ("-o", "--output"): outputFile = arg # check the wall file check_inputFile(wallFile,errorMg='wall file not provided') # check the transport file check_inputFile(transportFile,errorMg='transport file not provided') # check the phase file check_inputFile(phaseFile,errorMg='phase file not provided') # check for directory where the output file should be saved if(outputFile=='None'): print_mg_error('output path not provided') display_help() sys.exit(2) else: if( not os.path.isdir(os.path.dirname(outputFile)) and (not os.path.dirname(outputFile)=='')): print_mg_error('output dir does not exist') display_help() sys.exit(2) return wallFile, transportFile, phaseFile, outputFile # extract the energy rate supplied by the wall from the # header of the netcdf file def extract_energyWa(wallFile): ''' @description: extract the energy rate supplied by the wall from the header of the netcdf file ''' cmd='ncdump -h '+wallFile args = shlex.split(cmd) output = subprocess.Popen(args,stdout=subprocess.PIPE).communicate()[0] output = output.split('wall_maximum_heat_source')[1].split(';')[0].replace('=','') try: energyWa = float(output) except ValueError: print_mg_error('extract_energyWa') print_mg_error('error when converting wall energy to float') print_mg_error('output from ncdump: ',output) sys.exit(2) return energyWa # compute the energy distribution between transport, # phase transition, and internal energy def compute_energyRa(wallFile, transportFile, phaseFile, outputFile): ''' @description: compute the energy distribution between transport, phase transition, and internal energy ''' # extract the heat flux provided by the wall from # the netcdf file, wallFile energyWa = extract_energyWa(wallFile) # extract the data for the energy flowing # across the domain borders energyTr = np.loadtxt(transportFile) # extract the data for the energy # used by the phase transition process energyPh = np.loadtxt(phaseFile) # find the file index matching the # energyTr and energyPh data tmin = int(energyTr[0,0]) while tmin<int(energyPh[0,0]): tmin+=1 if(tmin>int(energyTr[-1,0])): print_mg_error('compute_energyRa') print_mg_error('cannot find the file index') print_mg_error('to match energyTr and energyPh') sys.exit(2) tmax = int(energyPh[-1,0]) # compute the energy ratios if(os.path.isfile(outputFile)): os.remove(outputFile) out = open(outputFile,'w') for t in range(tmin,tmax+1): if(int(energyTr[t,1])!=int(energyPh[t-tmin,1])): print_mg_error('compute_energyRa') print_mg_error('mismatch between energyTr and energyPh data') sys.exit(2) energyTr_r = energyTr[t,2]/energyWa*100 energyPh_r = energyPh[t-tmin,2]/energyWa*100 energyIn_r = 100-(energyTr_r+energyPh_r) out.write("%i %f %f %f %f\n" % (t,energyTr[t,1],energyTr_r,energyPh_r,energyIn_r)) out.close() if __name__=='__main__': # extract the options from the command line wallFile, transportFile, phaseFile, outputFile = parse_argv(sys.argv[1:]) # compute the energy distribution between # transport, phase transition and internal energy compute_energyRa(wallFile, transportFile, phaseFile, outputFile)
[ "desmaraisjulien@gmail.com" ]
desmaraisjulien@gmail.com
1d82f772f429dc0332e5f8d1b7f993895f9f527b
b2e1d96c0551b6b31ef85353f9b6e5b6354d64e8
/datafaucet/spark/rows.py
97e9ffa97152917b124d55ef93a80b38b4716046
[ "MIT" ]
permissive
SylarCS/datafaucet-1
8bd7b96cecc5592e153b61367892e2a63a96119d
a63074ba1fb1a6d15f06e2bfff05df754aaaa452
refs/heads/master
2020-09-15T06:04:31.999012
2019-11-18T20:00:55
2019-11-18T20:00:55
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,062
py
import sys from random import randint from pyspark.sql import DataFrame from datafaucet.spark import dataframe INT_MAX = sys.maxsize INT_MIN = -sys.maxsize-1 def sample(df, n=1000, *col, seed=None): # n 0<float<=1 -> fraction of samples # n floor(int)>1 -> number of samples # todo: # n dict of key, value pairs or array of (key, value) # cols = takes alist of columns for sampling if more than one column is provided # if a stratum is not specified, provide equally with what is left over form the total of the other quota if n>1: count = df.count() fraction = n/count return df if fraction>1 else df.sample(False, fraction, seed=seed) else: return df.sample(False, n, seed=seed) _sample = sample class Rows: def __init__(self, df, scols=None, gcols=None): self.df = df self.gcols = gcols or [] self.scols = scols or df.columns self.scols = list(set(self.scols) - set(self.gcols)) @property def columns(self): return [x for x in self.df.columns if x in (self.scols + self.gcols)] def overwrite(self,data): df = self.df return df.sql_ctx.createDataFrame(data,df.schema) def append(self, data): df = self.df return df.unionByName(df.sql_ctx.createDataFrame(data, df.schema)) def sample(self, n=1000, *cols, random_state=True): return _sample(self.df, n, *cols, random_state) def filter_by_date(self, column=None, start=None, end=None, window=None): df = dataframe.filter_by_datetime(self.df, column, start, end, window) return df def filter(self, *args, **kwargs): return self.df.filter(*args, **kwargs) @property def cols(self): from datafaucet.spark.cols import Cols return Cols(self.df, self.scols, self.gcols) @property def data(self): from datafaucet.spark.data import Data return Data(self.df, self.scols, self.gcols) def _rows(self): return Rows(self) DataFrame.rows = property(_rows)
[ "natalino.busa@gmail.com" ]
natalino.busa@gmail.com