code stringlengths 1 1.72M | language stringclasses 1 value |
|---|---|
from foaflib.helpers.basehelper import BaseHelper
from foaflib.utils.activitystreamevent import ActivityStreamEvent
class Delicious(BaseHelper):
def __init__(self):
try:
import feedparser
self.feedparser = feedparser
self._supported = True
except ImportError:
self._supported = False
def _accept_account(self, account):
homepage = account.accountServiceHomepage
return "del.icio.us" in homepage or "delicious.com" in homepage
def _handle_account(self, account):
events = []
username = account.accountName
if not username:
return events
feed_url = "http://feeds.delicious.com/v2/rss/%s?count=15" % username
entries = self.feedparser.parse(feed_url)["entries"]
for entry in entries:
event = ActivityStreamEvent()
event.type = "Del.icio.us"
event.detail = "Bookmarked: %s" % entry.title
event.link = entry.link
event.timestamp = entry.updated_parsed
events.append(event)
return events
| Python |
import foaflib.helpers.blog as blog
from foaflib.helpers.delicious import Delicious
from foaflib.helpers.identica import Identica
from foaflib.helpers.twitter_ import Twitter
try:
from feedformatter import Feed
_CAN_DO_FEEDS_ = True
except ImportError:
_CAN_DO_FEEDS_ = False
_ALL_HELPERS_ = [Delicious]
_ALL_HELPERS_.append(Identica)
_ALL_HELPERS_.append(Twitter)
class ActivityStream(object):
def __init__(self, foafperson):
self.person = foafperson
self.helpers = []
for helper in _ALL_HELPERS_:
self.helpers.append(helper())
def get_latest_events(self, count=10):
events = []
events.extend(blog.get_latest(self.person))
for helper in self.helpers:
events.extend(helper.get_latest(self.person))
events.sort()
events.reverse()
return events[0:count]
def build_feed(self):
if not _CAN_DO_FEEDS_:
return None
feed = Feed()
feed.feed["title"] = self.person.name + "'s Activity Stream"
feed.feed["description"] = self.person.name + "'s Activity Stream"
feed.feed["link"] = self.person.uri
feed.feed["author"] = self.person.name
for event in self.get_latest_events():
item = {}
item["title"] = event.type + " - " + event.detail
item["pubDate"] = event.timestamp
item["link"] = event.link
item["guid"] = event.link
feed.items.append(item)
return feed
| Python |
from hashlib import sha1
from foaflib.utils.basicscutter import BasicScutter
class FileStorageScutter(BasicScutter):
def __init__(self, directory, seed_uris=None):
BasicScutter.__init__(self, seed_uris)
self.directory = directory
def handle_person(self, foafperson):
filename = self.directory + "/" + sha1((foafperson.name or "noname") + (foafperson.homepage or "nohomepage")).hexdigest()
foafperson.save_as_xml_file(filename)
return foafperson
| Python |
class ActivityStreamEvent(object):
def __init__(self):
self.type = ""
self.detail = ""
self.link = ""
self.timestamp = None
def __cmp__(self, other):
return cmp(self.timestamp, other.timestamp)
| Python |
from robotparser import RobotFileParser
from urlparse import urljoin
import rdflib
from foaflib.classes.person import Person
class BasicScutter(object):
def __init__(self, seed_uris=None):
self.useragent = "foaflib"
if seed_uris is None:
seed_uris = []
self.current_list = seed_uris
self.next_list = []
self.seen_uris = []
self.rp = RobotFileParser()
def _can_access(self, uri):
try:
self.rp.set_url(urljoin(uri,"/robots.txt"))
self.rp.read()
return self.rp.can_fetch(self.useragent, uri)
except IOError:
# If uncertain, best to be polite
return False
def handle_person(self, person):
return person
def scutter(self, uri_limit=0, depth_limit=0):
uri_count = 0
depth_count = -1 # (Clearing the seed list doesn't count)
while self.current_list:
if depth_limit and depth_count == depth_limit:
return
for uri in self.current_list:
if uri in self.seen_uris:
continue
if not self._can_access(uri):
continue
try:
p = Person(uri)
self.seen_uris.append(uri)
except:
continue
if not depth_limit or (depth_limit and depth_count < depth_limit - 1):
for friend in p._graph.objects(predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/knows')):
for uri in p._graph.objects(subject=friend, predicate=rdflib.URIRef("http://www.w3.org/2000/01/rdf-schema#seeAlso")):
self.next_list.append(uri)
break
uri_count +=1
yield self.handle_person(p)
if uri_count == uri_limit:
return
self.current_list = self.next_list[:]
self.next_list = []
depth_count +=1
| Python |
import rdflib
class OnlineAccount(object):
def __init__(self, graph=None, node=None):
self.accountServiceHomepage = ""
self.accountName = ""
self.accountProfilePage = ""
if graph and node:
for homepage in graph.objects(subject=node, predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/accountServiceHomepage')):
self.accountServiceHomepage = unicode(homepage)
for name in graph.objects(subject=node, predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/accountName')):
self.accountName = unicode(name)
for profilepage in graph.objects(subject=node, predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/accountProfilePage')):
self.accountProfilePage = unicode(profilepage)
| Python |
import rdflib
from rdflib.Graph import ConjunctiveGraph as Graph
from urllib import urlopen
from foaflib.classes.onlineaccount import OnlineAccount
_SINGLETONS = """gender openid birthday pubkeyAddress""".split()
_BASIC_MULTIS = """mbox mbox_sha1sum jabberID aimChatID icqChatID yahooChatID msnChatID weblog tipjar made holdsAccount""".split()
class Agent(object):
def __init__(self, path=None):
for name in _BASIC_MULTIS:
setattr(self, "_get_%ss" % name, self._make_getter(name))
setattr(Agent, "%ss" % name, property(self._make_property_getter(name)))
setattr(self, "add_%s" % name, self._make_adder(name))
setattr(self, "del_%s" % name, self._make_deler(name))
self._graph = Graph()
if path:
self._graph.parse(path)
for topic in self._graph.objects(predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/primaryTopic')):
self._me = topic
# Things you can only reasonably have one of - gender, birthday, first name, etc. - are termed
# "singletons". Singletion I/O is handled purely through __getattr__ and __setattr__, below.
def __getattr__(self, name):
if name in _SINGLETONS:
for raw in self._graph.objects(subject=self._me, predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/%s' % name)):
return unicode(raw)
return None
raise AttributeError, name
def __setattr__(self, name, value):
if name in _SINGLETONS:
self._graph.remove((self._me, rdflib.URIRef('http://xmlns.com/foaf/0.1/%s' % name), None))
self._graph.add((self._me, rdflib.URIRef('http://xmlns.com/foaf/0.1/%s' % name), value))
else:
object.__setattr__(self, name, value)
# Stuff you might have more than one of - weblogs, accounts, friends, etc. - are handled by a
# combination of the property decorator and add/del methods.
def _make_getter(self, name):
def method():
return [unicode(x) for x in self._graph.objects(subject=self._me, predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/%s' % name))]
return method
def _make_property_getter(self, name):
def method(self):
return [unicode(x) for x in self._graph.objects(subject=self._me, predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/%s' % name))]
return method
def _make_adder(self, name):
def method(value):
self._graph.add((self._me, rdflib.URIRef('http://xmlns.com/foaf/0.1/%s' % name), rdflib.URIRef(value)))
return method
def _make_deler(self, name):
def method(value):
self._graph.remove((self._me, rdflib.URIRef('http://xmlns.com/foaf/0.1/%s' % name), rdflib.URIRef(value)))
return method
def _build_account(self, acct):
if isinstance(acct, rdflib.BNode):
return OnlineAccount(self._graph, acct)
elif isinstance(acct, rdflib.URIRef):
account = OnlineAccount()
account.accountServiceHomepage = unicode(acct)
return account
return OnlineAccount()
def _get_accounts(self):
for raw_account in self._graph.objects(predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/holdsAccount')):
account = self._build_account(raw_account)
if account:
yield account
accounts = property(_get_accounts)
def add_account(self, account):
x = rdflib.BNode()
self._graph.add((x, rdflib.URIRef("http://xmlns.com/foaf/0.1/accountServiceHomepage"), rdflib.URIRef(account.accountServiceHomepage)))
self._graph.add((x, rdflib.URIRef("http://xmlns.com/foaf/0.1/accountName"), rdflib.URIRef(account.accountName)))
if account.accountProfilePage:
self._graph.add((x, rdflib.URIRef("http://xmlns.com/foaf/0.1/accountProfilePage"), rdflib.URIRef(account.accountProfilePage)))
self._graph.add((self._me, rdflib.URIRef("http://xmlns.com/foaf/0.1/holdsAccount"), x))
# Serialisation
def get_xml_string(self):
self._graph.serialize()
def save_as_xml_file(self, filename):
self._graph.serialize(filename)
# Account stuff
| Python |
import rdflib
from rdflib.Graph import ConjunctiveGraph as Graph
from urllib import urlopen
from foaflib.classes.agent import Agent
_SINGLETONS = "title name nick givenname firstName surname family_name homepage geekcode meyersBriggs dnaChecksum plan".split()
_BASIC_MULTIS = "schoolHomepage workplaceHomepage img currentProject pastProject publications isPrimaryTopicOf page made workInfoHomepage interest".split()
class Person(Agent):
def __init__(self, uri=None):
Agent.__init__(self)
for name in _BASIC_MULTIS:
setattr(self, "_get_%ss" % name, self._make_getter(name))
setattr(Person, "%ss" % name, property(self._make_property_getter(name)))
setattr(self, "add_%s" % name, self._make_adder(name))
setattr(self, "del_%s" % name, self._make_deler(name))
self._graph = Graph()
self._error = False
if uri:
self.uri = uri
try:
self._graph.parse(uri)
self._find_me_node()
except:
self._error = True
else:
self.uri = ""
self._setup_profile()
def _setup_profile(self):
x = rdflib.BNode()
self._graph.add((x, rdflib.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), rdflib.URIRef('http://xmlns.com/foaf/0.1/PersonalProfileDocument')))
self._graph.add((x, rdflib.URIRef('http://webns.net/mvcb/generatorAgent'), rdflib.URIRef('http://code.google.com/p/foaflib')))
self._graph.add((x, rdflib.URIRef('http://xmlns.com/foaf/0.1/primaryTopic'), rdflib.URIRef('#me')))
self._graph.add((rdflib.URIRef('#me'), rdflib.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), rdflib.URIRef('http://xmlns.com/foaf/0.1/Person')))
self._me = rdflib.URIRef('#me')
def _get_people(self):
return self._graph.subjects(rdflib.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), rdflib.URIRef('http://xmlns.com/foaf/0.1/Person'))
def _find_me_node(self):
# Check for a PersonalProfileDocument
for doc in self._graph.subjects(predicate=rdflib.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), object=rdflib.URIRef('http://xmlns.com/foaf/0.1/PersonalProfileDocument')):
for topic in self._graph.objects(subject=doc, predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/primaryTopic')):
self._me = topic
return
# Check for a single Person
if len(list(self._get_people())) == 1:
for person in self._get_people():
self._me = person
return
# Return someone who isn't known by anyone else in this graph - the best we can do?
for person in self._get_people():
knowers = self._graph.subjects(rdflib.URIRef('http://xmlns.com/foaf/0.1/knows'), person)
if len(list(knowers)) == 0:
self._me = person
return
# Things you can only reasonably have one of - gender, birthday, first name, etc. - are termed
# "singletons". Singletion I/O is handled purely through __getattr__ and __setattr__, below.
def __getattr__(self, name):
if name in _SINGLETONS:
for raw in self._graph.objects(subject=self._me, predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/%s' % name)):
return unicode(raw)
return None
return Agent.__getattr__(self, name)
def __setattr__(self, name, value):
if name in _SINGLETONS:
self._graph.remove((self._me, rdflib.URIRef('http://xmlns.com/foaf/0.1/%s' % name), None))
self._graph.add((self._me, rdflib.URIRef('http://xmlns.com/foaf/0.1/%s' % name), value))
else:
Agent.__setattr__(self, name, value)
def _build_friend(self, raw_friend):
if isinstance(raw_friend, rdflib.URIRef):
return Person(unicode(raw_friend))
elif isinstance(raw_friend, rdflib.BNode):
# If a "seeAlso" gives us the URI of the friend's FOAF profile, use that
for uri in self._graph.objects(subject=raw_friend, predicate=rdflib.URIRef("http://www.w3.org/2000/01/rdf-schema#seeAlso")):
return Person(unicode(uri))
# Otherwise just build a Person up from what we have
f = Person()
for (s,p,o) in self._graph.triples((raw_friend, None, None)):
f._graph.add((f._get_primary_topic(),p,o))
return f
def _get_friends(self):
for raw_friend in self._graph.objects(predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/knows')):
friend = self._build_friend(raw_friend)
if friend:
yield friend
friends = property(_get_friends)
def add_friend(self, friend):
x = rdflib.BNode()
self._graph.add((self._me, rdflib.URIRef('http://xmlns.com/foaf/0.1/knows'), x))
self._graph.add((x, rdflib.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), rdflib.URIRef('http://xmlns.com/foaf/0.1/Person')))
if friend.name:
self._graph.add((x, rdflib.URIRef('http://xmlns.com/foaf/0.1/name'), friend.name))
if friend.homepage:
self._graph.add((x, rdflib.URIRef('http://xmlns.com/foaf/0.1/homepage'), friend.homepage))
for mbox in friend.mboxs:
self._graph.add((x, rdflib.URIRef('http://xmlns.com/foaf/0.1/mbox'), mbox))
for mbox_sha1sum in friend.mbox_sha1sums:
self._graph.add((x, rdflib.URIRef('http://xmlns.com/foaf/0.1/mbox_sha1sum'), mbox_sha1sum))
if friend.uri:
self._graph.add((x, rdflib.URIRef("http://www.w3.org/2000/01/rdf-schema#seeAlso"), friend.uri))
def _build_fast_friend(self, raw_friend):
if isinstance(raw_friend, rdflib.URIRef):
return Person(unicode(raw_friend))
elif isinstance(raw_friend, rdflib.BNode):
f = Person()
for (s,p,o) in self._graph.triples((raw_friend, None, None)):
f._graph.add((f._get_primary_topic(),p,o))
return f
def _get_fast_friends(self):
for raw_friend in self._graph.objects(predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/knows')):
friend = self._build_fast_friend(raw_friend)
if friend:
yield friend
fast_friends = property(_get_fast_friends)
def _build_fastest_friend(self, raw_friend):
if isinstance(raw_friend, rdflib.URIRef):
return None
elif isinstance(raw_friend, rdflib.BNode):
f = Person()
for (s,p,o) in self._graph.triples((raw_friend, None, None)):
f._graph.add((f._get_primary_topic(),p,o))
return f
def _get_fastest_friends(self):
for raw_friend in self._graph.objects(predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/knows')):
friend = self._build_fastest_friend(raw_friend)
if friend:
yield friend
fastest_friends = property(_get_fastest_friends)
# Serialisation
def get_xml_string(self, format="rdf/xml"):
return self._graph.serialize(format=format)
def save_as_xml_file(self, filename, format="rdf/xml"):
self._graph.serialize(filename, format=format)
| Python |
#!/usr/bin/env python
from setuptools import setup
setup(name="foaflib",
version="0.2",
description="Python library for working with FOAF data",
author="Luke Maurits",
author_email="luke@maurits.id.au",
url="http://code.google.com/p/foaflib/",
packages=["foaflib", "foaflib.classes", "foaflib.helpers", "foaflib.utils"],
install_requires=["rdflib"]
)
| Python |
#!/usr/bin/env python
from setuptools import setup
setup(name="foaflib",
version="0.1",
description="Python library for working with FOAF data",
author="Luke Maurits",
author_email="luke@maurits.id.au",
url="http://code.google.com/p/foaflib/",
packages=["foaflib", "foaflib.classes", "foaflib.helpers", "foaflib.utils"],
install_requires=["rdflib"]
)
| Python |
from foaflib.utils.activitystreamevent import ActivityStreamEvent
try:
from urllib import urlopen
from urlparse import urljoin
from BeautifulSoup import BeautifulSoup
from feedparser import parse
_CAN_DO_ = True
except ImportError:
_CAN_DO_ = False
def get_latest(foafprofile):
entries = []
if not _CAN_DO_:
return entries
for blog in foafprofile.weblogs:
u = urlopen(blog)
blogpage = u.read()
u.close()
try:
bs = BeautifulSoup(blogpage)
feeds = bs.findAll("link",{"type":"application/rss+xml"})
for feed in feeds:
try:
feed_url = urljoin(blog, feed["href"])
feedentries = []
for entry in parse(feed_url)["entries"]:
event = ActivityStreamEvent()
event.type = "Blog post"
event.detail = entry["title"]
if "published_parsed" in entry:
event.timestamp = entry["published_parsed"]
if "updated_parsed" in entry:
event.timestamp = entry["updated_parsed"]
feedentries.append(event)
entries.extend(feedentries)
break
except:
continue
except:
continue
return entries
| Python |
from foaflib.utils.activitystreamevent import ActivityStreamEvent
class BaseHelper(object):
def __init__(self):
self._supported = False
def _accept_account(self, onlineaccount):
return False
def _handle_account(self, onlineaccount):
return None
def get_latest(self, foafperson):
if not self._supported:
return []
events = []
for account in foafperson.accounts:
if self._accept_account(account):
account_events = self._handle_account(account)
account_events = filter(lambda x: isinstance(x, ActivityStreamEvent), account_events)
events.extend(account_events)
return events
| Python |
from foaflib.utils.activitystreamevent import ActivityStreamEvent
from foaflib.helpers.basehelper import BaseHelper
class Identica(BaseHelper):
def __init__(self):
BaseHelper.__init__(self)
try:
import feedparser
self.feedparser = feedparser
self._supported = True
except ImportError:
self._supported = False
def _accept_account(self, account):
return "identi.ca" in account.accountServiceHomepage
def _handle_account(self, account):
events = []
username = account.accountName
if not username:
return events
url = "https://identi.ca/api/statuses/user_timeline/%s.atom" % username
try:
feedentries = self.feedparser.parse(url)["entries"]
for entry in feedentries:
event = ActivityStreamEvent()
event.type = "Identi.ca"
event.detail = entry["title"]
event.link = entry["link"]
event.timestamp = entry["published_parsed"]
events.append(event)
except:
pass
return events
| Python |
from foaflib.helpers.basehelper import BaseHelper
from foaflib.utils.activitystreamevent import ActivityStreamEvent
class Twitter(BaseHelper):
def __init__(self):
BaseHelper.__init__(self)
try:
import twitter
self.twitter = twitter
import time
self.time = time
self._supported = True
except ImportError:
self._supported = False
def _accept_account(self, account):
return "twitter.com" in account.accountServiceHomepage
def _handle_account(self, account):
if account.accountName:
username = account.accountName
elif account.accountProfilePage:
username = account.accountProfilePage.split("/")[-1]
elif account.accountServiceHomepage:
username = account.accountServiceHomepage.split("/")[-1]
else:
return []
api = self.twitter.Api()
tweets = []
for tweet in api.GetUserTimeline(username):
event = ActivityStreamEvent()
event.type = "Twitter"
event.detail = tweet.text
event.link = "http://www.twitter.com/%s/status/%d" % (username, tweet.id)
event.timestamp = self.time.strptime(tweet.created_at, "%a %b %d %H:%M:%S +0000 %Y")
tweets.append(event)
return tweets
| Python |
from foaflib.helpers.basehelper import BaseHelper
from foaflib.utils.activitystreamevent import ActivityStreamEvent
class Delicious(BaseHelper):
def __init__(self):
try:
import feedparser
self.feedparser = feedparser
self._supported = True
except ImportError:
self._supported = False
def _accept_account(self, account):
homepage = account.accountServiceHomepage
return "del.icio.us" in homepage or "delicious.com" in homepage
def _handle_account(self, account):
events = []
username = account.accountName
if not username:
return events
feed_url = "http://feeds.delicious.com/v2/rss/%s?count=15" % username
entries = self.feedparser.parse(feed_url)["entries"]
for entry in entries:
event = ActivityStreamEvent()
event.type = "Del.icio.us"
event.detail = "Bookmarked: %s" % entry.title
event.link = entry.link
event.timestamp = entry.updated_parsed
events.append(event)
return events
| Python |
import foaflib.helpers.blog as blog
from foaflib.helpers.delicious import Delicious
from foaflib.helpers.identica import Identica
from foaflib.helpers.twitter_ import Twitter
_ALL_HELPERS_ = [Delicious]
_ALL_HELPERS_.append(Identica)
_ALL_HELPERS_.append(Twitter)
class ActivityStream(object):
def __init__(self, foafperson):
self.person = foafperson
self.helpers = []
for helper in _ALL_HELPERS_:
self.helpers.append(helper())
def get_latest_events(self, count=10):
events = []
events.extend(blog.get_latest(self.person))
for helper in self.helpers:
events.extend(helper.get_latest(self.person))
events.sort()
events.reverse()
return events[0:count]
| Python |
from hashlib import sha1
from foaflib.utils.basicscutter import BasicScutter
class FileStorageScutter(BasicScutter):
def __init__(self, directory, seed_uris=None):
BasicScutter.__init__(self, seed_uris)
self.directory = directory
def handle_person(self, foafperson):
filename = self.directory + "/" + sha1((foafperson.name or "noname") + (foafperson.homepage or "nohomepage")).hexdigest()
foafperson.save_as_xml_file(filename)
return foafperson
| Python |
class ActivityStreamEvent(object):
def __init__(self):
self.type = ""
self.detail = ""
self.link = ""
self.timestamp = None
def __cmp__(self, other):
return cmp(self.timestamp, other.timestamp)
| Python |
from robotparser import RobotFileParser
from urlparse import urljoin
import rdflib
from foaflib.classes.person import Person
class BasicScutter(object):
def __init__(self, seed_uris=None):
self.useragent = "foaflib"
if seed_uris is None:
seed_uris = []
self.current_list = seed_uris
self.next_list = []
self.seen_uris = []
self.rp = RobotFileParser()
def _can_access(self, uri):
try:
self.rp.set_url(urljoin(uri,"/robots.txt"))
self.rp.read()
return self.rp.can_fetch(self.useragent, uri)
except IOError:
# If uncertain, best to be polite
return False
def handle_person(self, person):
return person
def scutter(self, uri_limit=0, depth_limit=0):
uri_count = 0
depth_count = -1 # (Clearing the seed list doesn't count)
while self.current_list:
if depth_limit and depth_count == depth_limit:
return
for uri in self.current_list:
if uri in self.seen_uris:
continue
if not self._can_access(uri):
continue
try:
p = Person(uri)
self.seen_uris.append(uri)
except:
continue
if not depth_limit or (depth_limit and depth_count < depth_limit - 1):
for friend in p._graph.objects(predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/knows')):
for uri in p._graph.objects(subject=friend, predicate=rdflib.URIRef("http://www.w3.org/2000/01/rdf-schema#seeAlso")):
self.next_list.append(uri)
break
uri_count +=1
yield self.handle_person(p)
if uri_count == uri_limit:
return
self.current_list = self.next_list[:]
self.next_list = []
depth_count +=1
| Python |
import rdflib
class OnlineAccount(object):
def __init__(self, graph=None, node=None):
self.accountServiceHomepage = ""
self.accountName = ""
self.accountProfilePage = ""
if graph and node:
for homepage in graph.objects(subject=node, predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/accountServiceHomepage')):
self.accountServiceHomepage = unicode(homepage)
for name in graph.objects(subject=node, predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/accountName')):
self.accountName = unicode(name)
for profilepage in graph.objects(subject=node, predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/accountProfilePage')):
self.accountProfilePage = unicode(profilepage)
| Python |
import rdflib
from rdflib.Graph import ConjunctiveGraph as Graph
from urllib import urlopen
from foaflib.classes.onlineaccount import OnlineAccount
_SINGLETONS = """gender openid birthday pubkeyAddress""".split()
_BASIC_MULTIS = """mbox mbox_sha1sum jabberID aimChatID icqChatID yahooChatID msnChatID weblog tipjar made holdsAccount""".split()
class Agent(object):
def __init__(self, path=None):
for name in _BASIC_MULTIS:
setattr(self, "_get_%ss" % name, self._make_getter(name))
setattr(Agent, "%ss" % name, property(self._make_property_getter(name)))
setattr(self, "add_%s" % name, self._make_adder(name))
setattr(self, "del_%s" % name, self._make_deler(name))
self._graph = Graph()
if path:
self._graph.parse(path)
for topic in self._graph.objects(predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/primaryTopic')):
self._me = topic
# Things you can only reasonably have one of - gender, birthday, first name, etc. - are termed
# "singletons". Singletion I/O is handled purely through __getattr__ and __setattr__, below.
def __getattr__(self, name):
if name in _SINGLETONS:
for raw in self._graph.objects(subject=self._me, predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/%s' % name)):
return unicode(raw)
return None
raise AttributeError, name
def __setattr__(self, name, value):
if name in _SINGLETONS:
self._graph.remove((self._me, rdflib.URIRef('http://xmlns.com/foaf/0.1/%s' % name), None))
self._graph.add((self._me, rdflib.URIRef('http://xmlns.com/foaf/0.1/%s' % name), value))
else:
object.__setattr__(self, name, value)
# Stuff you might have more than one of - weblogs, accounts, friends, etc. - are handled by a
# combination of the property decorator and add/del methods.
def _make_getter(self, name):
def method():
return [unicode(x) for x in self._graph.objects(subject=self._me, predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/%s' % name))]
return method
def _make_property_getter(self, name):
def method(self):
return [unicode(x) for x in self._graph.objects(subject=self._me, predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/%s' % name))]
return method
def _make_adder(self, name):
def method(value):
self._graph.add((self._me, rdflib.URIRef('http://xmlns.com/foaf/0.1/%s' % name), rdflib.URIRef(value)))
return method
def _make_deler(self, name):
def method(value):
self._graph.remove((self._me, rdflib.URIRef('http://xmlns.com/foaf/0.1/%s' % name), rdflib.URIRef(value)))
return method
def _build_account(self, acct):
if isinstance(acct, rdflib.BNode):
return OnlineAccount(self._graph, acct)
elif isinstance(acct, rdflib.URIRef):
account = OnlineAccount()
account.accountServiceHomepage = unicode(acct)
return account
return OnlineAccount()
def _get_accounts(self):
for raw_account in self._graph.objects(predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/holdsAccount')):
account = self._build_account(raw_account)
if account:
yield account
accounts = property(_get_accounts)
def add_account(self, account):
x = rdflib.BNode()
self._graph.add((x, rdflib.URIRef("http://xmlns.com/foaf/0.1/accountServiceHomepage"), rdflib.URIRef(account.accountServiceHomepage)))
self._graph.add((x, rdflib.URIRef("http://xmlns.com/foaf/0.1/accountName"), rdflib.URIRef(account.accountName)))
if account.accountProfilePage:
self._graph.add((x, rdflib.URIRef("http://xmlns.com/foaf/0.1/accountProfilePage"), rdflib.URIRef(account.accountProfilePage)))
self._graph.add((self._me, rdflib.URIRef("http://xmlns.com/foaf/0.1/holdsAccount"), x))
# Serialisation
def get_xml_string(self):
self._graph.serialize()
def save_as_xml_file(self, filename):
self._graph.serialize(filename)
# Account stuff
| Python |
import rdflib
from rdflib.Graph import ConjunctiveGraph as Graph
from urllib import urlopen
from foaflib.classes.agent import Agent
_SINGLETONS = "title name nick givenname firstName surname family_name homepage geekcode meyersBriggs dnaChecksum plan".split()
_BASIC_MULTIS = "schoolHomepage workplaceHomepage img currentProject pastProject publications isPrimaryTopicOf page made workInfoHomepage interest".split()
class Person(Agent):
def __init__(self, uri=None):
Agent.__init__(self)
for name in _BASIC_MULTIS:
setattr(self, "_get_%ss" % name, self._make_getter(name))
setattr(Person, "%ss" % name, property(self._make_property_getter(name)))
setattr(self, "add_%s" % name, self._make_adder(name))
setattr(self, "del_%s" % name, self._make_deler(name))
self._graph = Graph()
self._error = False
if uri:
self.uri = uri
try:
self._graph.parse(uri)
self._find_me_node()
except:
self._error = True
else:
self.uri = ""
self._setup_profile()
def _setup_profile(self):
x = rdflib.BNode()
self._graph.add((x, rdflib.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), rdflib.URIRef('http://xmlns.com/foaf/0.1/PersonalProfileDocument')))
self._graph.add((x, rdflib.URIRef('http://webns.net/mvcb/generatorAgent'), rdflib.URIRef('http://code.google.com/p/foaflib')))
self._graph.add((x, rdflib.URIRef('http://xmlns.com/foaf/0.1/primaryTopic'), rdflib.URIRef('#me')))
self._graph.add((rdflib.URIRef('#me'), rdflib.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), rdflib.URIRef('http://xmlns.com/foaf/0.1/Person')))
self._me = rdflib.URIRef('#me')
def _get_people(self):
return self._graph.subjects(rdflib.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), rdflib.URIRef('http://xmlns.com/foaf/0.1/Person'))
def _find_me_node(self):
# Check for a PersonalProfileDocument
for doc in self._graph.triples((None, rdflib.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), rdflib.URIRef('http://xmlns.com/foaf/0.1/PersonalProfileDocument'))):
for topic in self._graph.objects(subject=doc, predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/primaryTopic')):
self._me = topic
return
# Check for a single Person
if len(list(self._get_people())) == 1:
for person in self._get_people():
self._me = person
return
# Return someone who isn't known by anyone else in this graph - the best we can do?
for person in self._get_people():
knowers = self._graph.subjects(rdflib.URIRef('http://xmlns.com/foaf/0.1/knows'), person)
if len(list(knowers)) == 0:
self._me = person
return
# Things you can only reasonably have one of - gender, birthday, first name, etc. - are termed
# "singletons". Singletion I/O is handled purely through __getattr__ and __setattr__, below.
def __getattr__(self, name):
if name in _SINGLETONS:
for raw in self._graph.objects(subject=self._me, predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/%s' % name)):
return unicode(raw)
return None
return Agent.__getattr__(self, name)
def __setattr__(self, name, value):
if name in _SINGLETONS:
self._graph.remove((self._me, rdflib.URIRef('http://xmlns.com/foaf/0.1/%s' % name), None))
self._graph.add((self._me, rdflib.URIRef('http://xmlns.com/foaf/0.1/%s' % name), value))
else:
Agent.__setattr__(self, name, value)
def _build_friend(self, raw_friend):
if isinstance(raw_friend, rdflib.URIRef):
return Person(unicode(raw_friend))
elif isinstance(raw_friend, rdflib.BNode):
# If a "seeAlso" gives us the URI of the friend's FOAF profile, use that
for uri in self._graph.objects(subject=raw_friend, predicate=rdflib.URIRef("http://www.w3.org/2000/01/rdf-schema#seeAlso")):
return Person(unicode(uri))
# Otherwise just build a Person up from what we have
f = Person()
for (s,p,o) in self._graph.triples((raw_friend, None, None)):
f._graph.add((f._get_primary_topic(),p,o))
return f
def _get_friends(self):
for raw_friend in self._graph.objects(predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/knows')):
friend = self._build_friend(raw_friend)
if friend:
yield friend
friends = property(_get_friends)
def add_friend(self, friend):
x = rdflib.BNode()
self._graph.add((self._me, rdflib.URIRef('http://xmlns.com/foaf/0.1/knows'), x))
self._graph.add((x, rdflib.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), rdflib.URIRef('http://xmlns.com/foaf/0.1/Person')))
if friend.name:
self._graph.add((x, rdflib.URIRef('http://xmlns.com/foaf/0.1/name'), friend.name))
if friend.homepage:
self._graph.add((x, rdflib.URIRef('http://xmlns.com/foaf/0.1/homepage'), friend.homepage))
for mbox in friend.mboxs:
self._graph.add((x, rdflib.URIRef('http://xmlns.com/foaf/0.1/mbox'), mbox))
for mbox_sha1sum in friend.mbox_sha1sums:
self._graph.add((x, rdflib.URIRef('http://xmlns.com/foaf/0.1/mbox_sha1sum'), mbox_sha1sum))
if friend.uri:
self._graph.add((x, rdflib.URIRef("http://www.w3.org/2000/01/rdf-schema#seeAlso"), friend.uri))
def _build_fast_friend(self, raw_friend):
if isinstance(raw_friend, rdflib.URIRef):
return Person(unicode(raw_friend))
elif isinstance(raw_friend, rdflib.BNode):
f = Person()
for (s,p,o) in self._graph.triples((raw_friend, None, None)):
f._graph.add((f._get_primary_topic(),p,o))
return f
def _get_fast_friends(self):
for raw_friend in self._graph.objects(predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/knows')):
friend = self._build_fast_friend(raw_friend)
if friend:
yield friend
fast_friends = property(_get_fast_friends)
def _build_fastest_friend(self, raw_friend):
if isinstance(raw_friend, rdflib.URIRef):
return None
elif isinstance(raw_friend, rdflib.BNode):
f = Person()
for (s,p,o) in self._graph.triples((raw_friend, None, None)):
f._graph.add((f._get_primary_topic(),p,o))
return f
def _get_fastest_friends(self):
for raw_friend in self._graph.objects(predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/knows')):
friend = self._build_fastest_friend(raw_friend)
if friend:
yield friend
fastest_friends = property(_get_fastest_friends)
# Serialisation
def get_xml_string(self, format="rdf/xml"):
return self._graph.serialize(format=format)
def save_as_xml_file(self, filename, format="rdf/xml"):
self._graph.serialize(filename, format=format)
| Python |
#!/usr/bin/env python
from setuptools import setup
setup(name="foaflib",
version="0.1",
description="Python library for working with FOAF data",
author="Luke Maurits",
author_email="luke@maurits.id.au",
url="http://code.google.com/p/foaflib/",
packages=["foaflib", "foaflib.classes", "foaflib.helpers", "foaflib.utils"],
install_requires=["rdflib"]
)
| Python |
#!/usr/bin/env python
from setuptools import setup
setup(name="foaflib",
version="0.1",
description="Python library for working with FOAF data",
author="Luke Maurits",
author_email="luke@maurits.id.au",
url="http://code.google.com/p/foaflib/",
packages=["foaflib", "foaflib.classes", "foaflib.helpers", "foaflib.utils"],
install_requires=["rdflib"]
)
| Python |
from foaflib.utils.activitystreamevent import ActivityStreamEvent
try:
from urllib import urlopen
from urlparse import urljoin
from BeautifulSoup import BeautifulSoup
from feedparser import parse
_CAN_DO_ = True
except ImportError:
_CAN_DO_ = False
def get_latest(foafprofile):
entries = []
if not _CAN_DO_:
return entries
for blog in foafprofile.weblogs:
u = urlopen(blog)
blogpage = u.read()
u.close()
try:
bs = BeautifulSoup(blogpage)
feeds = bs.findAll("link",{"type":"application/rss+xml"})
for feed in feeds:
try:
feed_url = urljoin(blog, feed["href"])
feedentries = []
for entry in parse(feed_url)["entries"]:
event = ActivityStreamEvent()
event.type = "Blog post"
event.detail = entry["title"]
if "published_parsed" in entry:
event.timestamp = entry["published_parsed"]
if "updated_parsed" in entry:
event.timestamp = entry["updated_parsed"]
feedentries.append(event)
entries.extend(feedentries)
break
except:
continue
except:
continue
return entries
| Python |
from foaflib.utils.activitystreamevent import ActivityStreamEvent
class BaseHelper(object):
def __init__(self):
self._supported = False
def _accept_account(self, onlineaccount):
return False
def _handle_account(self, onlineaccount):
return None
def get_latest(self, foafperson):
if not self._supported:
return []
events = []
for account in foafperson.accounts:
if self._accept_account(account):
account_events = self._handle_account(account)
account_events = filter(lambda x: isinstance(x, ActivityStreamEvent), account_events)
events.extend(account_events)
return events
| Python |
from foaflib.utils.activitystreamevent import ActivityStreamEvent
from foaflib.helpers.basehelper import BaseHelper
class Identica(BaseHelper):
def __init__(self):
BaseHelper.__init__(self)
try:
import feedparser
self.feedparser = feedparser
self._supported = True
except ImportError:
self._supported = False
def _accept_account(self, account):
return "identi.ca" in account.accountServiceHomepage
def _handle_account(self, account):
events = []
username = account.accountName
if not username:
return events
url = "https://identi.ca/api/statuses/user_timeline/%s.atom" % username
try:
feedentries = self.feedparser.parse(url)["entries"]
for entry in feedentries:
event = ActivityStreamEvent()
event.type = "Identi.ca"
event.detail = entry["title"]
event.link = entry["link"]
event.timestamp = entry["published_parsed"]
events.append(event)
except:
pass
return events
| Python |
from foaflib.helpers.basehelper import BaseHelper
from foaflib.utils.activitystreamevent import ActivityStreamEvent
class Twitter(BaseHelper):
def __init__(self):
BaseHelper.__init__(self)
try:
import twitter
self.twitter = twitter
import time
self.time = time
self._supported = True
except ImportError:
self._supported = False
def _accept_account(self, account):
return "twitter.com" in account.accountServiceHomepage
def _handle_account(self, account):
if account.accountName:
username = account.accountName
elif account.accountProfilePage:
username = account.accountProfilePage.split("/")[-1]
elif account.accountServiceHomepage:
username = account.accountServiceHomepage.split("/")[-1]
else:
return []
api = self.twitter.Api()
tweets = []
for tweet in api.GetUserTimeline(username):
event = ActivityStreamEvent()
event.type = "Twitter"
event.detail = tweet.text
event.link = "http://www.twitter.com/%s/status/%d" % (username, tweet.id)
event.timestamp = self.time.strptime(tweet.created_at, "%a %b %d %H:%M:%S +0000 %Y")
tweets.append(event)
return tweets
| Python |
from foaflib.helpers.basehelper import BaseHelper
from foaflib.utils.activitystreamevent import ActivityStreamEvent
class Delicious(BaseHelper):
def __init__(self):
try:
import feedparser
self.feedparser = feedparser
self._supported = True
except ImportError:
self._supported = False
def _accept_account(self, account):
homepage = account.accountServiceHomepage
return "del.icio.us" in homepage or "delicious.com" in homepage
def _handle_account(self, account):
events = []
username = account.accountName
if not username:
return events
feed_url = "http://feeds.delicious.com/v2/rss/%s?count=15" % username
entries = self.feedparser.parse(feed_url)["entries"]
for entry in entries:
event = ActivityStreamEvent()
event.type = "Del.icio.us"
event.detail = "Bookmarked: %s" % entry.title
event.link = entry.link
event.timestamp = entry.updated_parsed
events.append(event)
return events
| Python |
import foaflib.helpers.blog as blog
from foaflib.helpers.delicious import Delicious
from foaflib.helpers.identica import Identica
from foaflib.helpers.twitter_ import Twitter
try:
from feedformatter import Feed
_CAN_DO_FEEDS_ = True
except ImportError:
_CAN_DO_FEEDS_ = False
_ALL_HELPERS_ = [Delicious]
_ALL_HELPERS_.append(Identica)
_ALL_HELPERS_.append(Twitter)
class ActivityStream(object):
def __init__(self, foafperson):
self.person = foafperson
self.helpers = []
for helper in _ALL_HELPERS_:
self.helpers.append(helper())
def get_latest_events(self, count=10):
events = []
events.extend(blog.get_latest(self.person))
for helper in self.helpers:
events.extend(helper.get_latest(self.person))
events.sort()
events.reverse()
return events[0:count]
def build_feed(self):
if not _CAN_DO_FEEDS_:
return None
feed = Feed()
feed.feed["title"] = self.person.name + "'s Activity Stream"
feed.feed["description"] = self.person.name + "'s Activity Stream"
feed.feed["link"] = self.person.uri
feed.feed["author"] = self.person.name
for event in self.get_latest_events():
item = {}
item["title"] = event.type + " - " + event.detail
item["pubDate"] = event.timestamp
item["link"] = event.link
item["guid"] = event.link
feed.items.append(item)
return feed
| Python |
from hashlib import sha1
from foaflib.utils.basicscutter import BasicScutter
class FileStorageScutter(BasicScutter):
def __init__(self, directory, seed_uris=None):
BasicScutter.__init__(self, seed_uris)
self.directory = directory
def handle_person(self, foafperson):
filename = self.directory + "/" + sha1((foafperson.name or "noname") + (foafperson.homepage or "nohomepage")).hexdigest()
foafperson.save_as_xml_file(filename)
return foafperson
| Python |
class ActivityStreamEvent(object):
def __init__(self):
self.type = ""
self.detail = ""
self.link = ""
self.timestamp = None
def __cmp__(self, other):
return cmp(self.timestamp, other.timestamp)
| Python |
from robotparser import RobotFileParser
from urlparse import urljoin
import rdflib
from foaflib.classes.person import Person
class BasicScutter(object):
def __init__(self, seed_uris=None):
self.useragent = "foaflib"
if seed_uris is None:
seed_uris = []
self.current_list = seed_uris
self.next_list = []
self.seen_uris = []
self.rp = RobotFileParser()
def _can_access(self, uri):
try:
self.rp.set_url(urljoin(uri,"/robots.txt"))
self.rp.read()
return self.rp.can_fetch(self.useragent, uri)
except IOError:
# If uncertain, best to be polite
return False
def handle_person(self, person):
return person
def scutter(self, uri_limit=0, depth_limit=0):
uri_count = 0
depth_count = -1 # (Clearing the seed list doesn't count)
while self.current_list:
if depth_limit and depth_count == depth_limit:
return
for uri in self.current_list:
if uri in self.seen_uris:
continue
if not self._can_access(uri):
continue
try:
p = Person(uri)
self.seen_uris.append(uri)
except:
continue
if not depth_limit or (depth_limit and depth_count < depth_limit - 1):
for friend in p._graph.objects(predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/knows')):
for uri in p._graph.objects(subject=friend, predicate=rdflib.URIRef("http://www.w3.org/2000/01/rdf-schema#seeAlso")):
self.next_list.append(uri)
break
uri_count +=1
yield self.handle_person(p)
if uri_count == uri_limit:
return
self.current_list = self.next_list[:]
self.next_list = []
depth_count +=1
| Python |
import rdflib
class OnlineAccount(object):
def __init__(self, graph=None, node=None):
self.accountServiceHomepage = ""
self.accountName = ""
self.accountProfilePage = ""
if graph and node:
for homepage in graph.objects(subject=node, predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/accountServiceHomepage')):
self.accountServiceHomepage = unicode(homepage)
for name in graph.objects(subject=node, predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/accountName')):
self.accountName = unicode(name)
for profilepage in graph.objects(subject=node, predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/accountProfilePage')):
self.accountProfilePage = unicode(profilepage)
| Python |
import rdflib
from rdflib.Graph import ConjunctiveGraph as Graph
from urllib import urlopen
from foaflib.classes.onlineaccount import OnlineAccount
_SINGLETONS = """gender openid birthday pubkeyAddress""".split()
_BASIC_MULTIS = """mbox mbox_sha1sum jabberID aimChatID icqChatID yahooChatID msnChatID weblog tipjar made holdsAccount""".split()
class Agent(object):
def __init__(self, path=None):
for name in _BASIC_MULTIS:
setattr(self, "_get_%ss" % name, self._make_getter(name))
setattr(Agent, "%ss" % name, property(self._make_property_getter(name)))
setattr(self, "add_%s" % name, self._make_adder(name))
setattr(self, "del_%s" % name, self._make_deler(name))
self._graph = Graph()
if path:
self._graph.parse(path)
for topic in self._graph.objects(predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/primaryTopic')):
self._me = topic
# Things you can only reasonably have one of - gender, birthday, first name, etc. - are termed
# "singletons". Singletion I/O is handled purely through __getattr__ and __setattr__, below.
def __getattr__(self, name):
if name in _SINGLETONS:
for raw in self._graph.objects(subject=self._me, predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/%s' % name)):
return unicode(raw)
return None
raise AttributeError, name
def __setattr__(self, name, value):
if name in _SINGLETONS:
self._graph.remove((self._me, rdflib.URIRef('http://xmlns.com/foaf/0.1/%s' % name), None))
self._graph.add((self._me, rdflib.URIRef('http://xmlns.com/foaf/0.1/%s' % name), value))
else:
object.__setattr__(self, name, value)
# Stuff you might have more than one of - weblogs, accounts, friends, etc. - are handled by a
# combination of the property decorator and add/del methods.
def _make_getter(self, name):
def method():
return [unicode(x) for x in self._graph.objects(subject=self._me, predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/%s' % name))]
return method
def _make_property_getter(self, name):
def method(self):
return [unicode(x) for x in self._graph.objects(subject=self._me, predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/%s' % name))]
return method
def _make_adder(self, name):
def method(value):
self._graph.add((self._me, rdflib.URIRef('http://xmlns.com/foaf/0.1/%s' % name), rdflib.URIRef(value)))
return method
def _make_deler(self, name):
def method(value):
self._graph.remove((self._me, rdflib.URIRef('http://xmlns.com/foaf/0.1/%s' % name), rdflib.URIRef(value)))
return method
def _build_account(self, acct):
if isinstance(acct, rdflib.BNode):
return OnlineAccount(self._graph, acct)
elif isinstance(acct, rdflib.URIRef):
account = OnlineAccount()
account.accountServiceHomepage = unicode(acct)
return account
return OnlineAccount()
def _get_accounts(self):
for raw_account in self._graph.objects(predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/holdsAccount')):
account = self._build_account(raw_account)
if account:
yield account
accounts = property(_get_accounts)
def add_account(self, account):
x = rdflib.BNode()
self._graph.add((x, rdflib.URIRef("http://xmlns.com/foaf/0.1/accountServiceHomepage"), rdflib.URIRef(account.accountServiceHomepage)))
self._graph.add((x, rdflib.URIRef("http://xmlns.com/foaf/0.1/accountName"), rdflib.URIRef(account.accountName)))
if account.accountProfilePage:
self._graph.add((x, rdflib.URIRef("http://xmlns.com/foaf/0.1/accountProfilePage"), rdflib.URIRef(account.accountProfilePage)))
self._graph.add((self._me, rdflib.URIRef("http://xmlns.com/foaf/0.1/holdsAccount"), x))
# Serialisation
def get_xml_string(self):
self._graph.serialize()
def save_as_xml_file(self, filename):
self._graph.serialize(filename)
# Account stuff
| Python |
import rdflib
from rdflib.Graph import ConjunctiveGraph as Graph
from urllib import urlopen
from foaflib.classes.agent import Agent
_SINGLETONS = "title name nick givenname firstName surname family_name homepage geekcode meyersBriggs dnaChecksum plan".split()
_BASIC_MULTIS = "schoolHomepage workplaceHomepage img currentProject pastProject publications isPrimaryTopicOf page made workInfoHomepage interest".split()
class Person(Agent):
def __init__(self, uri=None):
Agent.__init__(self)
for name in _BASIC_MULTIS:
setattr(self, "_get_%ss" % name, self._make_getter(name))
setattr(Person, "%ss" % name, property(self._make_property_getter(name)))
setattr(self, "add_%s" % name, self._make_adder(name))
setattr(self, "del_%s" % name, self._make_deler(name))
self._graph = Graph()
self._error = False
if uri:
self.uri = uri
try:
self._graph.parse(uri)
self._find_me_node()
except:
self._error = True
else:
self.uri = ""
self._setup_profile()
def _setup_profile(self):
x = rdflib.BNode()
self._graph.add((x, rdflib.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), rdflib.URIRef('http://xmlns.com/foaf/0.1/PersonalProfileDocument')))
self._graph.add((x, rdflib.URIRef('http://webns.net/mvcb/generatorAgent'), rdflib.URIRef('http://code.google.com/p/foaflib')))
self._graph.add((x, rdflib.URIRef('http://xmlns.com/foaf/0.1/primaryTopic'), rdflib.URIRef('#me')))
self._graph.add((rdflib.URIRef('#me'), rdflib.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), rdflib.URIRef('http://xmlns.com/foaf/0.1/Person')))
self._me = rdflib.URIRef('#me')
def _get_people(self):
return self._graph.subjects(rdflib.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), rdflib.URIRef('http://xmlns.com/foaf/0.1/Person'))
def _find_me_node(self):
# Check for a PersonalProfileDocument
for doc in self._graph.subjects(predicate=rdflib.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), object=rdflib.URIRef('http://xmlns.com/foaf/0.1/PersonalProfileDocument')):
for topic in self._graph.objects(subject=doc, predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/primaryTopic')):
self._me = topic
return
# Check for a single Person
if len(list(self._get_people())) == 1:
for person in self._get_people():
self._me = person
return
# Return someone who isn't known by anyone else in this graph - the best we can do?
for person in self._get_people():
knowers = self._graph.subjects(rdflib.URIRef('http://xmlns.com/foaf/0.1/knows'), person)
if len(list(knowers)) == 0:
self._me = person
return
# Things you can only reasonably have one of - gender, birthday, first name, etc. - are termed
# "singletons". Singletion I/O is handled purely through __getattr__ and __setattr__, below.
def __getattr__(self, name):
if name in _SINGLETONS:
for raw in self._graph.objects(subject=self._me, predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/%s' % name)):
return unicode(raw)
return None
return Agent.__getattr__(self, name)
def __setattr__(self, name, value):
if name in _SINGLETONS:
self._graph.remove((self._me, rdflib.URIRef('http://xmlns.com/foaf/0.1/%s' % name), None))
self._graph.add((self._me, rdflib.URIRef('http://xmlns.com/foaf/0.1/%s' % name), value))
else:
Agent.__setattr__(self, name, value)
def _build_friend(self, raw_friend):
if isinstance(raw_friend, rdflib.URIRef):
return Person(unicode(raw_friend))
elif isinstance(raw_friend, rdflib.BNode):
# If a "seeAlso" gives us the URI of the friend's FOAF profile, use that
for uri in self._graph.objects(subject=raw_friend, predicate=rdflib.URIRef("http://www.w3.org/2000/01/rdf-schema#seeAlso")):
return Person(unicode(uri))
# Otherwise just build a Person up from what we have
f = Person()
for (s,p,o) in self._graph.triples((raw_friend, None, None)):
f._graph.add((f._get_primary_topic(),p,o))
return f
def _get_friends(self):
for raw_friend in self._graph.objects(predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/knows')):
friend = self._build_friend(raw_friend)
if friend:
yield friend
friends = property(_get_friends)
def add_friend(self, friend):
x = rdflib.BNode()
self._graph.add((self._me, rdflib.URIRef('http://xmlns.com/foaf/0.1/knows'), x))
self._graph.add((x, rdflib.URIRef('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), rdflib.URIRef('http://xmlns.com/foaf/0.1/Person')))
if friend.name:
self._graph.add((x, rdflib.URIRef('http://xmlns.com/foaf/0.1/name'), friend.name))
if friend.homepage:
self._graph.add((x, rdflib.URIRef('http://xmlns.com/foaf/0.1/homepage'), friend.homepage))
for mbox in friend.mboxs:
self._graph.add((x, rdflib.URIRef('http://xmlns.com/foaf/0.1/mbox'), mbox))
for mbox_sha1sum in friend.mbox_sha1sums:
self._graph.add((x, rdflib.URIRef('http://xmlns.com/foaf/0.1/mbox_sha1sum'), mbox_sha1sum))
if friend.uri:
self._graph.add((x, rdflib.URIRef("http://www.w3.org/2000/01/rdf-schema#seeAlso"), friend.uri))
def _build_fast_friend(self, raw_friend):
if isinstance(raw_friend, rdflib.URIRef):
return Person(unicode(raw_friend))
elif isinstance(raw_friend, rdflib.BNode):
f = Person()
for (s,p,o) in self._graph.triples((raw_friend, None, None)):
f._graph.add((f._get_primary_topic(),p,o))
return f
def _get_fast_friends(self):
for raw_friend in self._graph.objects(predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/knows')):
friend = self._build_fast_friend(raw_friend)
if friend:
yield friend
fast_friends = property(_get_fast_friends)
def _build_fastest_friend(self, raw_friend):
if isinstance(raw_friend, rdflib.URIRef):
return None
elif isinstance(raw_friend, rdflib.BNode):
f = Person()
for (s,p,o) in self._graph.triples((raw_friend, None, None)):
f._graph.add((f._get_primary_topic(),p,o))
return f
def _get_fastest_friends(self):
for raw_friend in self._graph.objects(predicate=rdflib.URIRef('http://xmlns.com/foaf/0.1/knows')):
friend = self._build_fastest_friend(raw_friend)
if friend:
yield friend
fastest_friends = property(_get_fastest_friends)
# Serialisation
def get_xml_string(self, format="rdf/xml"):
return self._graph.serialize(format=format)
def save_as_xml_file(self, filename, format="rdf/xml"):
self._graph.serialize(filename, format=format)
| Python |
#!/usr/bin/env python
from setuptools import setup
setup(name="foaflib",
version="0.1",
description="Python library for working with FOAF data",
author="Luke Maurits",
author_email="luke@maurits.id.au",
url="http://code.google.com/p/foaflib/",
packages=["foaflib", "foaflib.classes", "foaflib.helpers", "foaflib.utils"],
install_requires=["rdflib"]
)
| Python |
#!/usr/bin/env python
#coding=utf-8
from xml.dom import minidom
import urllib
import httplib
import re
import os
import time
import sys
import hashlib
fsock = open('error.log', 'a')
fsock.write(time.strftime('%Y-%m-%d %X',time.localtime())+"\n")
fsock.flush()
sys.stderr = fsock
pid = open('pid','w')
pid.write(str(os.getpid()))
pid.close()
foobar2000_path = "d:/foobar2000/foobar2000"
input_url = sys.argv[1]
playlist_url = urllib.urlopen(input_url)
xmldom = minidom.parse(playlist_url)
playlist_url.close()
songs = xmldom.getElementsByTagName('song')
length = len(songs)
default_key = "c51181b7f9bfce1ac742ed8b4a1ae4ed"
def google_download(id):
song_url = "http://www.google.cn/music/top100/musicdownload?id="+id
try:
song_pagedata = urllib.urlopen(song_url).read()
except Exception:
return False
match_url = re.search("(?<=url\?q=).*?(?=&ct)",song_pagedata)
if match_url:
download_url = urllib.unquote(match_url.group())
return download_url
else:
return False
def google_stream(id):
sig = hashlib.md5(default_key+id)
sig = sig.hexdigest()
xml_url = "http://www.google.cn/music/songstreaming?id="+id+"&sig="+sig+"&output=xml"
try:
xml_url = urllib.urlopen(xml_url)
xmldom_stream = minidom.parse(xml_url)
xml_url.close()
except Exception:
return False
download_url = xmldom_stream.getElementsByTagName('songUrl')[0].firstChild.data
return download_url
def updateplaylist():
playlist = open("playlist/google.m3u","w")
song_iter = iter(songs)
retry = False
trytimes = 0
start = 0
while True:
if retry != True or trytimes > 3:
trytimes = 0
try:
song = song_iter.next()
percent = open("percent.txt","w")
start += 1
percent.write(str(start)+'/'+str(length))
percent.close()
except StopIteration:
break
except Exception:
pass
id = song.firstChild.firstChild.data
download_url = google_stream(id)
if download_url:
playlist.write(download_url+"\n")
retry = False
else:
trytimes += 1
if trytimes > 3:
log_file = open('google_log.txt','a')
log_file.write(time.strftime('%Y-%m-%d %X',time.localtime())+"\n")
log_data = song.childNodes[1].firstChild.data+": "+id+"\n"
log_file.write(log_data.encode('utf-8'))
log_file.close()
retry = True
time.sleep(1)
try:
percent = open("percent.txt","w")
percent.write("1")
percent.close()
playlist.close()
except Exception:
pass
time.sleep(5)
if os.path.exists('percent.txt'):
os.remove('percent.txt')
updateplaylist()
os.popen('start '+foobar2000_path+' /playlist:"Google"','r')
time.sleep(6)
os.popen('start '+foobar2000_path+' /play "playlist/empty.fpl"','r')
time.sleep(4)
if os.path.exists("playlist/temp.fpl"):
os.popen('start '+foobar2000_path+' /add "playlist/temp.fpl"','r')
os.popen('start '+foobar2000_path+' /add "playlist/google.m3u"','r')
time.sleep(2)
os.popen('start '+foobar2000_path+' /play','r')
os.popen('start '+foobar2000_path+' /hide','r')
while True:
time.sleep(10000)
updateplaylist()
os.popen('start '+foobar2000_path+' /playlist:"Google"','r')
time.sleep(4)
os.popen('start '+foobar2000_path+' /play "playlist/empty.fpl"','r')
time.sleep(4)
if os.path.exists("playlist/temp.fpl"):
os.popen('start '+foobar2000_path+' /add "playlist/temp.fpl"','r')
os.popen('start '+foobar2000_path+' /add "playlist/google.m3u"','r')
time.sleep(2)
os.popen('start '+foobar2000_path+' /play','r')
time.sleep(1)
| Python |
#!/usr/bin/env python
#coding=utf-8
from xml.dom import minidom
import urllib
import httplib
import re
import os
import time
import sys
import hashlib
fsock = open('error.log', 'a')
fsock.write(time.strftime('%Y-%m-%d %X',time.localtime())+"\n")
fsock.flush()
sys.stderr = fsock
pid = open('pid','w')
pid.write(str(os.getpid()))
pid.close()
foobar2000_path = "d:/foobar2000/foobar2000"
input_url = sys.argv[1]
playlist_url = urllib.urlopen(input_url)
xmldom = minidom.parse(playlist_url)
playlist_url.close()
songs = xmldom.getElementsByTagName('song')
length = len(songs)
default_key = "c51181b7f9bfce1ac742ed8b4a1ae4ed"
def google_download(id):
song_url = "http://www.google.cn/music/top100/musicdownload?id="+id
try:
song_pagedata = urllib.urlopen(song_url).read()
except Exception:
return False
match_url = re.search("(?<=url\?q=).*?(?=&ct)",song_pagedata)
if match_url:
download_url = urllib.unquote(match_url.group())
return download_url
else:
return False
def google_stream(id):
sig = hashlib.md5(default_key+id)
sig = sig.hexdigest()
xml_url = "http://www.google.cn/music/songstreaming?id="+id+"&sig="+sig+"&output=xml"
try:
xml_url = urllib.urlopen(xml_url)
xmldom_stream = minidom.parse(xml_url)
xml_url.close()
except Exception:
return False
download_url = xmldom_stream.getElementsByTagName('songUrl')[0].firstChild.data
return download_url
def updateplaylist():
playlist = open("playlist/google.m3u","w")
song_iter = iter(songs)
retry = False
trytimes = 0
start = 0
while True:
if retry != True or trytimes > 3:
trytimes = 0
try:
song = song_iter.next()
percent = open("percent.txt","w")
start += 1
percent.write(str(start)+'/'+str(length))
percent.close()
except StopIteration:
break
except Exception:
pass
id = song.firstChild.firstChild.data
download_url = google_stream(id)
if download_url:
playlist.write(download_url+"\n")
retry = False
else:
trytimes += 1
if trytimes > 3:
log_file = open('google_log.txt','a')
log_file.write(time.strftime('%Y-%m-%d %X',time.localtime())+"\n")
log_data = song.childNodes[1].firstChild.data+": "+id+"\n"
log_file.write(log_data.encode('utf-8'))
log_file.close()
retry = True
time.sleep(1)
try:
percent = open("percent.txt","w")
percent.write("1")
percent.close()
playlist.close()
except Exception:
pass
time.sleep(5)
if os.path.exists('percent.txt'):
os.remove('percent.txt')
updateplaylist()
os.popen('start '+foobar2000_path+' /playlist:"Google"','r')
time.sleep(6)
os.popen('start '+foobar2000_path+' /play "playlist/empty.fpl"','r')
time.sleep(4)
if os.path.exists("playlist/temp.fpl"):
os.popen('start '+foobar2000_path+' /add "playlist/temp.fpl"','r')
os.popen('start '+foobar2000_path+' /add "playlist/google.m3u"','r')
time.sleep(2)
os.popen('start '+foobar2000_path+' /play','r')
os.popen('start '+foobar2000_path+' /hide','r')
while True:
time.sleep(10000)
updateplaylist()
os.popen('start '+foobar2000_path+' /playlist:"Google"','r')
time.sleep(4)
os.popen('start '+foobar2000_path+' /play "playlist/empty.fpl"','r')
time.sleep(4)
if os.path.exists("playlist/temp.fpl"):
os.popen('start '+foobar2000_path+' /add "playlist/temp.fpl"','r')
os.popen('start '+foobar2000_path+' /add "playlist/google.m3u"','r')
time.sleep(2)
os.popen('start '+foobar2000_path+' /play','r')
time.sleep(1)
| Python |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:
import subprocess
import os
import sys
from webbrowser import _iscommand as is_command
import gtk
import mimetypes, mimetools
import config
import locale
import ctypes
try: import i18n
except: from gettext import gettext as _
_browser = ''
def open_webbrowser(uri):
'''open a URI in the registered default application
'''
## for proxychains
os.environ['LD_PRELOAD'] = ' '.join(
[ ld for ld in os.environ.get('LD_PRELOAD', '').split(' ') if 'libproxychains.so' not in ld ]
)
browser = 'xdg-open'
if sys.platform[:3] == "win":
browser = 'start'
subprocess.Popen([browser, uri])
def webkit_set_proxy_uri(uri):
if uri and '://' not in uri:
uri = 'https://' + uri
try:
if os.name == 'nt':
libgobject = ctypes.CDLL('libgobject-2.0-0.dll')
libsoup = ctypes.CDLL('libsoup-2.4-1.dll')
libwebkit = ctypes.CDLL('libwebkit-1.0-2.dll')
else:
libgobject = ctypes.CDLL('libgobject-2.0.so.0')
libsoup = ctypes.CDLL('libsoup-2.4.so.1')
try:
libwebkit = ctypes.CDLL('libwebkitgtk-1.0.so.0')
except:
libwebkit = ctypes.CDLL('libwebkit-1.0.so.2')
pass
proxy_uri = libsoup.soup_uri_new(str(uri)) if uri else 0
session = libwebkit.webkit_get_default_session()
libgobject.g_object_set(session, "proxy-uri", proxy_uri, None)
if proxy_uri:
libsoup.soup_uri_free(proxy_uri)
libgobject.g_object_set(session, "max-conns", 20, None)
libgobject.g_object_set(session, "max-conns-per-host", 5, None)
return 0
except:
exctype, value = sys.exc_info()[:2]
print 'error: webkit_set_proxy_uri: (%s, %s)' % (exctype,value)
return 1
def open_file_chooser_dialog():
sel_file = None
fc_dlg = gtk.FileChooserDialog(title='Open ... '
, parent=None
, action=gtk.FILE_CHOOSER_ACTION_OPEN
, buttons=(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN,gtk.RESPONSE_OK))
fc_dlg.set_default_response(gtk.RESPONSE_OK)
resp = fc_dlg.run()
if resp == gtk.RESPONSE_OK:
sel_file = fc_dlg.get_filename()
fc_dlg.destroy()
gtk.gdk.threads_leave()
return sel_file
def encode_multipart_formdata(fields, files):
BOUNDARY = mimetools.choose_boundary()
CRLF = '\r\n'
L = []
total_size = 0
L = []
for key, value in fields.items():
key, value = key.encode('utf8'), value.encode('utf8')
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="%s"' % key)
L.append('')
L.append(value)
for pair in files:
key, filename = pair[0].encode('utf8'), pair[1].encode('utf8')
L.append('--' + BOUNDARY)
L.append('Content-Disposition: form-data; name="%s"; filename="%s"' %
(key, 'hotot.png'));
L.append('Content-Type: %s' % get_content_type(filename))
L.append('')
L.append(file(filename).read())
total_size += os.path.getsize(filename)
L.append('--' + BOUNDARY + '--')
L.append('')
body = CRLF.join(L)
headers = {'content-type':'multipart/form-data; boundary=%s' % BOUNDARY
, 'content-length': str(len(body))};
return headers, body
def get_content_type(filename):
return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
def get_ui_object(name):
for base in config.DATA_DIRS:
fullpath = os.path.join(base, name)
if os.path.exists(fullpath):
return fullpath
def get_extra_exts():
import glob
exts = []
files = glob.glob(os.path.join(config.CONF_DIR, config.EXT_DIR_NAME) + '/*')
ext_dirs = filter(lambda x: os.path.isdir(x), files)
for dir in ext_dirs:
ext_js = os.path.join(dir, 'entry.js')
if os.path.exists(ext_js):
exts.append('file://%s' % ext_js)
return exts
def get_extra_fonts():
font_list = [ff.get_name() for ff in
gtk.gdk.pango_context_get().list_families()]
font_list.sort()
for font in font_list:
try:
font.decode('ascii')
except:
font_list.remove(font)
font_list.insert(0, font)
return font_list
def get_locale():
lang, encode = locale.getdefaultlocale()
return lang
| Python |
#!/usr/bin/env python
# -*- coding:utf8 -*-
import json
import config
import time
import base64
import urllib, urllib2
import gtk
import threading
import gobject
import utils
import hotot
import os
import sys
import subprocess
try: import i18n
except: from gettext import gettext as _
reload(sys)
sys.setdefaultencoding('utf8')
USE_GTKNOTIFICATION_IN_NATIVE_PLATFORM = True
## Disable GtkNotification on Gnome3
screen = gtk.gdk.screen_get_default()
window_manager_name = screen.get_window_manager_name().lower() if screen else ''
if 'mutter' in window_manager_name:
USE_GTKNOTIFICATION_IN_NATIVE_PLATFORM = False
if USE_GTKNOTIFICATION_IN_NATIVE_PLATFORM:
import gtknotification
class Notification(object):
def do_notify(self, summary, body, icon_file = None):
if (icon_file == None or not os.path.isfile(icon_file)):
icon_file = utils.get_ui_object(os.path.join('image','ic64_hotot.png'));
icon_file = 'file://' + icon_file
title = _("Hotot Notification")
text = summary + '\n' + body
gobject.idle_add(gtknotification.gtknotification, title, text, icon_file)
update = do_notify
show = str
notify = Notification()
else:
import pynotify
pynotify.init(_("Hotot Notification"))
notify = pynotify.Notification('Init', '')
webv = None
app = None
http_code_msg_table = {
404: 'The URL you request does not exist. Please check your API Base/OAuth Base/Search Base.'
, 401: 'Server cannot authenticate you. Please check your username/password and API base.'
, 500: 'Server is broken. Please try again later.'
, 502: 'Server is down or being upgraded. Please try again later.'
, 503: 'Server is overcapacity. Please try again later.'
}
def init_notify():
if USE_GTKNOTIFICATION_IN_NATIVE_PLATFORM:
return
notify.set_icon_from_pixbuf(
gtk.gdk.pixbuf_new_from_file(
utils.get_ui_object(os.path.join('image','ic64_hotot.png'))))
notify.set_timeout(5000)
def do_notify(summary, body, icon_file = None):
if USE_GTKNOTIFICATION_IN_NATIVE_PLATFORM:
return notify.do_notify(summary, body, icon_file)
n = pynotify.Notification(summary, body)
if (icon_file == None or not os.path.isfile(icon_file)):
icon_file = utils.get_ui_object(os.path.join('image','ic64_hotot.png'));
n.set_icon_from_pixbuf(gtk.gdk.pixbuf_new_from_file(icon_file))
n.set_timeout(5000)
n.show()
def crack_hotot(uri):
params = uri.split('/')
try:
if params[0] == 'system':
crack_system(params)
elif params[0] == 'action':
crack_action(params)
elif params[0] == 'request':
raw_json = urllib.unquote(params[1])
req_params = dict([(k.encode('utf8'), v)
for k, v in json.loads(raw_json).items()])
crack_request(req_params)
except Exception, e:
import traceback
print "Exception:"
traceback.print_exc(file=sys.stdout)
def crack_action(params):
if params[1] == 'search':
load_search(params[2])
elif params[1] == 'choose_file':
callback = params[2]
file_path = utils.open_file_chooser_dialog()
webv.execute_script('%s("%s")' % (callback, file_path))
elif params[1] == 'save_avatar':
img_uri = urllib.unquote(params[2])
avatar_file = urllib.unquote(params[3])
avatar_path = os.path.join(config.AVATAR_CACHE_DIR, avatar_file)
if not (os.path.exists(avatar_path) and avatar_file.endswith(img_uri[img_uri.rfind('/')+1:])):
print 'Download:', img_uri , 'To' , avatar_path
th = threading.Thread(
target = save_file_proc,
args=(img_uri, avatar_path))
th.start()
elif params[1] == 'log':
print '\033[1;31;40m[%s]\033[0m %s' % (urllib.unquote(params[2]) ,urllib.unquote(params[3]))
elif params[1] == 'paste_clipboard_text':
webv.paste_clipboard();
elif params[1] == 'set_clipboard_text':
clipboard = gtk.clipboard_get()
text = list(params)
del text[0:2]
clipboard.set_text('/'.join(text))
def crack_system(params):
if params[1] == 'notify':
type = urllib.unquote(params[2])
summary = urllib.unquote(params[3])
body = urllib.unquote(params[4])
if type == 'content':
try:
avatar_file = os.path.join(config.AVATAR_CACHE_DIR, urllib.unquote(params[5]))
except:
avatar_file = None
do_notify(summary, body, avatar_file)
elif type == 'count':
notify.update(summary, body)
notify.show()
elif params[1] == 'load_settings':
settings = json.loads(urllib.unquote(params[2]))
config.load_settings(settings)
app.apply_settings()
elif params[1] == 'sign_in':
app.on_sign_in()
elif params[1] == 'sign_out':
app.on_sign_out()
elif params[1] == 'quit':
app.quit()
def crack_request(req_params):
args = ( req_params['uuid']
, req_params['method']
, req_params['url']
, req_params['params']
, req_params['headers']
, req_params['files'])
th = threading.Thread(target = request, args=args)
th.start()
def save_file_proc(uri, save_path):
if (not os.path.isfile(save_path)):
try:
avatar = open(save_path, "wb")
avatar.write(_get(uri, req_timeout=5))
avatar.close()
except:
import traceback
print "Exception:"
traceback.print_exc(file=sys.stdout)
os.unlink(save_path)
def execute_script(scripts):
return webv.execute_script(scripts)
def update_status(text):
webv.execute_script('''
ui.StatusBox.update_status('%s');
''' % text);
def load_search(query):
webv.execute_script('''
ui.Main.reset_search_page('%s');
$('#search_tweet_block > ul').html('');
ui.Notification.set(_("Loading Search result %s ...")).show();
daemon.update_search();
''' % (query, query));
def set_style_scheme():
style = app.window.get_style()
base, fg, bg, text = style.base, style.fg, style.bg, style.text
webv.execute_script('''
$('#header').css('background', '%s');
''' % str(bg[gtk.STATE_NORMAL]));
def get_prefs(name):
return config.settings[name]
def set_prefs(name, value):
config.settings[name] = value
def request(uuid, method, url, params={}, headers={},files=[],additions=''):
scripts = ''
try:
if (method == 'POST'):
result = _post(url, params, headers, files, additions)
else:
result = _get(url, params, headers)
except urllib2.HTTPError, e:
msg = 'Unknown Errors ... '
if http_code_msg_table.has_key(e.getcode()):
msg = http_code_msg_table[e.getcode()]
tech_info = 'HTTP Code: %s\\nURL: %s\\nDetails: %s' % (e.getcode(), e.geturl(), str(e))
content = '<p>%s</p><h3>- Technological Info -</h3><div class="dlg_group"><pre>%s</pre></div>' % (msg, tech_info)
scripts = '''
widget.DialogManager.alert('%s', '%s');
lib.network.error_task_table['%s']('');
''' % ('Ooops, an Error occurred!', content, uuid);
except urllib2.URLError, e:
content = '<p><label>Error Code:</label>%s<br/><label>Reason:</label> %s, %s<br/></p>' % (e.errno, e.reason, e.strerror)
scripts = '''
widget.DialogManager.alert('%s', '%s');
lib.network.error_task_table['%s']('');
''' % ('Ooops, an Error occurred!', content, uuid);
else:
if uuid != None:
if result[0] != '{' and result[0] != '[':
scripts = '''lib.network.success_task_table['%s']('%s');
''' % (uuid, result)
else:
scripts = '''lib.network.success_task_table['%s'](%s);
''' % (uuid, result)
scripts += '''delete lib.network.success_task_table['%s'];
delete lib.network.error_task_table['%s'];
''' % (uuid, uuid);
gobject.idle_add(webv.execute_script, scripts)
def _get(url, params={}, req_headers={}, req_timeout=None):
urlopen = urllib2.urlopen
if get_prefs('use_http_proxy'):
proxy_support = urllib2.ProxyHandler(
{"http" : get_prefs('http_proxy_host') +':'+str(get_prefs('http_proxy_port'))})
urlopen = urllib2.build_opener(proxy_support).open
request = urllib2.Request(url, headers=req_headers)
ret = urlopen(request, timeout=req_timeout).read()
return ret
def _post(url, params={}, req_headers={}, files=[], additions='', req_timeout=None):
if files != []:
files_headers, files_data = utils.encode_multipart_formdata(params, files)
params ={}
req_headers.update(files_headers)
additions += files_data
urlopen = urllib2.urlopen
if get_prefs('use_http_proxy'):
proxy_support = urllib2.ProxyHandler(
{"http" : get_prefs('http_proxy_host') +':'+str(get_prefs('http_proxy_port'))})
urlopen = urllib2.build_opener(proxy_support).open
params = dict([(k.encode('utf8')
, v.encode('utf8') if type(v)==unicode else v)
for k, v in params.items()])
request = urllib2.Request(url,
urlencode(params) + additions, headers=req_headers);
ret = urlopen(request, timeout=req_timeout).read()
return ret
pycurl = None
StringIO = None
def _curl(url, params=None, post=False, username=None, password=None, header=None, body=None):
global pycurl, StringIO
if not pycurl:
import pycurl
try: import cStringIO as StringIO
except: import StringIO
curl = pycurl.Curl()
if get_prefs('use_http_proxy'):
HTTP_PROXY = '%s:%s' % (get_prefs('http_proxy_host'), get_prefs('http_proxy_port'))
curl.setopt(pycurl.PROXY, HTTP_PROXY)
if header:
curl.setopt(pycurl.HTTPHEADER, [str(k) + ':' + str(v) for k, v in header.items()])
if post:
curl.setopt(pycurl.POST, 1)
if params:
if post:
curl.setopt(pycurl.POSTFIELDS, urllib.urlencode(params))
else:
url = "?".join((url, urllib.urlencode(params)))
curl.setopt(pycurl.URL, str(url))
if username and password:
curl.setopt(pycurl.USERPWD, "%s:%s" % (str(username), str(password)))
curl.setopt(pycurl.FOLLOWLOCATION, 1)
curl.setopt(pycurl.MAXREDIRS, 5)
curl.setopt(pycurl.TIMEOUT, 15)
curl.setopt(pycurl.CONNECTTIMEOUT, 8)
curl.setopt(pycurl.HTTP_VERSION, pycurl.CURL_HTTP_VERSION_1_0)
content = StringIO.StringIO()
hdr = StringIO.StringIO()
curl.setopt(pycurl.WRITEFUNCTION, content.write)
curl.setopt(pycurl.HEADERFUNCTION, hdr.write)
print curl, url, header
try:
curl.perform()
except pycurl.error, e:
raise e
http_code = curl.getinfo(pycurl.HTTP_CODE)
if http_code != 200:
status_line = hdr.getvalue().splitlines()[0]
status_message = status_line
e =urllib2.HTTPError (str(url), http_code, status_message, {}, None)
e.url = url
raise e
else:
return content.getvalue()
def urlencode(query):
for k,v in query.items():
if not v:
del query[k]
return urllib.urlencode(query)
def idle_it(fn):
return lambda *args: gobject.idle_add(fn, *args)
| Python |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:
import glib
import gtk
import pango
import os
from xml.sax.saxutils import escape
queue = list()
actual_notification = None
def gtknotification(title, text, icon_file=None, const=None, callback=None, tooltip=None):
global actual_notification
global queue
if actual_notification is None:
actual_notification = Notification(title, text, icon_file, callback, tooltip)
actual_notification.show()
else:
if actual_notification._title == title:
actual_notification.append_text(text)
else:
found = False
auxqueue = list()
for _title, _text, _icon_file, _callback, _tooltip in queue:
if _title == title:
_text = _text + "\n" + text
found = True
auxqueue.append([_title, _text, _icon_file, _callback, _tooltip])
if found:
del queue
queue = auxqueue
else:
queue.append([title, text, icon_file, callback, tooltip])
class Notification(gtk.Window):
title_markup = '<span foreground="%s" weight="ultrabold">%s</span>'
text_markup = '<span foreground="%s"><b>%s</b>\n<span>%s</span></span>'
def __init__(self, title, text, icon_file, callback, tooltip):
gtk.Window.__init__(self, type=gtk.WINDOW_POPUP)
self.foreground_color = "white"
background_color = gtk.gdk.Color()
icon_size = 48;
max_width = 300;
self.callback = callback
self.set_border_width(10)
self._title = title
title_label = gtk.Label(self.title_markup % (self.foreground_color, escape(self._title)))
title_label.set_use_markup(True)
title_label.set_justify(gtk.JUSTIFY_LEFT)
title_label.set_ellipsize(pango.ELLIPSIZE_END)
text1, text2 = (text + '\n').split('\n', 1)
text = self.text_markup % (self.foreground_color, escape(text1), escape(text2))
self.text = text
self.message_label = gtk.Label(text)
self.message_label.set_use_markup(True)
self.message_label.set_justify(gtk.JUSTIFY_LEFT)
self.message_label.set_line_wrap(True)
self.message_label.set_alignment(0, 0)
image = gtk.Image()
image.set_alignment(0, 0)
if icon_file:
if icon_file.startswith('file://'):
icon_file = icon_file[7:]
try:
pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(icon_file, icon_size, icon_size)
image.set_from_pixbuf(pixbuf)
except:
pass
self.message_vbox = gtk.VBox()
self.message_vbox.pack_start(title_label, False, False)
self.message_vbox.pack_start(self.message_label, False, True)
lbox = gtk.HBox()
lbox.set_spacing(10)
lbox.pack_start(image, False, False)
lbox.pack_start(self.message_vbox, True, True)
event_box = gtk.EventBox()
event_box.set_visible_window(False)
event_box.set_events(gtk.gdk.BUTTON_PRESS_MASK)
event_box.connect("button_press_event", self.on_click)
event_box.add(lbox)
self.connect("button_press_event", self.on_click)
if tooltip is not None:
event_box.set_tooltip_text(tooltip)
nbox = gtk.HBox()
nbox.pack_start(event_box, True, True)
self.add(nbox)
self.set_app_paintable(True)
self.realize()
self.window.set_background(background_color)
self.set_opacity(0.6)
self.timer_id = None
self.set_default_size(max_width, -1)
self.connect("size-allocate", self.relocate)
self.show_all()
def append_text(self, text):
text1, text2 = (text + '\n').split('\n', 1)
text = self.text_markup % (self.foreground_color, escape(text1), escape(text2))
self.text = self.text + "\n" + text
self.message_label.set_text(self.text)
self.message_label.set_use_markup(True)
self.message_label.show()
def relocate(self, widget=None, allocation=None):
width, height = self.get_size()
screen_w = gtk.gdk.screen_width()
screen_h = gtk.gdk.screen_height()
x = screen_w - width - 20
y = 30
self.move(x,y)
def on_click(self, widget, event):
if self.callback is not None:
self.callback()
self.close()
def show(self):
self.show_all()
self.timer_id = glib.timeout_add_seconds(15, self.close)
return True
def close(self, *args):
global actual_notification
global queue
self.hide()
if self.timer_id is not None:
glib.source_remove(self.timer_id)
if len(queue) != 0:
title, text, icon_file, callback, tooltip = queue.pop(0)
actual_notification = Notification(title, text, icon_file, callback, tooltip)
actual_notification.show()
else:
actual_notification = None
self.destroy()
| Python |
#!/usr/bin/env python
# -*- coding:utf8 -*-
'''Hotot
@author: U{Shellex Wei <5h3ll3x@gmail.com>}
@license: LGPLv3+
'''
import gtk
import gobject
import view
import config
import agent
import keybinder
import utils
try:
import appindicator
except ImportError:
HAS_INDICATOR = False
else:
HAS_INDICATOR = True
if __import__('os').environ.get('DESKTOP_SESSION') in ('gnome-2d', 'classic-gnome'):
HAS_INDICATOR = False
try: import i18n
except: from gettext import gettext as _
try:
import glib
glib.set_application_name(_("Hotot"))
except:
pass
class Hotot:
def __init__(self):
self.is_sign_in = False
self.active_profile = 'default'
self.protocol = ''
self.build_gui()
if not HAS_INDICATOR:
self.create_trayicon()
def build_gui(self):
self.window = gtk.Window()
gtk.window_set_default_icon_from_file(
utils.get_ui_object('image/ic64_hotot_classics.png'))
self.window.set_icon_from_file(
utils.get_ui_object('image/ic64_hotot_classics.png'))
self.window.set_title(_("Hotot"))
self.window.set_position(gtk.WIN_POS_CENTER)
#self.window.set_default_size(500, 550)
vbox = gtk.VBox()
scrollw = gtk.ScrolledWindow()
self.webv = view.MainView()
agent.view = self.webv
scrollw.add(self.webv)
vbox.pack_start(scrollw)
vbox.show_all()
self.window.add(vbox)
self.menu_tray = gtk.Menu()
mitem_resume = gtk.MenuItem(_("_Resume/Hide"))
mitem_resume.connect('activate', self.on_trayicon_activate);
self.menu_tray.append(mitem_resume)
mitem_prefs = gtk.ImageMenuItem(gtk.STOCK_PREFERENCES)
mitem_prefs.connect('activate', self.on_mitem_prefs_activate);
self.menu_tray.append(mitem_prefs)
mitem_about = gtk.ImageMenuItem(gtk.STOCK_ABOUT)
mitem_about.connect('activate', self.on_mitem_about_activate);
self.menu_tray.append(mitem_about)
mitem_quit = gtk.ImageMenuItem(gtk.STOCK_QUIT)
mitem_quit.connect('activate', self.on_mitem_quit_activate);
self.menu_tray.append(mitem_quit)
self.menu_tray.show_all()
## support for ubuntu unity indicator-appmenu
menubar = gtk.MenuBar()
menuitem_file = gtk.MenuItem(_("_File"))
menuitem_file_menu = gtk.Menu()
mitem_resume = gtk.MenuItem(_("_Resume/Hide"))
mitem_resume.connect('activate', self.on_mitem_resume_activate);
menuitem_file_menu.append(mitem_resume)
mitem_prefs = gtk.ImageMenuItem(gtk.STOCK_PREFERENCES)
mitem_prefs.connect('activate', self.on_mitem_prefs_activate);
menuitem_file_menu.append(mitem_prefs)
menuitem_quit = gtk.ImageMenuItem(gtk.STOCK_QUIT)
menuitem_quit.connect("activate", self.quit)
menuitem_file_menu.append(menuitem_quit)
menuitem_file.set_submenu(menuitem_file_menu)
menubar.append(menuitem_file)
menuitem_help = gtk.MenuItem(_("_Help"))
menuitem_help_menu = gtk.Menu()
menuitem_about = gtk.ImageMenuItem(gtk.STOCK_ABOUT)
menuitem_about.connect("activate", self.on_mitem_about_activate)
menuitem_help_menu.append(menuitem_about)
menuitem_help.set_submenu(menuitem_help_menu)
menubar.append(menuitem_help)
menubar.set_size_request(0, 0)
menubar.show_all()
vbox.pack_start(menubar, expand=0, fill=0, padding=0)
##
self.window.set_geometry_hints(min_height=380, min_width=460)
self.window.show()
self.window.connect('delete-event', gtk.Widget.hide_on_delete)
def on_btn_update_clicked(self, btn):
if (self.tbox_status.get_text_length() <= 140):
agent.update_status(self.tbox_status.get_text())
self.tbox_status.set_text('')
self.inputw.hide()
def on_tbox_status_changed(self, entry):
if (self.tbox_status.get_text_length() <= 140):
entry.modify_base(gtk.STATE_NORMAL, gtk.gdk.Color('#fff'))
else:
entry.modify_base(gtk.STATE_NORMAL, gtk.gdk.Color('#f00'))
def on_tbox_status_key_released(self, entry, event):
if event.keyval == gtk.keysyms.Return:
self.btn_update.clicked();
entry.stop_emission('insert-text')
def on_mitem_resume_activate(self, item):
self.window.present()
def on_mitem_prefs_activate(self, item):
agent.execute_script('''
ui.PrefsDlg.load_settings(conf.settings);
ui.PrefsDlg.load_prefs();
globals.prefs_dialog.open();''');
self.window.present()
def on_mitem_about_activate(self, item):
agent.execute_script('globals.about_dialog.open();');
self.window.present()
def on_mitem_quit_activate(self, item):
self.quit()
def quit(self, *args):
gtk.gdk.threads_leave()
self.window.destroy()
gtk.main_quit()
import sys
sys.exit(0)
def apply_settings(self):
# init hotkey
self.init_hotkey()
# resize window
self.window.set_gravity(gtk.gdk.GRAVITY_CENTER)
self.window.resize(
config.settings['size_w']
, config.settings['size_h'])
# apply proxy
self.apply_proxy_setting()
def apply_proxy_setting(self):
if config.settings['use_http_proxy']:
proxy_uri = "https://%s:%s" % (
config.settings['http_proxy_host']
, config.settings['http_proxy_port'])
if config.settings['http_proxy_host'].startswith('http://'):
proxy_uri = "%s:%s" % (
config.settings['http_proxy_host']
, config.settings['http_proxy_port'])
utils.webkit_set_proxy_uri(proxy_uri)
else:
utils.webkit_set_proxy_uri("")
# workaround for a BUG of webkitgtk/soupsession
# proxy authentication
agent.execute_script('''
new Image().src='http://google.com/';''');
def init_hotkey(self):
try:
keybinder.bind(
config.settings['shortcut_summon_hotot']
, self.on_hotkey_compose)
except:
pass
def create_trayicon(self):
"""
Create status icon and connect signals
"""
self.trayicon = gtk.StatusIcon()
self.trayicon.connect('activate', self.on_trayicon_activate)
self.trayicon.connect('popup-menu', self.on_trayicon_popup_menu)
self.trayicon.set_tooltip(_("Hotot: Click to Active."))
self.trayicon.set_from_file(
utils.get_ui_object('image/ic24_hotot_mono_light.svg'))
self.trayicon.set_visible(True)
def on_trayicon_activate(self, icon):
gobject.idle_add(self._on_trayicon_activate, icon)
def _on_trayicon_activate(self, icon):
if self.window.is_active():
self.window.hide()
else:
self.window.present()
def on_trayicon_popup_menu(self, icon, button, activate_time):
self.menu_tray.popup(None, None
, None, button=button
, activate_time=activate_time)
def on_hotkey_compose(self):
gobject.idle_add(self._on_hotkey_compose)
def _on_hotkey_compose(self):
if not self.webv.is_focus():
self.window.hide()
self.window.present()
self.webv.grab_focus()
def on_sign_in(self):
self.is_sign_in = True
#self.window.set_title('Hotot | %s' % '$')
def on_sign_out(self):
self.is_sign_in = False
def main():
global HAS_INDICATOR
gtk.gdk.threads_init()
config.loads();
try:
import dl
libc = dl.open('/lib/libc.so.6')
libc.call('prctl', 15, 'hotot', 0, 0, 0)
except:
pass
agent.init_notify()
app = Hotot()
agent.app = app
if HAS_INDICATOR:
#TODO the icon is only work when installed to /usr/share/icons/hicolor/
indicator = appindicator.Indicator('hotot',
'hotot',
appindicator.CATEGORY_COMMUNICATIONS)
indicator.set_status(appindicator.STATUS_ACTIVE)
indicator.set_attention_icon(utils.get_ui_object('image/ic24_hotot_mono_light.svg'))
indicator.set_menu(app.menu_tray)
gtk.gdk.threads_enter()
gtk.main()
gtk.gdk.threads_leave()
if __name__ == '__main__':
main()
| Python |
#!/usr/bin/env python
# -*- coding:utf8 -*-
import gtk
gtk.gdk.threads_init() ## fix issue 24
import webkit
import agent
import config
from webkit import WebView
import utils
import json
import gobject
try: import i18n
except: from gettext import gettext as _
class MainView(WebView):
def __init__(self):
WebView.__init__(self)
self.load_finish_flag = False
self.set_property('can-focus', True)
self.set_property('can-default', True)
self.set_full_content_zoom(1)
self.clipbord = gtk.Clipboard()
settings = self.get_settings()
try:
settings.set_property('enable-universal-access-from-file-uris', True)
settings.set_property('javascript-can-access-clipboard', True)
settings.set_property('enable-default-context-menu', True)
settings.set_property('enable-page-cache', True)
settings.set_property('tab-key-cycles-through-elements', True)
settings.set_property('enable-file-access-from-file-uris', True)
settings.set_property('enable-spell-checking', False)
settings.set_property('enable-caret-browsing', False)
except:
print 'Error: settings property was not set.'
webkit.set_web_database_directory_path(config.DB_DIR)
webkit.set_default_web_database_quota(1024**3L)
## bind events
self.connect('navigation-requested', self.on_navigation_requested);
self.connect('new-window-policy-decision-requested', self.on_new_window_requested);
self.connect('script-alert', self.on_script_alert);
self.connect('load-finished', self.on_load_finish);
self.connect("hovering-over-link", self.on_over_link);
templatefile = utils.get_ui_object(config.TEMPLATE)
template = open(templatefile, 'rb').read()
self.load_html_string(template, 'file://' + templatefile)
def on_navigation_requested(self, view, webframe, request):
return self.handle_uri(request.get_uri())
def on_new_window_requested(self, view, frame, request, decision, u_data):
return self.handle_uri(request.get_uri())
def handle_uri(self, uri):
if uri.startswith('file://'):
return False
elif uri.startswith('hotot:'):
self.on_hotot_action(uri)
return True
elif uri.startswith('about:'):
return True
else:
utils.open_webbrowser(uri)
return True
def on_script_alert(self, view, webframe, message):
if message.startswith('hotot:'):
self.on_hotot_action(message)
return True
return False
def on_hotot_action(self, uri):
if uri.startswith('hotot:'):
agent.crack_hotot(uri[6:])
return True
def on_load_finish(self, view, webframe):
self.load_finish_flag = True;
agent.webv = self
# overlay extra variables of web part
variables = {
'platform': 'Linux'
, 'conf_dir': config.CONF_DIR
, 'cache_dir': config.CACHE_DIR
, 'avatar_cache_dir': config.AVATAR_CACHE_DIR
, 'extra_fonts': utils.get_extra_fonts()
, 'extra_exts': utils.get_extra_exts()
, 'locale': utils.get_locale()
};
# and then, notify web part i am ready to work :)
gobject.idle_add(view.execute_script, '''
overlay_variables(%s);
globals.load_flags = 1;
''' % json.dumps(variables))
def on_over_link(self, view, alt, href):
href = href or ""
if not alt and not href.startswith('file:'):
self.parent.set_tooltip_text(href)
| Python |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:
# Author: Huang Jiahua <jhuangjiahua@gmail.com>
# License: LGPLv3+
# Last modified:
app = 'hotot'
import os, sys
import gettext
import json
import re
if os.path.isdir(os.path.dirname(sys.argv[0]) + '/../build/mo'):
gettext.install(app, os.path.dirname(sys.argv[0]) + '/../build/mo', unicode=True)
elif os.path.isdir(os.path.dirname(sys.argv[0]) + '/build/mo'):
gettext.install(app, os.path.dirname(sys.argv[0]) + '/build/mo', unicode=True)
else:
gettext.install(app, unicode=True)
if __name__=="__main__":
print _('')
| Python |
# -*- coding: UTF-8 -*-
import os
import pickle
import json
import gtk
import sys
import glob
import shutil
import glib
PROGRAM_NAME = 'hotot'
EXT_DIR_NAME = 'ext'
CONF_DIR = os.path.join(glib.get_user_config_dir(), PROGRAM_NAME)
DB_DIR = os.path.join(CONF_DIR, 'db')
CACHE_DIR = os.path.join(glib.get_user_cache_dir(), PROGRAM_NAME)
AVATAR_CACHE_DIR = os.path.join(CACHE_DIR, 'avatar')
DATA_DIRS = []
DATA_BASE_DIRS = [
'/usr/local/share'
, '/usr/share'
, glib.get_user_data_dir()
]
DATA_DIRS += [os.path.join(d, PROGRAM_NAME) for d in DATA_BASE_DIRS]
DATA_DIRS.append(os.path.abspath('./data'))
TEMPLATE = 'index.html'
settings = {}
def getconf():
'''获取 config
'''
config = {}
##
if not os.path.isdir(CONF_DIR): os.makedirs(CONF_DIR)
if not os.path.isdir(AVATAR_CACHE_DIR): os.makedirs(AVATAR_CACHE_DIR)
for k, v in globals().items():
if not k.startswith('__') and (
isinstance(v, str)
or isinstance(v, int)
or isinstance(v, long)
or isinstance(v, float)
or isinstance(v, dict)
or isinstance(v, list)
or isinstance(v, bool)
):
config[k] = v
return config
def loads():
config = getconf();
def load_settings(pushed_settings):
pushed_settings = dict([(k.encode('utf8'), v) for k, v in pushed_settings.items()])
globals()['settings'] = pushed_settings
return settings
| Python |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# vim:set shiftwidth=4 tabstop=4 expandtab textwidth=79:
# Author: Shellex Wai <5h3ll3x@gmail.com>
# License: GNU LGPL
# Last modified:
"""
"""
__revision__ = '0.1'
if __name__=="__main__":
import hotot.hotot
hotot.hotot.main()
| Python |
#!/usr/bin/env python
# -*- coding:utf8 -*-
from distutils.core import setup
from DistUtilsExtra.command import *
from glob import glob
import os, os.path
def get_data_files(root, data_dir):
return [
(root + parent[len(data_dir):], [ os.path.join(parent, fn) for fn in files ])
for parent, dirs, files in os.walk(data_dir) if files
]
setup(name='hotot',
version="0.9.6",
description='Lightweight Twitter Client',
long_description =
"""
Lightweight Twitter Client base on Gtk2 and Webkit.
Features include:
- Update/View Timelines.
- Follow/Unfollow peoples.
- Post status.
- Reply tweets.
- Post direct messages.
- View people profile.
- Native notification.
- Global key-shortcut.
""",
author='Shellex Wai',
author_email='5h3ll3x@gmail.com',
license='LGPL-3',
url="http://code.google.com/p/hotot",
download_url="http://code.google.com/p/hotot/downloads/list",
platforms = ['Linux'],
requires = ['webkit', 'gtk', 'gobject', 'keybinder', 'pynotify'],
scripts=['scripts/hotot'],
packages = ['hotot'],
data_files = [
('share/pixmaps', ['hotot.png']),
] + get_data_files('share/hotot', 'data'),
cmdclass = { "build" : build_extra.build_extra,
"build_i18n" : build_i18n.build_i18n,
}
)
| Python |
#!/usr/bin/env python
# -*- coding:utf8 -*-
import re
import json
import os.path
TEMPLATE = "data/index.html"
DEFAULT_LOCALE_FILE = 'data/_locales/en/messages.json'
JS_FILE_DIR = ['data/js/']
LOCALE_FILE_DIR = 'data/_locales/'
template_tag_re = re.compile('data-i18n-[a-z0-9]+="(.+?)"')
js_tag_re = re.compile('''_\('([a-z0-9_]+)'\)''', re.MULTILINE)
js_tag_map = {}
def scan_template():
template_file = open(TEMPLATE, 'r')
html_data = template_file.read()
template_file.close()
key_list = template_tag_re.findall(html_data)
return key_list
def scan_js_dir():
for dir in JS_FILE_DIR:
os.path.walk(dir, scan_js_dir_cb, None)
def scan_js_dir_cb(arg, dir_name, f_names):
''' scan js files and generate a empty map'''
for name in f_names:
if not name.endswith('.js'):
continue
path = os.path.join(dir_name, name)
data = file(path, 'r').read()
tags = js_tag_re.findall(data)
if tags:
for tag in tags:
js_tag_map[tag] = {'message': '', 'description': path}
def generate_trans_template(key_list):
template = {}
for key in key_list:
template[key] = {'message':'', 'description': TEMPLATE}
return template
def load_exist_trans(trans_file):
return json.loads(file(trans_file).read())
def walk_cb(empty_trans, dir_name, f_names):
new_trans = ''
exists_trans = {}
if dir_name.endswith('data/_locales/'):
return
file_path = os.path.join(dir_name, 'messages.json')
if 'messages.json' in f_names:
trans_file = open(file_path, 'r')
exists_data = trans_file.read()
if exists_data:
exists_trans = json.loads(exists_data)
else:
exists_trans = {}
trans_file.close()
new_trans = format_out(merge_trans(empty_trans, exists_trans))
print '[Update]', file_path
else:
default_trans = json.loads(file(DEFAULT_LOCALE_FILE, 'r').read())
new_trans = format_out(merge_trans(empty_trans, default_trans))
print '[Create]', file_path
trans_file = open(file_path, 'w+')
trans_file.write(new_trans.encode('utf-8'))
trans_file.close()
def merge_trans(empty_trans, exists_trans):
keys_not_supported = []
for key in exists_trans:
if key not in empty_trans:
keys_not_supported.append(key)
for key in keys_not_supported:
print 'Cannot find Key', key, 'in template, delete it? (y/n):' ,
if raw_input().strip() == 'y':
del exists_trans[key]
new_trans = empty_trans.copy()
new_trans.update(exists_trans)
for key in new_trans:
if not new_trans[key]['message']:
print '[!] Empty Key: [%s]' % key
return new_trans
def format_out(trans):
arr = []
for k, v in trans.items():
sub_arr = []
for sub_k, sub_v in v.items():
sub_arr.append('\t\t"%s": "%s"' % (sub_k, sub_v))
arr.append(('\t"%s": {\n' % k )+ ',\n'.join(sub_arr) + '\n\t}')
return '{\n'+',\n'.join(arr)+'\n}'
if __name__ == '__main__':
keys = scan_template()
scan_js_dir()
print 'keys: ', keys
empty_trans = generate_trans_template(keys)
empty_trans.update(js_tag_map)
os.path.walk(LOCALE_FILE_DIR, walk_cb, empty_trans)
| Python |
# Django settings for foiaqui project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@domain.com'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = 'mysql' # 'postgresql', 'mysql', 'sqlite3' or 'ado_mssql'.
DATABASE_NAME = 'foiaqui' # Or path to database file if using sqlite3.
DATABASE_USER = 'root' # Not used with sqlite3.
DATABASE_PASSWORD = 'myPassword' # 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.
# Local time zone for this installation. All choices can be found here:
# http://www.postgresql.org/docs/current/static/datetime-keywords.html#DATETIME-TIMEZONE-SET-TABLE
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.w3.org/TR/REC-html40/struct/dirlang.html#langcodes
# http://blogs.law.harvard.edu/tech/stories/storyReader$15
LANGUAGE_CODE = 'pt-br'
SITE_ID = 1
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT.
# Example: "http://media.lawrence.com"
MEDIA_URL = ''
# URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a
# trailing slash.
# Examples: "http://foo.com/media/", "/media/".
ADMIN_MEDIA_PREFIX = '/media/'
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'j9_o9y+#(=f5v5r(w+vp_14kz%du3bqh700+__clh%r$h+exb^'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
# 'django.template.loaders.eggs.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.middleware.doc.XViewMiddleware',
'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
)
ROOT_URLCONF = 'foiaqui.urls'
TEMPLATE_DIRS = (
'templates'
# Put strings here, like "/home/html/django_templates".
# Always use forward slashes, even on Windows.
)
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.admin',
'django.contrib.sites',
'django.contrib.flatpages',
'foiaqui.core',
'foiaqui.polls',
'foiaqui.crimes',
# 'foiaqui.contacts',
)
| Python |
#!/usr/bin/python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
if __name__ == "__main__":
execute_manager(settings)
| Python |
from django.db import models
class Poll(models.Model):
question = models.CharField(maxlength=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.question
class Admin:
pass
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(maxlength=200)
votes = models.IntegerField()
def __str__(self):
return self.choice
class Admin:
pass
| Python |
from django.shortcuts import render_to_response
from foiaqui.polls.models import Poll
from django.shortcuts import render_to_response, get_object_or_404
def index(request):
latest_poll_list = Poll.objects.all().order_by('-pub_date')[:5]
return render_to_response('polls/index.html', {'latest_poll_list': latest_poll_list})
#def detail(request, poll_id):
#return HttpResponse("You're looking at poll %s." % poll_id)
#def detail(request, poll_id):
#try:
#p = Poll.objects.get(pk=poll_id)
#except Poll.DoesNotExist:
#raise Http404
#return render_to_response('polls/detail.html', {'poll': p})
def detail(request, poll_id):
p = get_object_or_404(Poll, pk=poll_id)
return render_to_response('polls/detail.html', {'poll': p})
| Python |
from django.conf.urls.defaults import *
urlpatterns = patterns('',
(r'^polls/$', 'foiaqui.polls.views.index'),
(r'^polls/(?P<poll_id>\d+)/$', 'foiaqui.polls.views.detail'),
(r'^polls/(?P<poll_id>\d+)/results/$', 'foiaqui.polls.views.results'),
(r'^polls/(?P<poll_id>\d+)/vote/$', 'foiaqui.polls.views.vote'),
(r'^mediafiles/(?P<path>.*)$', 'django.views.static.serve', {'document_root': '/home/silveira/Desktop/foiaqui/media'}),
(r'^admin/', include('django.contrib.admin.urls')),
(r'^crimes/xml/$', 'foiaqui.crimes.views.xml'),
(r'^crimes/form/$', 'foiaqui.crimes.views.form'),
(r'^crimes/insert/$', 'foiaqui.crimes.views.insert'),
(r'^crimes/(?P<id>\d+)/$', 'foiaqui.crimes.views.detail'),
(r'^$', 'foiaqui.core.views.index'),
# (r'^contact/thankyou/', 'contacts.views.thankyou'),
# (r'^contact/', 'contacts.views.contactview'),
)
| Python |
from django.db import models
import datetime
# mobility classification
MOBILITY = (
('WK', 'Walking'),
('VE', 'Vehicle'),
)
QUANTITY = (
('AL','Alone'),
('FO','Folloied'),
)
THIEF = (
('ON','One'),
('MA','Many'),
)
WEAPON = (
('MW','Melee'),
('GN','Guns'),
('NN','None'),
)
PERIOD = (
('MO','Morning'),
('EV','Evening'),
('NI','Night'),
)
class Incident (models.Model):
"""An localized crime incident"""
# general information
desc = models.TextField()
lon = models.CharField(maxlength=30)
lat = models.CharField(maxlength=30)
when = models.DateTimeField()
# classification
mobility = models.CharField(maxlength=2, choices=MOBILITY)
quantity = models.CharField(maxlength=2, choices=QUANTITY)
thief = models.CharField(maxlength=2, choices=THIEF)
weapon = models.CharField(maxlength=2, choices=WEAPON)
period = models.CharField(maxlength=2, choices=PERIOD)
def summary(self):
"""An short description of the description"""
cut = 100
if len(self.desc) > cut:
return self.desc[:cut]+" ..."
else:
return self.desc[:cut]
def __str__(self):
"""An string representation of the incident object"""
cut = 10
if len(self.desc) > cut:
return str(self.id)+" "+self.desc[:cut]+" ..."
else:
return str(self.id)+" "+self.desc[:cut]
def was_today(self):
"""True if when is current day"""
return self.when == datetime.date.today()
# To be visible in the admin interface
class Admin:
pass
| Python |
# Django
from django.shortcuts import render_to_response
from django.shortcuts import render_to_response, get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
# Python
from datetime import datetime
# foiaqui
from foiaqui.crimes.models import Incident
# XML view
def xml(request):
""" Sends a XML file with some incidents """
incident_list = Incident.objects.all()
response = render_to_response('crimes/list.xml', {'incident_list': incident_list})
response['Content-Type'] = 'text/xml'
response['Content-Disposition'] = "attachment; filename=list.xml"
return response
def insert(request):
""" Calls that when you want to insert an incident by POST """
# Get current time and date from the server
now = datetime.now()
# From POST we get desc, lat, lng
desc = request.POST.get('desc', '')
lat = request.POST.get('lat', '')
lng = request.POST.get('lng', '')
# Create a new incident and save it
new_incident = Incident(desc=desc, lat=lat, lon=lng, when=now)
new_incident.save()
# If we got all parameters
if desc and lat and lng:
return HttpResponse('desc=%s<br/>lat=%s<br/>lng=%s<br/>'%(desc,lat,lng))
# If one or more are missing
else:
return HttpResponse('One or more parameters are missing ...<br/>desc=%s<br/>lat=%s<br/>lng=%s<br/>'%(desc,lat,lng))
def form(request):
""" Displays a form of a new incident """
if request.method == 'POST':
mobility = request.POST.get("mobility", "")
quantity = request.POST.get("quantity", "")
thief = request.POST.get("thief", "")
weapon = request.POST.get("weapon", "")
period = request.POST.get("period", "")
desc = request.POST.get("desc", "")
lat = request.POST.get("lat", "0")
lng = request.POST.get("lng", "0")
print 'eis: ',lat, lng
# If this request come from the main site (the map), the form should know only desc.
from_main = request.POST.get("from_main", "False")
if from_main == "True":
return render_to_response('crimes/form.html', {'desc':desc, 'lat':lat,'lng':lng})
# If we have all stuff we need, lets create a incident and save it.
if mobility and quantity and thief and weapon and period and desc:
# we get the local time
now = datetime.now()
# creates a new incident and save it
new_incident = Incident(desc=desc, when=now, mobility=mobility, quantity=quantity, thief=thief, weapon = weapon, period=period, lat=lat, lon=lng)
new_incident.save()
return HttpResponseRedirect('/')
# If everything else fails, we call form.html but passing what we have.
return render_to_response('crimes/form.html',{'mobility': mobility,'quantity':quantity, 'thief': thief, 'weapon':weapon, 'period':period, 'desc':desc, 'lat':lat, 'lng':lng, 'from_main':from_main})
else:
return HttpResponseRedirect('/')
# return HttpResponse('Acesse o site principal para criar um novo incidente')
# return render_to_response('base.html')
def detail(request, id='1'):
""" Displays a detailed view of an incident"""
i = get_object_or_404(Incident, pk=id)
return render_to_response('crimes/detail.html',{'incident':i})
#i = Incident.objects.all().get(pk=id)
#return render_to_response('crimes/form.html',{'incident':i})
| Python |
from django.db import models
# Create your models here.
| Python |
from django.shortcuts import render_to_response
from foiaqui.crimes.models import Incident
def index(request):
# How many incidents we have
n = Incident.objects.count()
# Transform in a language text
if n == 0:
text = "Nao ha nenhum incidente registrado."
elif n == 1:
text = "Atualmente nos temos <strong>%d</strong> incidente registrado." % n
else:
text = "Atualmente nos temos <strong>%d</strong> incidentes registrados." % n
# get all incidents
list = Incident.objects.all()
return render_to_response('base.html', {'incident_list':list, 'incident_counter_text':text})
| Python |
#!/usr/bin/python
from django.core.management import execute_manager
try:
import settings # Assumed to be in the same directory.
except ImportError:
import sys
sys.stderr.write("Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customized things.\nYou'll have to run django-admin.py, passing it your settings module.\n(If the file settings.py does indeed exist, it's causing an ImportError somehow.)\n" % __file__)
sys.exit(1)
if __name__ == "__main__":
execute_manager(settings)
| Python |
#!/usr/bin/env python
#coding=utf-8
import os
import string
from consts import *
def main():
line_infos = [[0]*1024 for i in range(10)]
for idx in range(10):
for flag in range(1024):
flag |= 0xFC00
p1 = (idx and [idx-1] or [0xF])[0]
while not flag & (1 << p1):
p1 = (p1 and [p1-1] or [0xF])[0]
p2 = (p1 and [p1-1] or [0xF])[0]
while not flag & (1 << p2):
p2 = (p2 and [p2-1] or [0xF])[0]
n1 = idx + 1
while not flag & (1 << n1):
n1 += 1
n2 = n1 + 1
while not flag & (1 << n2):
n2 += 1
line_infos[idx][flag & 1023] = p1 | (p2 << 4) | (n1 << 8) | (n2 << 12)
bits = [1 << i for i in range(10)]
bit_counts = [len([j for j in bits if i & j])for i in range(1024)]
distance_infos = [[(19 << 10 | 1023)]*128 for i in range(91)]
for src in range(90):
sy, sx = divmod(src, 9)
for dst in range(90):
if dst == src:
continue
dy, dx = divmod(dst, 9)
if dx == sx:
idx = dx+10
mask = sum(bits[i] for i in set(range(dy+1, sy)+range(sy+1, dy)) if i in range(10))
distance_infos[src][dst] = (idx << 10) | mask
elif dy == sy:
idx = dy
mask = sum(bits[i] for i in set(range(dx+1, sx)+range(sx+1, dx)) if i in range(10))
distance_infos[src][dst] = (idx << 10) | mask
dict = {}
dict['infos'] = d2a_str(line_infos, u32)
dict['counts'] = d1a_str(bit_counts, u32)
dict['distance'] = d2a_str(distance_infos, u32)
template = open(os.path.join(template_path, 'bitmap_data.cpp.tmpl'), 'rb').read()
template = string.Template(template)
path = os.path.join(folium_path, 'bitmap_data.cpp')
open(path, 'wb').write(str(template.safe_substitute(dict)))
if __name__ == "__main__":
main()
| Python |
import xq_data
xq_data.main()
import xq_position_data
xq_position_data.main()
import history_data
history_data.main()
import bitmap_data
bitmap_data.main()
| Python |
#!/usr/bin/env python
#coding=utf-8
import os
import string
from consts import *
from xq_data import *
def capture_scores():
capture_scores = [[0]*32 for i in range(33)]
e = [10000, 1041, 1040, 2000, 1088, 1096, 1020]
m = [1000, 41, 40, 200, 88, 96, 20]
def level(src_type, dst_type): return levels[src_type][dst_type]
def color(piece): return PC[piece]
def type(piece):
t = PT[piece]
if t >= 7:
t -= 7
return t
for src_piece in range(32):
for dst_piece in range(32):
if color(src_piece) != color(dst_piece):
src_type = type(src_piece)
dst_type = type(dst_piece)
capture_scores[dst_piece][src_piece] = e[dst_type] - m[src_type] + 1 << 17
return capture_scores
capture_scores = capture_scores()
def main():
dict = {}
dict['scores'] = d2a_str(capture_scores, u32)
template = open(os.path.join(template_path, 'history_data.cpp.tmpl'), 'rb').read()
template = string.Template(template)
path = os.path.join(folium_path, 'history_data.cpp')
open(path, 'wb').write(str(template.safe_substitute(dict)))
if __name__ == "__main__":
main() | Python |
#!/usr/bin/env python
#coding=utf-8
import os
import string
from consts import *
def main():
line_infos = [[0]*1024 for i in range(10)]
for idx in range(10):
for flag in range(1024):
flag |= 0xFC00
p1 = (idx and [idx-1] or [0xF])[0]
while not flag & (1 << p1):
p1 = (p1 and [p1-1] or [0xF])[0]
p2 = (p1 and [p1-1] or [0xF])[0]
while not flag & (1 << p2):
p2 = (p2 and [p2-1] or [0xF])[0]
n1 = idx + 1
while not flag & (1 << n1):
n1 += 1
n2 = n1 + 1
while not flag & (1 << n2):
n2 += 1
line_infos[idx][flag & 1023] = p1 | (p2 << 4) | (n1 << 8) | (n2 << 12)
bits = [1 << i for i in range(10)]
bit_counts = [len([j for j in bits if i & j])for i in range(1024)]
distance_infos = [[(19 << 10 | 1023)]*128 for i in range(91)]
for src in range(90):
sy, sx = divmod(src, 9)
for dst in range(90):
if dst == src:
continue
dy, dx = divmod(dst, 9)
if dx == sx:
idx = dx+10
mask = sum(bits[i] for i in set(range(dy+1, sy)+range(sy+1, dy)) if i in range(10))
distance_infos[src][dst] = (idx << 10) | mask
elif dy == sy:
idx = dy
mask = sum(bits[i] for i in set(range(dx+1, sx)+range(sx+1, dx)) if i in range(10))
distance_infos[src][dst] = (idx << 10) | mask
dict = {}
dict['infos'] = d2a_str(line_infos, u32)
dict['counts'] = d1a_str(bit_counts, u32)
dict['distance'] = d2a_str(distance_infos, u32)
template = open(os.path.join(template_path, 'bitmap_data.cpp.tmpl'), 'rb').read()
template = string.Template(template)
path = os.path.join(folium_path, 'bitmap_data.cpp')
open(path, 'wb').write(str(template.safe_substitute(dict)))
if __name__ == "__main__":
main()
| Python |
RedKing = 0;
RedAdvisor = 1;
RedBishop = 2;
RedRook = 3;
RedKnight = 4;
RedCannon = 5;
RedPawn = 6;
BlackKing = 7;
BlackAdvisor = 8;
BlackBishop = 9;
BlackRook = 10;
BlackKnight = 11;
BlackCannon = 12;
BlackPawn = 13;
EmptyType = 14;
InvalidType = 15;
RedKingFlag = 1 << 0;
RedAdvisorFlag = 1 << 1;
RedBishopFlag = 1 << 2;
RedRookFlag = 1 << 3;
RedKnightFlag = 1 << 4;
RedCannonFlag = 1 << 5;
RedPawnFlag = 1 << 6;
BlackKingFlag = 1 << 7;
BlackAdvisorFlag = 1 << 8;
BlackBishopFlag = 1 << 9;
BlackRookFlag = 1 << 10;
BlackKnightFlag = 1 << 11;
BlackCannonFlag = 1 << 12;
BlackPawnFlag = 1 << 13;
EmptyFlag = 1 << 14;
InvaildFlag = 1 << 15;
AdvisorFlag = RedAdvisorFlag | BlackAdvisorFlag
BishopFlag = RedBishopFlag | BlackBishopFlag
RedKingPawnFlag = RedKingFlag | RedPawnFlag
AdvisorBishopFlag = RedAdvisorFlag | RedBishopFlag | BlackAdvisorFlag | BlackBishopFlag
RedKingSquares = [x + y * 9 for x, y in [(3, 0), (4, 0), (5, 0), (3, 1), (4, 1), (5, 1), (3, 2), (4, 2), (5, 2)]]
RedAdvisorSquares = [x + y * 9 for x, y in [(3,0), (5,0), (4, 1), (3,2), (5,2)]]
RedBishopSquares = [x + y * 9 for x, y in [(2, 0), (6, 0), (0, 2), (4, 2), (8, 2), (2, 4), (6, 4)]]
RedRookSquares = range(90)
RedKnightSquares = range(90)
RedCannonSquares = range(90)
RedPawnSquares = [x + y * 9 for x, y in [(0, 3), (2, 3), (4, 3), (6, 3), (8, 3), (0, 4), (2, 4), (4, 4), (6, 4), (8, 4)]]
RedPawnSquares.extend(range(45, 90))
BlackKingSquares = [89 - sq for sq in RedKingSquares]
BlackAdvisorSquares = [89 - sq for sq in RedAdvisorSquares]
BlackBishopSquares = [89 - sq for sq in RedBishopSquares]
BlackRookSquares = [89 - sq for sq in RedRookSquares]
BlackKnightSquares = [89 - sq for sq in RedKnightSquares]
BlackCannonSquares = [89 - sq for sq in RedCannonSquares]
BlackPawnSquares = [89 - sq for sq in RedPawnSquares]
def SquareFlags():
SquareFlags = [0]*91
for sq in RedKingSquares:
SquareFlags[sq] |= RedKingFlag
SquareFlags[89 - sq] |= BlackKingFlag
for sq in RedAdvisorSquares:
SquareFlags[sq] |= RedAdvisorFlag
SquareFlags[89 - sq] |= BlackAdvisorFlag
for sq in RedBishopSquares:
SquareFlags[sq] |= RedBishopFlag
SquareFlags[89 - sq] |= BlackBishopFlag
for sq in RedPawnSquares:
SquareFlags[sq] |= RedPawnFlag
SquareFlags[89 - sq] |= BlackPawnFlag
for sq in range(90):
SquareFlags[sq] |= RedRookFlag
SquareFlags[sq] |= RedKnightFlag
SquareFlags[sq] |= RedCannonFlag
SquareFlags[sq] |= BlackRookFlag
SquareFlags[sq] |= BlackKnightFlag
SquareFlags[sq] |= BlackCannonFlag
SquareFlags[sq] |= EmptyFlag
SquareFlags[90] |= InvaildFlag
return SquareFlags
SquareFlags = SquareFlags()
def u64(i):
return str(i)+'ULL'
def u32(i):
return str(i)+'UL'
def s32(i):
return str(i)+'L'
def d1a_str(array_1d, func):
array_1d = [func(i) for i in array_1d]
return ', '.join(array_1d)
def d2a_str(array_2d, func):
array_2d = ['{%s}'%d1a_str(array_1d, func) for array_1d in array_2d]
return ',\n'.join(array_2d)
import os
script_path = os.path.abspath(os.path.dirname(__file__))
work_path = os.path.dirname(script_path)
folium_path = os.path.join(work_path, 'cpp', 'folium')
template_path = os.path.join(script_path, 'template')
if not os.path.exists(template_path):
os.mkdir(template_path)
if __name__ == "__main__":
print work_path
print script_path
print folium_path
| Python |
#!/usr/bin/env python
#coding=utf-8
import os
import string
from consts import *
def u(x): return SquareDowns[x]
def d(x): return SquareUps[x]
def l(x): return SquareLefts[x]
def r(x): return SquareRights[x]
SquareDowns = [0]*91
SquareUps = [0]*91
SquareLefts = [0]*91
SquareRights = [0]*91
Xs = [9]*91
Ys = [10]*91
XYs = [[90]*16 for i in range(16)]
KnightLegs = [[90]*128 for i in range(91)]
BishopEyes = [[90]*128 for i in range(91)]
def info():
def _(x, y):
if x < 0 or x >8 or y < 0 or y > 9:
return 90
return x + 9 * y
for sq in range(90):
#x, y = sq % 9, sq / 9
y, x = divmod(sq, 9)
SquareDowns[sq] = _(x, y - 1)
SquareUps[sq] = _(x, y + 1)
SquareLefts[sq] = _(x - 1, y)
SquareRights[sq] = _(x + 1, y)
Xs[sq] = x
Ys[sq] = y
XYs[y][x] = sq
SquareDowns[90] = 90
SquareUps[90] = 90
SquareLefts[90] = 90
SquareRights[90] = 90
info()
def leg():
u = lambda s:SquareDowns[s]
d = lambda s:SquareUps[s]
l = lambda s:SquareLefts[s]
r = lambda s:SquareRights[s]
for src in range(90):
leg = u(src)
dst = l(u(leg))
if dst != 90: KnightLegs[src][dst] = leg
dst = r(u(leg))
if dst != 90: KnightLegs[src][dst] = leg
leg = d(src)
dst = l(d(leg))
if dst != 90: KnightLegs[src][dst] = leg
dst = r(d(leg))
if dst != 90: KnightLegs[src][dst] = leg
leg = l(src)
dst = u(l(leg))
if dst != 90: KnightLegs[src][dst] = leg
dst = d(l(leg))
if dst != 90: KnightLegs[src][dst] = leg
leg = r(src)
dst = u(r(leg))
if dst != 90: KnightLegs[src][dst] = leg
dst = d(r(leg))
if dst != 90: KnightLegs[src][dst] = leg
leg()
PF = [RedKingFlag]+[RedAdvisorFlag]*2+[RedBishopFlag]*2\
+[RedRookFlag]*2+[RedKnightFlag]*2+[RedCannonFlag]*2+[RedPawnFlag]*5\
+[BlackKingFlag]+[BlackAdvisorFlag]*2+[BlackBishopFlag]*2\
+[BlackRookFlag]*2+[BlackKnightFlag]*2+[BlackCannonFlag]*2+[BlackPawnFlag]*5\
+[EmptyFlag, InvaildFlag]
PT = [RedKing]+[RedAdvisor]*2+[RedBishop]*2+[RedRook]*2+[RedKnight]*2+[RedCannon]*2+[RedPawn]*5\
+[BlackKing]+[BlackAdvisor]*2+[BlackBishop]*2+[BlackRook]*2+[BlackKnight]*2+[BlackCannon]*2+[BlackPawn]*5\
+[EmptyType]+[InvalidType]
PC = [0]*16 + [1]*16 + [2] + [3]
def MoveFlags():
u = lambda s:SquareDowns[s]
d = lambda s:SquareUps[s]
l = lambda s:SquareLefts[s]
r = lambda s:SquareRights[s]
MoveFlags = [[0]*128 for i in range(91)]
for src in range(90):
sf = SquareFlags[src]
#red king
if sf & RedKingFlag:
for dst in [u(src), d(src), l(src), r(src)]:
if SquareFlags[dst] & RedKingFlag:
#这里加上兵的flag主要是为了可以区分和将见面的情况,下同
MoveFlags[dst][src] = MoveFlags[dst][src] | RedKingFlag | RedPawnFlag
#black king
elif sf & BlackKingFlag:
for dst in [u(src), d(src), l(src), r(src)]:
if SquareFlags[dst] & BlackKingFlag:
MoveFlags[dst][src] = MoveFlags[dst][src] | BlackKingFlag | BlackPawnFlag
#red advisor
if sf & RedAdvisorFlag:
for dst in [l(u(src)), l(d(src)), r(u(src)), r(d(src))]:
if SquareFlags[dst] & RedAdvisorFlag:
MoveFlags[dst][src] = MoveFlags[dst][src] | RedAdvisorFlag
#black advisor
elif sf & BlackAdvisorFlag:
for dst in [l(u(src)), l(d(src)), r(u(src)), r(d(src))]:
if SquareFlags[dst] & BlackAdvisorFlag:
MoveFlags[dst][src] = MoveFlags[dst][src] | BlackAdvisorFlag
#red bishop
elif sf & RedBishopFlag:
for dst in [l(l(u(u(src)))), l(l(d(d(src)))), r(r(u(u(src)))), r(r(d(d(src))))]:
if SquareFlags[dst] & RedBishopFlag:
MoveFlags[dst][src] = MoveFlags[dst][src] | RedBishopFlag
#black bishop
elif sf & BlackBishopFlag:
for dst in [l(l(u(u(src)))), l(l(d(d(src)))), r(r(u(u(src)))), r(r(d(d(src))))]:
if SquareFlags[dst] & BlackBishopFlag:
MoveFlags[dst][src] = MoveFlags[dst][src] | BlackBishopFlag
#knight
for dst in [l(u(u(src))), l(d(d(src))), r(u(u(src))), r(d(d(src))), l(l(u(src))), l(l(d(src))), r(r(u(src))), r(r(d(src)))]:
if dst in range(90):
MoveFlags[dst][src] = MoveFlags[dst][src] | RedKnightFlag | BlackKnightFlag
#red pawn
if sf & RedPawnFlag:
for dst in [l(src), r(src), d(src)]:
if SquareFlags[dst] & RedPawnFlag:
MoveFlags[dst][src] = MoveFlags[dst][src] | RedPawnFlag
#black pawn
if sf & BlackPawnFlag:
for dst in [l(src), r(src), u(src)]:
if SquareFlags[dst] & BlackPawnFlag:
MoveFlags[dst][src] = MoveFlags[dst][src] | BlackPawnFlag
for dst in range(90):
df = SquareFlags[dst]
if sf & RedKingFlag and df & BlackKingFlag and src%9 == dst%9:
MoveFlags[dst][src] = MoveFlags[dst][src] | RedKingFlag
elif sf & BlackKingFlag and df & RedKingFlag and src%9 == dst%9:
MoveFlags[dst][src] = MoveFlags[dst][src] | BlackKingFlag
#rook cannon
if src != dst:
if src%9 == dst%9 or src/9 == dst/9:
MoveFlags[dst][src] = MoveFlags[dst][src] | RedRookFlag | RedCannonFlag | BlackRookFlag | BlackCannonFlag
return MoveFlags
MoveFlags=MoveFlags()
def KnightMoves():
KnightMoves = [[23130]*16 for i in range(91)]
for sq in range(90):
ls = KnightMoves[sq]
leg = u(sq)
for dst in [l(u(leg)),r(u(leg))]:
if dst != 90:
ls[ls.index(23130)] = (leg << 8) | dst
leg = d(sq)
for dst in [l(d(leg)),r(d(leg))]:
if dst != 90:
ls[ls.index(23130)] = (leg << 8) | dst
leg = l(sq)
for dst in [u(l(leg)),d(l(leg))]:
if dst != 90:
ls[ls.index(23130)] = (leg << 8) | dst
leg = r(sq)
for dst in [u(r(leg)),d(r(leg))]:
if dst != 90:
ls[ls.index(23130)] = (leg << 8) | dst
return KnightMoves
KnightMoves = KnightMoves()
def RedKingPawnMoves():
RedKingPawnMoves = [[90]*8 for i in range(91)]
for sq in range(90):
Moves = RedKingPawnMoves[sq]
flag = SquareFlags[sq]
sqs = []
if flag & RedKingFlag:
sqs = [i for i in [u(sq), d(sq), l(sq), r(sq)] if SquareFlags[i] & RedKingFlag]
elif flag & RedPawnFlag:
sqs = [i for i in [d(sq), l(sq), r(sq)] if SquareFlags[i] & RedPawnFlag]
for sq in sqs:
Moves[Moves.index(90)] = sq
return RedKingPawnMoves
RedKingPawnMoves = RedKingPawnMoves()
def BlackKingPawnMoves():
BlackKingPawnMoves = [[90]*8 for i in range(91)]
for sq in range(90):
Moves = BlackKingPawnMoves[sq]
flag = SquareFlags[sq]
sqs = []
if flag & BlackKingFlag:
sqs = [i for i in [u(sq), d(sq), l(sq), r(sq)] if SquareFlags[i] & BlackKingFlag]
elif flag & BlackPawnFlag:
sqs = [i for i in [u(sq), l(sq), r(sq)] if SquareFlags[i] & BlackPawnFlag]
for sq in sqs:
Moves[Moves.index(90)] = sq
return BlackKingPawnMoves
BlackKingPawnMoves = BlackKingPawnMoves()
def AdvisorBishopMoves():
AdvisorBishopMoves = [[90]*8 for i in range(91)]
for sq in range(90):
Moves = AdvisorBishopMoves[sq]
flag = SquareFlags[sq]
if flag & BishopFlag:
for square in [u(u(r(r(sq)))), u(u(l(l(sq)))), d(d(r(r(sq)))), d(d(l(l(sq))))]:
if SquareFlags[square] & BishopFlag:
Moves[Moves.index(90)] = square
elif flag & AdvisorFlag:
for square in [u(l(sq)), u(r(sq)), d(l(sq)), d(r(sq))]:
if SquareFlags[square] & AdvisorFlag:
Moves[Moves.index(90)] = square
return AdvisorBishopMoves
AdvisorBishopMoves = AdvisorBishopMoves()
def main():
dict = {}
dict['xs'] = d1a_str(Xs, u32)
dict['ys'] = d1a_str(Ys, u32)
dict['xys'] = d2a_str(XYs, u32)
dict['downs'] = d1a_str(SquareDowns, u32)
dict['ups'] = d1a_str(SquareUps, u32)
dict['lefts'] = d1a_str(SquareLefts, u32)
dict['rights'] = d1a_str(SquareRights, u32)
dict['square_flags'] = d1a_str(SquareFlags, u32)
dict ['ptypes'] = d1a_str(PT, u32)
dict ['pflags'] = d1a_str(PF, u32)
dict ['pcolors'] = d1a_str(PC, u32)
dict ['mf'] = d2a_str(MoveFlags, u32)
dict ['kl'] = d2a_str(KnightLegs, u32)
dict['nm'] = d2a_str(KnightMoves, u32)
dict['rkpm'] = d2a_str(RedKingPawnMoves, u32)
dict['bkpm'] = d2a_str(BlackKingPawnMoves, u32)
dict['abm'] = d2a_str(AdvisorBishopMoves, u32)
template = open(os.path.join(template_path, 'xq_data.cpp.tmpl'), 'rb').read()
template = string.Template(template)
path = os.path.join(folium_path, 'xq_data.cpp')
open(path, 'wb').write(str(template.safe_substitute(dict)))
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/env python
#coding=utf-8
import os
import string
from consts import *
from xq_data import *
RedKingPawnValues = [0]*91
BlackKingPawnValues = [0]*91
AdvisorBishopValues = [0]*91
RedRookValues = [0]*91
BlackRookValues = [0]*91
RedKnightValues = [0]*91
BlackKnightValues = [0]*91
RedCannonValues = [0]*91
BlackCannonValues = [0]*91
def value():
KingBaseValue = 5000
AdvisorBaseValue = 40
BishopBaseValue = 40
RookBaseValue = 200
KnightBaseValue = 88
CannonBaseValue = 96
PawnBaseValue = 9
RedKingPawnPositionValues = [
0, 0, 0, 1, 5, 1, 0, 0, 0,
0, 0, 0, -8, -8, -8, 0, 0, 0,
0, 0, 0, -9, -9, -9, 0, 0, 0,
-2, 0, -2, 0, 6, 0, -2, 0, -2,
3, 0, 4, 0, 7, 0, 4, 0, 3,
10, 18, 22, 35, 40, 35, 22, 18, 10,
20, 27, 30, 40, 42, 40, 35, 27, 20,
20, 30, 45, 55, 55, 55, 45, 30, 20,
20, 30, 50, 65, 70, 65, 50, 30, 20,
0, 0, 0, 2, 4, 2, 0, 0, 0,]
RedAdvisorBishopPositionValues = [
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 3, 0, 0, 0, 0,
-2, 0, 0, 0, 3, 0, 0, 0, -2,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,]
RedRookPositionValues = [
-6, 6, 4, 12, 0, 12, 4, 6, -6,
5, 8, 6, 12, 0, 12, 6, 8, 5,
-2, 8, 4, 12, 12, 12, 4, 8, -2,
4, 9, 4, 12, 14, 12, 4, 9, 4,
8, 12, 12, 14, 15, 14, 12, 12, 8,
8, 11, 11, 14, 15, 14, 11, 11, 8,
6, 13, 13, 16, 16, 16, 13, 13, 6,
6, 8, 7, 14, 16, 14, 7, 8, 6,
6, 12, 9, 16, 33, 16, 9, 12, 6,
6, 8, 7, 13, 14, 13, 7, 8, 6,]
RedKnightPositionValues = [
0, -3, 2, 0, 2, 0, 2, -3, 0,
-3, 2, 4, 5, -10, 5, 4, 2, -3,
5, 4, 6, 7, 4, 7, 6, 4, 5,
4, 6, 10, 7, 10, 7, 10, 6, 4,
2, 10, 13, 14, 15, 14, 13, 10, 2,
2, 12, 11, 15, 16, 15, 11, 12, 2,
5, 20, 12, 19, 12, 19, 12, 20, 5,
4, 10, 11, 15, 11, 15, 11, 10, 4,
2, 8, 15, 9, 6, 9, 15, 8, 2,
2, 2, 2, 8, 2, 8, 2, 2, 2,]
RedCannonPositionValues = [
0, 0, 1, 3, 3, 3, 1, 0, 0,
0, 1, 2, 2, 2, 2, 2, 1, 0,
1, 0, 4, 3, 5, 3, 4, 0, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0,
-1, 0, 3, 0, 4, 0, 3, 0, -1,
0, 0, 0, 0, 4, 0, 0, 0, 0,
0, 3, 3, 2, 4, 2, 3, 3, 0,
1, 1, 0, -5, -4, -5, 0, 1, 1,
2, 2, 0, -4, -7, -4, 0, 2, 2,
4, 4, 0, -5, -6, -5, 0, 4, 4,]
for sq in range(90):
flag = SquareFlags[sq]
if flag & RedKingFlag:
RedKingPawnValues[sq] = KingBaseValue + RedKingPawnPositionValues[sq]
BlackKingPawnValues[89 - sq] = -RedKingPawnValues[sq]
if flag & RedAdvisorFlag:
AdvisorBishopValues[sq] = AdvisorBaseValue + RedAdvisorBishopPositionValues[sq]
AdvisorBishopValues[89 - sq] = -AdvisorBishopValues[sq]
if flag & RedBishopFlag:
AdvisorBishopValues[sq] = BishopBaseValue + RedAdvisorBishopPositionValues[sq]
AdvisorBishopValues[89 - sq] = -AdvisorBishopValues[sq]
RedRookValues[sq] = RookBaseValue + RedRookPositionValues[sq]
BlackRookValues[89 - sq] = -RedRookValues[sq]
RedKnightValues[sq] = KnightBaseValue + RedKnightPositionValues[sq]
BlackKnightValues[89 - sq] = -RedKnightValues[sq]
RedCannonValues[sq] = CannonBaseValue + RedCannonPositionValues[sq]
BlackCannonValues[89 - sq] = -RedCannonValues[sq]
if flag & RedPawnFlag:
RedKingPawnValues[sq] = PawnBaseValue + RedKingPawnPositionValues[sq]
BlackKingPawnValues[89 - sq] = -RedKingPawnValues[sq]
value()
RedKingPawnLocks = [0]*91
BlackKingPawnLocks = [0]*91
AdvisorBishopLocks = [0]*91
RedRookLocks = [0]*91
BlackRookLocks = [0]*91
RedKnightLocks = [0]*91
BlackKnightLocks = [0]*91
RedCannonLocks = [0]*91
BlackCannonLocks = [0]*91
RedKingPawnKeys = [0]*91
BlackKingPawnKeys = [0]*91
AdvisorBishopKeys = [0]*91
RedRookKeys = [0]*91
BlackRookKeys = [0]*91
RedKnightKeys = [0]*91
BlackKnightKeys = [0]*91
RedCannonKeys = [0]*91
BlackCannonKeys = [0]*91
def hash():
from random import randint, seed
seed(51)
for sq in range(90):
flag = SquareFlags[sq]
if flag & RedKingPawnFlag:
RedKingPawnLocks[sq] = randint(0, 0x10000000000000000)
RedKingPawnKeys[sq] = randint(0, 0x100000000)
BlackKingPawnLocks[89 - sq] = randint(0, 0x10000000000000000)
BlackKingPawnKeys[89 - sq] = randint(0, 0x100000000)
if flag & AdvisorBishopFlag:
AdvisorBishopLocks[sq] = randint(0, 0x10000000000000000)
AdvisorBishopKeys[sq] = randint(0, 0x100000000)
RedRookLocks[sq] = randint(0, 0x10000000000000000)
RedRookKeys[sq] = randint(0, 0x100000000)
BlackRookLocks[sq] = randint(0, 0x10000000000000000)
BlackRookKeys[sq] = randint(0, 0x100000000)
RedKnightLocks[sq] = randint(0, 0x10000000000000000)
RedKnightKeys[sq] = randint(0, 0x100000000)
BlackKnightLocks[sq] = randint(0, 0x10000000000000000)
BlackKnightKeys[sq] = randint(0, 0x100000000)
RedCannonLocks[sq] = randint(0, 0x10000000000000000)
RedCannonKeys[sq] = randint(0, 0x100000000)
BlackCannonLocks[sq] = randint(0, 0x10000000000000000)
BlackCannonKeys[sq] = randint(0, 0x100000000)
file = open('hash.data')
for seq in [RedKingPawnLocks,BlackKingPawnLocks,AdvisorBishopLocks,RedRookLocks,BlackRookLocks,RedKnightLocks,BlackKnightLocks,RedCannonLocks,BlackCannonLocks]:
for i in range(90):
i1 = int(file.readline())
i2 = int(file.readline())
seq[i] = (i1<<32)|i2
for seq in [RedKingPawnKeys,BlackKingPawnKeys,AdvisorBishopKeys,RedRookKeys,BlackRookKeys,RedKnightKeys,BlackKnightKeys,RedCannonKeys,BlackCannonKeys]:
for i in range(90):
seq[i] = int(file.readline())
hash()
def main():
dict = {}
dict['rkpl'] = d1a_str(RedKingPawnLocks, u64)
dict['rkpk'] = d1a_str(RedKingPawnKeys, u32)
dict['rkpv'] = d1a_str(RedKingPawnValues, s32)
dict['bkpl'] = d1a_str(BlackKingPawnLocks, u64)
dict['bkpk'] = d1a_str(BlackKingPawnKeys, u32)
dict['bkpv'] = d1a_str(BlackKingPawnValues, s32)
dict['abl'] = d1a_str(AdvisorBishopLocks, u64)
dict['abk'] = d1a_str(AdvisorBishopKeys, u32)
dict['abv'] = d1a_str(AdvisorBishopValues, s32)
dict['rrl'] = d1a_str(RedRookLocks, u64)
dict['rrk'] = d1a_str(RedRookKeys, u32)
dict['rrv'] = d1a_str(RedRookValues, s32)
dict['brl'] = d1a_str(BlackRookLocks, u64)
dict['brk'] = d1a_str(BlackRookKeys, u32)
dict['brv'] = d1a_str(BlackRookValues, s32)
dict['rnl'] = d1a_str(RedKnightLocks, u64)
dict['rnk'] = d1a_str(RedKnightKeys, u32)
dict['rnv'] = d1a_str(RedKnightValues, s32)
dict['bnl'] = d1a_str(BlackKnightLocks, u64)
dict['bnk'] = d1a_str(BlackKnightKeys, u32)
dict['bnv'] = d1a_str(BlackKnightValues, s32)
dict['rcl'] = d1a_str(RedCannonLocks, u64)
dict['rck'] = d1a_str(RedCannonKeys, u32)
dict['rcv'] = d1a_str(RedCannonValues, s32)
dict['bcl'] = d1a_str(BlackCannonLocks, u64)
dict['bck'] = d1a_str(BlackCannonKeys, u32)
dict['bcv'] = d1a_str(BlackCannonValues, s32)
PF = [RedKingFlag]+[RedAdvisorFlag]*2+[RedBishopFlag]*2\
+[RedRookFlag]*2+[RedKnightFlag]*2+[RedCannonFlag]*2+[RedPawnFlag]*5\
+[BlackKingFlag]+[BlackAdvisorFlag]*2+[BlackBishopFlag]*2\
+[BlackRookFlag]*2+[BlackKnightFlag]*2+[BlackCannonFlag]*2+[BlackPawnFlag]*5\
+[EmptyFlag, InvaildFlag]
PT = [RedKing]+[RedAdvisor]*2+[RedBishop]*2+[RedRook]*2+[RedKnight]*2+[RedCannon]*2+[RedPawn]*5\
+[BlackKing]+[BlackAdvisor]*2+[BlackBishop]*2+[BlackRook]*2+[BlackKnight]*2+[BlackCannon]*2+[BlackPawn]*5\
+[EmptyType]+[InvalidType]
PC = [0]*16 + [1]*16 + [2] + [3]
PL = ['s_red_king_pawn_locks']+['s_advisor_bishop_locks']*4+['s_red_rook_locks']*2+['s_red_knight_locks']*2\
+['s_red_cannon_locks']*2+['s_red_king_pawn_locks']*5\
+['s_black_king_pawn_locks']+['s_advisor_bishop_locks']*4+['s_black_rook_locks']*2+['s_black_knight_locks']*2\
+['s_black_cannon_locks']*2+['s_black_king_pawn_locks']*5
PK = ['s_red_king_pawn_keys']+['s_advisor_bishop_keys']*4+['s_red_rook_keys']*2+['s_red_knight_keys']*2\
+['s_red_cannon_keys']*2+['s_red_king_pawn_keys']*5\
+['s_black_king_pawn_keys']+['s_advisor_bishop_keys']*4+['s_black_rook_keys']*2+['s_black_knight_keys']*2\
+['s_black_cannon_keys']*2+['s_black_king_pawn_keys']*5
PV = ['s_red_king_pawn_values']+['s_advisor_bishop_values']*4+['s_red_rook_values']*2+['s_red_knight_values']*2\
+['s_red_cannon_values']*2+['s_red_king_pawn_values']*5\
+['s_black_king_pawn_values']+['s_advisor_bishop_values']*4+['s_black_rook_values']*2+['s_black_knight_values']*2\
+['s_black_cannon_values']*2+['s_black_king_pawn_values']*5
dict['plocks'] = d1a_str(PL, lambda x: x)
dict['pkeys'] = d1a_str(PK, lambda x: x)
dict['pvalues'] = d1a_str(PV, lambda x: x)
TL = ['s_red_king_pawn_locks']+['s_advisor_bishop_locks']*2\
+['s_red_rook_locks','s_red_knight_locks','s_red_cannon_locks','s_red_king_pawn_locks']\
+['s_black_king_pawn_locks']+['s_advisor_bishop_locks']*2\
+['s_black_rook_locks','s_black_knight_locks','s_black_cannon_locks','s_black_king_pawn_locks']
TK = ['s_red_king_pawn_keys']+['s_advisor_bishop_keys']*2\
+['s_red_rook_keys','s_red_knight_keys','s_red_cannon_keys','s_red_king_pawn_keys']\
+['s_black_king_pawn_keys']+['s_advisor_bishop_keys']*2\
+['s_black_rook_keys','s_black_knight_keys','s_black_cannon_keys','s_black_king_pawn_keys']
TV = ['s_red_king_pawn_values']+['s_advisor_bishop_values']*2\
+['s_red_rook_values','s_red_knight_values','s_red_cannon_values','s_red_king_pawn_values']\
+['s_black_king_pawn_values']+['s_advisor_bishop_values']*2\
+['s_black_rook_values','s_black_knight_values','s_black_cannon_values','s_black_king_pawn_values']
dict['tlocks'] = d1a_str(TL, lambda x: x)
dict['tkeys'] = d1a_str(TK, lambda x: x)
dict['tvalues'] = d1a_str(TV, lambda x: x)
#template = string.Template(template)
template = open(os.path.join(template_path, 'xq_position_data.cpp.tmpl'), 'rb').read()
template = string.Template(template)
path = os.path.join(folium_path, 'xq_position_data.cpp')
open(path, 'wb').write(str(template.safe_substitute(dict)))
if __name__ == "__main__":
main() | Python |
import os
import sys
if sys.platform == "win32":
cpppath = [r'D:\toolbox\boost_1_36_0', r'D:\Python26\include']
libpath = [r'D:\toolbox\boost_1_36_0\lib_x86\lib', r'D:\Python26\libs']
env = Environment(tools=['mingw'], CPPPATH=cpppath, LIBPATH=libpath)
ccflags = '-O3'
libs=['boost_python-mgw34-mt', 'python26']
else:
env = Environment()
ccflags = '-O3'
cppdefines = {'NDEBUG':None}
src = []
for root, dirs, files in os.walk('cpp'):
for file in files:
if file.endswith('.cpp'):
src.append(os.path.join(root, file))
folium = env.Program(
'folium',
src,
LIBS=libs,
CPPDEFINES = cppdefines,
CCFLAGS = ccflags)
| Python |
#coding=utf-8
class Mirror(object):
flags = range(4)
def __init__(self):
object.__init__(self)
self.m1_map = dict(zip('abcdefghi0123456789', 'ihgfedcba0123456789'))
self.m2_map = dict(zip('abcdefghi0123456789', 'ihgfedcba9876543210'))
def move(self, move, flag):
if flag&1:
move = ''.join(self.m1_map[c] for c in move)
if flag&2:
move = ''.join(self.m2_map[c] for c in move)
return move
def fen(self, fen, flag):
board, player = fen.split()[:2]
player = 'b' if player is 'b' else 'r'
if flag&1:
board = '/'.join(''.join(reversed(line)) for line in board.split('/'))
if flag&2:
board = ''.join(reversed(board.swapcase()))
player = 'r' if player is 'b' else 'b'
return '%s %s' % (board, player) | Python |
import os
import sys
import dbhash
import cPickle
import random
import mirror
class Reader(object):
def __init__(self):
bookfile = os.path.join(os.path.dirname(sys.argv[0]), 'snake.book')
self.book = dbhash.open(bookfile, 'r')
self.mirror = mirror.Mirror()
def flag(self, fen):
_ = []
for flag in self.mirror.flags:
new= self.mirror.fen(fen, flag)
if not new.endswith('b'):
_.append([new, flag])
_.sort()
return _[0] if _[0][0] >= _[1][0] else _[1]
def search(self, fen, bans):
fen, flag = self.flag(fen)
if not self.book.has_key(fen):
return
fen, moves = self.book.set_location(fen)
moves = cPickle.loads(moves)
moves = [(self.mirror.move(move, flag), moves[move]) for move in moves]
moves = [(move, score) for move, score in moves if move not in bans]
scores = sum(score for move, score in moves)
idx = random.randint(0, scores-1)
for move, score in moves:
if score > idx:
return move
idx = idx - score
| Python |
#!/usr/bin/env python
#coding=utf-8
def main():
import sys
if len(sys.argv) == 1:
import pyfolium.protocol
engine = pyfolium.protocol.Engine()
engine.run() | Python |
import os
import sys
import datetime
import time
import folium
import pipe
import pyfolium.book.reader
class Engine(folium.Engine):
def __init__(self):
folium.Engine.__init__(self)
self.book = pyfolium.book.reader.Reader()
self.logfile = None
logdir = os.path.join(os.path.dirname(sys.argv[0]), 'log')
if not os.path.exists(logdir):
os.mkdir(logdir)
for i in range(0, 256):
filename = os.path.join(logdir, '%s_%d.txt'%(datetime.date.today(), i))
if not os.path.exists(filename):
self.logfile = open(filename, 'w')
break
def writeline(self, line):
folium.Engine.writeline(self, line)
self.log("write line:%s" % line)
def readline(self):
if not self.readable():
return
line = folium.Engine.readline(self)
self.log("read line:%s" % line)
return line
def log(self, s):
if not self.logfile:
return
self.logfile.write("%s\n"%s)
# self.logfile.flush()
def __del__(self):
self.logfile.flush()
def run(self):
while not self.readable():
time.sleep(0.001)
line = self.readline()
if line != 'ucci':
return
self.writeline('id name folium')
self.writeline('id author Wangmao Lin')
self.writeline('id user engine tester')
self.writeline('option usemillisec type check default true')
self.usemillisec = True
self.writeline('ucciok')
self.bans = []
self.loop()
def loop(self):
while True:
while not self.readable():
time.sleep(0.001)
line = self.readline()
if line == 'isready':
self.writeline('readyok')
elif line == 'quit' or line == 'exit':
self.writeline('bye')
return
elif line.startswith('setoption '):
self.setoption(line[10:])
elif line.startswith('position '):
self.position(line[9:])
elif line.startswith('banmoves '):
self.banmoves(line[9:])
elif line.startswith('go'):
self.go(line)
elif line.startswith('probe'):
self.probe(line)
def position(self, position):
if " moves " in position:
position, moves = position.split(" moves ")
moves = moves.split()
else:
moves = []
if position.startswith("fen "):
fen = position[4:]
elif position == "startpos":
fen = "rnbakabnr/9/1c5c1/p1p1p1p1p/9/9/P1P1P1P1P/1C5C1/9/RNBAKABNR r"
self.load(fen)
for move in moves:
move = folium.ucci2move(move)
self.makemove(move)
self.bans = []
def setoption(self, option):
return
if option.startswith('usemillisec '):
self.usemillisec = (option[12:] == 'true')
elif option.startswith('debug'):
pass
def banmoves(self, moves):
self.bans = moves.split()
def go(self, line):
self.stop = False
self.ponder = False
self.draw = False
self.depth = 255
self.starttime = folium.time()
self.mintime = self.maxtime = self.starttime + 24*60*60
move = self.book.search(str(self), self.bans) if self.book else None
if move:
self.writeline("info book move: %s" % move)
self.writeline("info book search time: %f" % (folium.time() - self.starttime))
self.writeline("bestmove %s" % move)
return
if line.startswith("go ponder "):
self.ponder = True
line = line[10:]
elif line.startswith("go draw "):
self.draw = True
line = line[8:]
else:
line = line[2:]
if self.usemillisec:
propertime = limittime = float(24*3600*1000)
else:
propertime = limittime = float(24*3600)
parameters = line.split()
if parameters:
parameter = parameters[0]
if parameter == "depth":
self.ponder = False
parameter = parameters[1]
if parameter != "infinite":
self.depth = int(parameter)
elif parameter == "time":
propertime = limittime = totaltime = float(parameters[1])
parameters = parameters[2:]
while parameters:
parameter = parameters[0]
if parameter == "movestogo":
count = int(parameters[1])
propertime = totaltime/count
limittime = totaltime
elif parameter == "increment":
increment = int(parameters[1])
propertime = totaltime*0.05+increment
limittime = totaltime*0.5
parameters = parameters[2:]
limittime = min(propertime*1.618, limittime)
propertime = propertime*0.618
if self.usemillisec:
propertime = propertime * 0.001
limittime = limittime * 0.001
self.mintime = self.starttime + propertime
self.maxtime = self.starttime + limittime
move = self.search([folium.ucci2move(move) for move in self.bans])
if move:
self.writeline("bestmove %s" % folium.move2ucci(move))
else:
self.writeline("nobestmove") | Python |
#!/usr/bin/env python
#coding=utf-8
def main():
import sys
if len(sys.argv) == 1:
import pyfolium.protocol
engine = pyfolium.protocol.Engine()
engine.run() | Python |
#!/usr/bin/env python
#coding=utf-8
import os
import string
from consts import *
def main():
line_infos = [[0]*1024 for i in range(10)]
for idx in range(10):
for flag in range(1024):
flag |= 0xFC00
p1 = (idx and [idx-1] or [0xF])[0]
while not flag & (1 << p1):
p1 = (p1 and [p1-1] or [0xF])[0]
p2 = (p1 and [p1-1] or [0xF])[0]
while not flag & (1 << p2):
p2 = (p2 and [p2-1] or [0xF])[0]
n1 = idx + 1
while not flag & (1 << n1):
n1 += 1
n2 = n1 + 1
while not flag & (1 << n2):
n2 += 1
line_infos[idx][flag & 1023] = p1 | (p2 << 4) | (n1 << 8) | (n2 << 12)
bits = [1 << i for i in range(10)]
bit_counts = [len([j for j in bits if i & j])for i in range(1024)]
distance_infos = [[(19 << 10 | 1023)]*128 for i in range(91)]
for src in range(90):
sy, sx = divmod(src, 9)
for dst in range(90):
if dst == src:
continue
dy, dx = divmod(dst, 9)
if dx == sx:
idx = dx+10
mask = sum(bits[i] for i in set(range(dy+1, sy)+range(sy+1, dy)) if i in range(10))
distance_infos[src][dst] = (idx << 10) | mask
elif dy == sy:
idx = dy
mask = sum(bits[i] for i in set(range(dx+1, sx)+range(sx+1, dx)) if i in range(10))
distance_infos[src][dst] = (idx << 10) | mask
dict = {}
dict['infos'] = d2a_str(line_infos, u32)
dict['counts'] = d1a_str(bit_counts, u32)
dict['distance'] = d2a_str(distance_infos, u32)
template = open(os.path.join(template_path, 'bitmap_data.cpp.tmpl'), 'rb').read()
template = string.Template(template)
path = os.path.join(folium_path, 'bitmap_data.cpp')
open(path, 'wb').write(str(template.safe_substitute(dict)))
if __name__ == "__main__":
main()
| Python |
import xq_data
xq_data.main()
import engine_data
engine_data.main()
import history_data
history_data.main()
import bitmap_data
bitmap_data.main()
| Python |
#!/usr/bin/env python
#coding=utf-8
import os
import string
from consts import *
from xq_data import *
RedKingPawnValues = [0]*91
BlackKingPawnValues = [0]*91
AdvisorBishopValues = [0]*91
RedRookValues = [0]*91
BlackRookValues = [0]*91
RedKnightValues = [0]*91
BlackKnightValues = [0]*91
RedCannonValues = [0]*91
BlackCannonValues = [0]*91
def value():
KingBaseValue = 5000
AdvisorBaseValue = 40
BishopBaseValue = 40
RookBaseValue = 200
KnightBaseValue = 88
CannonBaseValue = 96
PawnBaseValue = 9
RedKingPawnPositionValues = [
0, 0, 0, 1, 5, 1, 0, 0, 0,
0, 0, 0, -8, -8, -8, 0, 0, 0,
0, 0, 0, -9, -9, -9, 0, 0, 0,
-2, 0, -2, 0, 6, 0, -2, 0, -2,
3, 0, 4, 0, 7, 0, 4, 0, 3,
10, 18, 22, 35, 40, 35, 22, 18, 10,
20, 27, 30, 40, 42, 40, 35, 27, 20,
20, 30, 45, 55, 55, 55, 45, 30, 20,
20, 30, 50, 65, 70, 65, 50, 30, 20,
0, 0, 0, 2, 4, 2, 0, 0, 0,]
RedAdvisorBishopPositionValues = [
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 3, 0, 0, 0, 0,
-2, 0, 0, 0, 3, 0, 0, 0, -2,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,]
RedRookPositionValues = [
-6, 6, 4, 12, 0, 12, 4, 6, -6,
5, 8, 6, 12, 0, 12, 6, 8, 5,
-2, 8, 4, 12, 12, 12, 4, 8, -2,
4, 9, 4, 12, 14, 12, 4, 9, 4,
8, 12, 12, 14, 15, 14, 12, 12, 8,
8, 11, 11, 14, 15, 14, 11, 11, 8,
6, 13, 13, 16, 16, 16, 13, 13, 6,
6, 8, 7, 14, 16, 14, 7, 8, 6,
6, 12, 9, 16, 33, 16, 9, 12, 6,
6, 8, 7, 13, 14, 13, 7, 8, 6,]
RedKnightPositionValues = [
0, -3, 2, 0, 2, 0, 2, -3, 0,
-3, 2, 4, 5, -10, 5, 4, 2, -3,
5, 4, 6, 7, 4, 7, 6, 4, 5,
4, 6, 10, 7, 10, 7, 10, 6, 4,
2, 10, 13, 14, 15, 14, 13, 10, 2,
2, 12, 11, 15, 16, 15, 11, 12, 2,
5, 20, 12, 19, 12, 19, 12, 20, 5,
4, 10, 11, 15, 11, 15, 11, 10, 4,
2, 8, 15, 9, 6, 9, 15, 8, 2,
2, 2, 2, 8, 2, 8, 2, 2, 2,]
RedCannonPositionValues = [
0, 0, 1, 3, 3, 3, 1, 0, 0,
0, 1, 2, 2, 2, 2, 2, 1, 0,
1, 0, 4, 3, 5, 3, 4, 0, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0,
-1, 0, 3, 0, 4, 0, 3, 0, -1,
0, 0, 0, 0, 4, 0, 0, 0, 0,
0, 3, 3, 2, 4, 2, 3, 3, 0,
1, 1, 0, -5, -4, -5, 0, 1, 1,
2, 2, 0, -4, -7, -4, 0, 2, 2,
4, 4, 0, -5, -6, -5, 0, 4, 4,]
for sq in range(90):
flag = SquareFlags[sq]
if flag & RedKingFlag:
RedKingPawnValues[sq] = KingBaseValue + RedKingPawnPositionValues[sq]
BlackKingPawnValues[89 - sq] = -RedKingPawnValues[sq]
if flag & RedAdvisorFlag:
AdvisorBishopValues[sq] = AdvisorBaseValue + RedAdvisorBishopPositionValues[sq]
AdvisorBishopValues[89 - sq] = -AdvisorBishopValues[sq]
if flag & RedBishopFlag:
AdvisorBishopValues[sq] = BishopBaseValue + RedAdvisorBishopPositionValues[sq]
AdvisorBishopValues[89 - sq] = -AdvisorBishopValues[sq]
RedRookValues[sq] = RookBaseValue + RedRookPositionValues[sq]
BlackRookValues[89 - sq] = -RedRookValues[sq]
RedKnightValues[sq] = KnightBaseValue + RedKnightPositionValues[sq]
BlackKnightValues[89 - sq] = -RedKnightValues[sq]
RedCannonValues[sq] = CannonBaseValue + RedCannonPositionValues[sq]
BlackCannonValues[89 - sq] = -RedCannonValues[sq]
if flag & RedPawnFlag:
RedKingPawnValues[sq] = PawnBaseValue + RedKingPawnPositionValues[sq]
BlackKingPawnValues[89 - sq] = -RedKingPawnValues[sq]
value()
RedKingPawnLocks = [0]*91
BlackKingPawnLocks = [0]*91
AdvisorBishopLocks = [0]*91
RedRookLocks = [0]*91
BlackRookLocks = [0]*91
RedKnightLocks = [0]*91
BlackKnightLocks = [0]*91
RedCannonLocks = [0]*91
BlackCannonLocks = [0]*91
RedKingPawnKeys = [0]*91
BlackKingPawnKeys = [0]*91
AdvisorBishopKeys = [0]*91
RedRookKeys = [0]*91
BlackRookKeys = [0]*91
RedKnightKeys = [0]*91
BlackKnightKeys = [0]*91
RedCannonKeys = [0]*91
BlackCannonKeys = [0]*91
def hash():
from random import randint, seed
seed(51)
for sq in range(90):
flag = SquareFlags[sq]
if flag & RedKingPawnFlag:
RedKingPawnLocks[sq] = randint(0, 0x10000000000000000)
RedKingPawnKeys[sq] = randint(0, 0x100000000)
BlackKingPawnLocks[89 - sq] = randint(0, 0x10000000000000000)
BlackKingPawnKeys[89 - sq] = randint(0, 0x100000000)
if flag & AdvisorBishopFlag:
AdvisorBishopLocks[sq] = randint(0, 0x10000000000000000)
AdvisorBishopKeys[sq] = randint(0, 0x100000000)
RedRookLocks[sq] = randint(0, 0x10000000000000000)
RedRookKeys[sq] = randint(0, 0x100000000)
BlackRookLocks[sq] = randint(0, 0x10000000000000000)
BlackRookKeys[sq] = randint(0, 0x100000000)
RedKnightLocks[sq] = randint(0, 0x10000000000000000)
RedKnightKeys[sq] = randint(0, 0x100000000)
BlackKnightLocks[sq] = randint(0, 0x10000000000000000)
BlackKnightKeys[sq] = randint(0, 0x100000000)
RedCannonLocks[sq] = randint(0, 0x10000000000000000)
RedCannonKeys[sq] = randint(0, 0x100000000)
BlackCannonLocks[sq] = randint(0, 0x10000000000000000)
BlackCannonKeys[sq] = randint(0, 0x100000000)
file = open('hash.data')
for seq in [RedKingPawnLocks,BlackKingPawnLocks,AdvisorBishopLocks,RedRookLocks,BlackRookLocks,RedKnightLocks,BlackKnightLocks,RedCannonLocks,BlackCannonLocks]:
for i in range(90):
i1 = int(file.readline())
i2 = int(file.readline())
seq[i] = (i1<<32)|i2
for seq in [RedKingPawnKeys,BlackKingPawnKeys,AdvisorBishopKeys,RedRookKeys,BlackRookKeys,RedKnightKeys,BlackKnightKeys,RedCannonKeys,BlackCannonKeys]:
for i in range(90):
seq[i] = int(file.readline())
hash()
def main():
dict = {}
dict['rkpl'] = d1a_str(RedKingPawnLocks, u64)
dict['rkpk'] = d1a_str(RedKingPawnKeys, u32)
dict['rkpv'] = d1a_str(RedKingPawnValues, s32)
dict['bkpl'] = d1a_str(BlackKingPawnLocks, u64)
dict['bkpk'] = d1a_str(BlackKingPawnKeys, u32)
dict['bkpv'] = d1a_str(BlackKingPawnValues, s32)
dict['abl'] = d1a_str(AdvisorBishopLocks, u64)
dict['abk'] = d1a_str(AdvisorBishopKeys, u32)
dict['abv'] = d1a_str(AdvisorBishopValues, s32)
dict['rrl'] = d1a_str(RedRookLocks, u64)
dict['rrk'] = d1a_str(RedRookKeys, u32)
dict['rrv'] = d1a_str(RedRookValues, s32)
dict['brl'] = d1a_str(BlackRookLocks, u64)
dict['brk'] = d1a_str(BlackRookKeys, u32)
dict['brv'] = d1a_str(BlackRookValues, s32)
dict['rnl'] = d1a_str(RedKnightLocks, u64)
dict['rnk'] = d1a_str(RedKnightKeys, u32)
dict['rnv'] = d1a_str(RedKnightValues, s32)
dict['bnl'] = d1a_str(BlackKnightLocks, u64)
dict['bnk'] = d1a_str(BlackKnightKeys, u32)
dict['bnv'] = d1a_str(BlackKnightValues, s32)
dict['rcl'] = d1a_str(RedCannonLocks, u64)
dict['rck'] = d1a_str(RedCannonKeys, u32)
dict['rcv'] = d1a_str(RedCannonValues, s32)
dict['bcl'] = d1a_str(BlackCannonLocks, u64)
dict['bck'] = d1a_str(BlackCannonKeys, u32)
dict['bcv'] = d1a_str(BlackCannonValues, s32)
PF = [RedKingFlag]+[RedAdvisorFlag]*2+[RedBishopFlag]*2\
+[RedRookFlag]*2+[RedKnightFlag]*2+[RedCannonFlag]*2+[RedPawnFlag]*5\
+[BlackKingFlag]+[BlackAdvisorFlag]*2+[BlackBishopFlag]*2\
+[BlackRookFlag]*2+[BlackKnightFlag]*2+[BlackCannonFlag]*2+[BlackPawnFlag]*5\
+[EmptyFlag, InvaildFlag]
PT = [RedKing]+[RedAdvisor]*2+[RedBishop]*2+[RedRook]*2+[RedKnight]*2+[RedCannon]*2+[RedPawn]*5\
+[BlackKing]+[BlackAdvisor]*2+[BlackBishop]*2+[BlackRook]*2+[BlackKnight]*2+[BlackCannon]*2+[BlackPawn]*5\
+[EmptyType]+[InvalidType]
PC = [0]*16 + [1]*16 + [2] + [3]
PL = ['s_red_king_pawn_locks']+['s_advisor_bishop_locks']*4+['s_red_rook_locks']*2+['s_red_knight_locks']*2\
+['s_red_cannon_locks']*2+['s_red_king_pawn_locks']*5\
+['s_black_king_pawn_locks']+['s_advisor_bishop_locks']*4+['s_black_rook_locks']*2+['s_black_knight_locks']*2\
+['s_black_cannon_locks']*2+['s_black_king_pawn_locks']*5
PK = ['s_red_king_pawn_keys']+['s_advisor_bishop_keys']*4+['s_red_rook_keys']*2+['s_red_knight_keys']*2\
+['s_red_cannon_keys']*2+['s_red_king_pawn_keys']*5\
+['s_black_king_pawn_keys']+['s_advisor_bishop_keys']*4+['s_black_rook_keys']*2+['s_black_knight_keys']*2\
+['s_black_cannon_keys']*2+['s_black_king_pawn_keys']*5
PV = ['s_red_king_pawn_values']+['s_advisor_bishop_values']*4+['s_red_rook_values']*2+['s_red_knight_values']*2\
+['s_red_cannon_values']*2+['s_red_king_pawn_values']*5\
+['s_black_king_pawn_values']+['s_advisor_bishop_values']*4+['s_black_rook_values']*2+['s_black_knight_values']*2\
+['s_black_cannon_values']*2+['s_black_king_pawn_values']*5
dict['plocks'] = d1a_str(PL, lambda x: x)
dict['pkeys'] = d1a_str(PK, lambda x: x)
dict['pvalues'] = d1a_str(PV, lambda x: x)
TL = ['s_red_king_pawn_locks']+['s_advisor_bishop_locks']*2\
+['s_red_rook_locks','s_red_knight_locks','s_red_cannon_locks','s_red_king_pawn_locks']\
+['s_black_king_pawn_locks']+['s_advisor_bishop_locks']*2\
+['s_black_rook_locks','s_black_knight_locks','s_black_cannon_locks','s_black_king_pawn_locks']
TK = ['s_red_king_pawn_keys']+['s_advisor_bishop_keys']*2\
+['s_red_rook_keys','s_red_knight_keys','s_red_cannon_keys','s_red_king_pawn_keys']\
+['s_black_king_pawn_keys']+['s_advisor_bishop_keys']*2\
+['s_black_rook_keys','s_black_knight_keys','s_black_cannon_keys','s_black_king_pawn_keys']
TV = ['s_red_king_pawn_values']+['s_advisor_bishop_values']*2\
+['s_red_rook_values','s_red_knight_values','s_red_cannon_values','s_red_king_pawn_values']\
+['s_black_king_pawn_values']+['s_advisor_bishop_values']*2\
+['s_black_rook_values','s_black_knight_values','s_black_cannon_values','s_black_king_pawn_values']
dict['tlocks'] = d1a_str(TL, lambda x: x)
dict['tkeys'] = d1a_str(TK, lambda x: x)
dict['tvalues'] = d1a_str(TV, lambda x: x)
#template = string.Template(template)
template = open(os.path.join(template_path, 'engine_data.cpp.tmpl'), 'rb').read()
template = string.Template(template)
path = os.path.join(folium_path, 'engine_data.cpp')
open(path, 'wb').write(str(template.safe_substitute(dict)))
if __name__ == "__main__":
main() | Python |
#!/usr/bin/env python
#coding=utf-8
import os
import string
from consts import *
from xq_data import *
def capture_scores():
capture_scores = [[0]*32 for i in range(33)]
e = [10000, 1041, 1040, 2000, 1088, 1096, 1020]
m = [1000, 41, 40, 200, 88, 96, 20]
def level(src_type, dst_type): return levels[src_type][dst_type]
def color(piece): return PC[piece]
def type(piece):
t = PT[piece]
if t >= 7:
t -= 7
return t
for src_piece in range(32):
for dst_piece in range(32):
if color(src_piece) != color(dst_piece):
src_type = type(src_piece)
dst_type = type(dst_piece)
capture_scores[dst_piece][src_piece] = e[dst_type] - m[src_type] + 1 << 17
return capture_scores
capture_scores = capture_scores()
def main():
dict = {}
dict['scores'] = d2a_str(capture_scores, u32)
template = open(os.path.join(template_path, 'history_data.cpp.tmpl'), 'rb').read()
template = string.Template(template)
path = os.path.join(folium_path, 'history_data.cpp')
open(path, 'wb').write(str(template.safe_substitute(dict)))
if __name__ == "__main__":
main() | Python |
#!/usr/bin/env python
#coding=utf-8
import os
import string
from consts import *
def main():
line_infos = [[0]*1024 for i in range(10)]
for idx in range(10):
for flag in range(1024):
flag |= 0xFC00
p1 = (idx and [idx-1] or [0xF])[0]
while not flag & (1 << p1):
p1 = (p1 and [p1-1] or [0xF])[0]
p2 = (p1 and [p1-1] or [0xF])[0]
while not flag & (1 << p2):
p2 = (p2 and [p2-1] or [0xF])[0]
n1 = idx + 1
while not flag & (1 << n1):
n1 += 1
n2 = n1 + 1
while not flag & (1 << n2):
n2 += 1
line_infos[idx][flag & 1023] = p1 | (p2 << 4) | (n1 << 8) | (n2 << 12)
bits = [1 << i for i in range(10)]
bit_counts = [len([j for j in bits if i & j])for i in range(1024)]
distance_infos = [[(19 << 10 | 1023)]*128 for i in range(91)]
for src in range(90):
sy, sx = divmod(src, 9)
for dst in range(90):
if dst == src:
continue
dy, dx = divmod(dst, 9)
if dx == sx:
idx = dx+10
mask = sum(bits[i] for i in set(range(dy+1, sy)+range(sy+1, dy)) if i in range(10))
distance_infos[src][dst] = (idx << 10) | mask
elif dy == sy:
idx = dy
mask = sum(bits[i] for i in set(range(dx+1, sx)+range(sx+1, dx)) if i in range(10))
distance_infos[src][dst] = (idx << 10) | mask
dict = {}
dict['infos'] = d2a_str(line_infos, u32)
dict['counts'] = d1a_str(bit_counts, u32)
dict['distance'] = d2a_str(distance_infos, u32)
template = open(os.path.join(template_path, 'bitmap_data.cpp.tmpl'), 'rb').read()
template = string.Template(template)
path = os.path.join(folium_path, 'bitmap_data.cpp')
open(path, 'wb').write(str(template.safe_substitute(dict)))
if __name__ == "__main__":
main()
| Python |
RedKing = 0;
RedAdvisor = 1;
RedBishop = 2;
RedRook = 3;
RedKnight = 4;
RedCannon = 5;
RedPawn = 6;
BlackKing = 7;
BlackAdvisor = 8;
BlackBishop = 9;
BlackRook = 10;
BlackKnight = 11;
BlackCannon = 12;
BlackPawn = 13;
EmptyType = 14;
InvalidType = 15;
RedKingFlag = 1 << 0;
RedAdvisorFlag = 1 << 1;
RedBishopFlag = 1 << 2;
RedRookFlag = 1 << 3;
RedKnightFlag = 1 << 4;
RedCannonFlag = 1 << 5;
RedPawnFlag = 1 << 6;
BlackKingFlag = 1 << 7;
BlackAdvisorFlag = 1 << 8;
BlackBishopFlag = 1 << 9;
BlackRookFlag = 1 << 10;
BlackKnightFlag = 1 << 11;
BlackCannonFlag = 1 << 12;
BlackPawnFlag = 1 << 13;
EmptyFlag = 1 << 14;
InvaildFlag = 1 << 15;
AdvisorFlag = RedAdvisorFlag | BlackAdvisorFlag
BishopFlag = RedBishopFlag | BlackBishopFlag
RedKingPawnFlag = RedKingFlag | RedPawnFlag
AdvisorBishopFlag = RedAdvisorFlag | RedBishopFlag | BlackAdvisorFlag | BlackBishopFlag
RedKingSquares = [x + y * 9 for x, y in [(3, 0), (4, 0), (5, 0), (3, 1), (4, 1), (5, 1), (3, 2), (4, 2), (5, 2)]]
RedAdvisorSquares = [x + y * 9 for x, y in [(3,0), (5,0), (4, 1), (3,2), (5,2)]]
RedBishopSquares = [x + y * 9 for x, y in [(2, 0), (6, 0), (0, 2), (4, 2), (8, 2), (2, 4), (6, 4)]]
RedRookSquares = range(90)
RedKnightSquares = range(90)
RedCannonSquares = range(90)
RedPawnSquares = [x + y * 9 for x, y in [(0, 3), (2, 3), (4, 3), (6, 3), (8, 3), (0, 4), (2, 4), (4, 4), (6, 4), (8, 4)]]
RedPawnSquares.extend(range(45, 90))
BlackKingSquares = [89 - sq for sq in RedKingSquares]
BlackAdvisorSquares = [89 - sq for sq in RedAdvisorSquares]
BlackBishopSquares = [89 - sq for sq in RedBishopSquares]
BlackRookSquares = [89 - sq for sq in RedRookSquares]
BlackKnightSquares = [89 - sq for sq in RedKnightSquares]
BlackCannonSquares = [89 - sq for sq in RedCannonSquares]
BlackPawnSquares = [89 - sq for sq in RedPawnSquares]
def SquareFlags():
SquareFlags = [0]*91
for sq in RedKingSquares:
SquareFlags[sq] |= RedKingFlag
SquareFlags[89 - sq] |= BlackKingFlag
for sq in RedAdvisorSquares:
SquareFlags[sq] |= RedAdvisorFlag
SquareFlags[89 - sq] |= BlackAdvisorFlag
for sq in RedBishopSquares:
SquareFlags[sq] |= RedBishopFlag
SquareFlags[89 - sq] |= BlackBishopFlag
for sq in RedPawnSquares:
SquareFlags[sq] |= RedPawnFlag
SquareFlags[89 - sq] |= BlackPawnFlag
for sq in range(90):
SquareFlags[sq] |= RedRookFlag
SquareFlags[sq] |= RedKnightFlag
SquareFlags[sq] |= RedCannonFlag
SquareFlags[sq] |= BlackRookFlag
SquareFlags[sq] |= BlackKnightFlag
SquareFlags[sq] |= BlackCannonFlag
SquareFlags[sq] |= EmptyFlag
SquareFlags[90] |= InvaildFlag
return SquareFlags
SquareFlags = SquareFlags()
def u64(i):
return str(i)+'ULL'
def u32(i):
return str(i)+'UL'
def s32(i):
return str(i)+'L'
def d1a_str(array_1d, func):
array_1d = [func(i) for i in array_1d]
return ', '.join(array_1d)
def d2a_str(array_2d, func):
array_2d = ['{%s}'%d1a_str(array_1d, func) for array_1d in array_2d]
return ',\n'.join(array_2d)
import os
script_path = os.path.abspath(os.path.dirname(__file__))
work_path = os.path.dirname(script_path)
folium_path = os.path.join(work_path, 'src')
template_path = os.path.join(script_path, 'template')
if not os.path.exists(template_path):
os.mkdir(template_path)
if __name__ == "__main__":
print work_path
print script_path
print folium_path
| Python |
#!/usr/bin/env python
#coding=utf-8
import os
import string
from consts import *
def u(x): return SquareUps[x]
def d(x): return SquareDowns[x]
def l(x): return SquareLefts[x]
def r(x): return SquareRights[x]
SquareUps = [0]*91
SquareDowns = [0]*91
SquareLefts = [0]*91
SquareRights = [0]*91
Xs = [9]*91
Ys = [10]*91
XYs = [[90]*16 for i in range(16)]
KnightLegs = [[90]*128 for i in range(91)]
BishopEyes = [[90]*128 for i in range(91)]
def info():
def _(x, y):
if x < 0 or x >8 or y < 0 or y > 9:
return 90
return x + 9 * y
for sq in range(90):
#x, y = sq % 9, sq / 9
y, x = divmod(sq, 9)
SquareUps[sq] = _(x, y - 1)
SquareDowns[sq] = _(x, y + 1)
SquareLefts[sq] = _(x - 1, y)
SquareRights[sq] = _(x + 1, y)
Xs[sq] = x
Ys[sq] = y
XYs[y][x] = sq
SquareUps[90] = 90
SquareDowns[90] = 90
SquareLefts[90] = 90
SquareRights[90] = 90
info()
def leg():
u = lambda s:SquareUps[s]
d = lambda s:SquareDowns[s]
l = lambda s:SquareLefts[s]
r = lambda s:SquareRights[s]
for src in range(90):
leg = u(src)
dst = l(u(leg))
if dst != 90: KnightLegs[src][dst] = leg
dst = r(u(leg))
if dst != 90: KnightLegs[src][dst] = leg
leg = d(src)
dst = l(d(leg))
if dst != 90: KnightLegs[src][dst] = leg
dst = r(d(leg))
if dst != 90: KnightLegs[src][dst] = leg
leg = l(src)
dst = u(l(leg))
if dst != 90: KnightLegs[src][dst] = leg
dst = d(l(leg))
if dst != 90: KnightLegs[src][dst] = leg
leg = r(src)
dst = u(r(leg))
if dst != 90: KnightLegs[src][dst] = leg
dst = d(r(leg))
if dst != 90: KnightLegs[src][dst] = leg
leg()
PF = [RedKingFlag]+[RedAdvisorFlag]*2+[RedBishopFlag]*2\
+[RedRookFlag]*2+[RedKnightFlag]*2+[RedCannonFlag]*2+[RedPawnFlag]*5\
+[BlackKingFlag]+[BlackAdvisorFlag]*2+[BlackBishopFlag]*2\
+[BlackRookFlag]*2+[BlackKnightFlag]*2+[BlackCannonFlag]*2+[BlackPawnFlag]*5\
+[EmptyFlag, InvaildFlag]
PT = [RedKing]+[RedAdvisor]*2+[RedBishop]*2+[RedRook]*2+[RedKnight]*2+[RedCannon]*2+[RedPawn]*5\
+[BlackKing]+[BlackAdvisor]*2+[BlackBishop]*2+[BlackRook]*2+[BlackKnight]*2+[BlackCannon]*2+[BlackPawn]*5\
+[EmptyType]+[InvalidType]
PC = [0]*16 + [1]*16 + [2] + [3]
def MoveFlags():
u = lambda s:SquareUps[s]
d = lambda s:SquareDowns[s]
l = lambda s:SquareLefts[s]
r = lambda s:SquareRights[s]
MoveFlags = [[0]*128 for i in range(91)]
for src in range(90):
sf = SquareFlags[src]
#red king
if sf & RedKingFlag:
for dst in [u(src), d(src), l(src), r(src)]:
if SquareFlags[dst] & RedKingFlag:
#这里加上兵的flag主要是为了可以区分和将见面的情况,下同
MoveFlags[dst][src] = MoveFlags[dst][src] | RedKingFlag | RedPawnFlag
#black king
elif sf & BlackKingFlag:
for dst in [u(src), d(src), l(src), r(src)]:
if SquareFlags[dst] & BlackKingFlag:
MoveFlags[dst][src] = MoveFlags[dst][src] | BlackKingFlag | BlackPawnFlag
#red advisor
if sf & RedAdvisorFlag:
for dst in [l(u(src)), l(d(src)), r(u(src)), r(d(src))]:
if SquareFlags[dst] & RedAdvisorFlag:
MoveFlags[dst][src] = MoveFlags[dst][src] | RedAdvisorFlag
#black advisor
elif sf & BlackAdvisorFlag:
for dst in [l(u(src)), l(d(src)), r(u(src)), r(d(src))]:
if SquareFlags[dst] & BlackAdvisorFlag:
MoveFlags[dst][src] = MoveFlags[dst][src] | BlackAdvisorFlag
#red bishop
elif sf & RedBishopFlag:
for dst in [l(l(u(u(src)))), l(l(d(d(src)))), r(r(u(u(src)))), r(r(d(d(src))))]:
if SquareFlags[dst] & RedBishopFlag:
MoveFlags[dst][src] = MoveFlags[dst][src] | RedBishopFlag
#black bishop
elif sf & BlackBishopFlag:
for dst in [l(l(u(u(src)))), l(l(d(d(src)))), r(r(u(u(src)))), r(r(d(d(src))))]:
if SquareFlags[dst] & BlackBishopFlag:
MoveFlags[dst][src] = MoveFlags[dst][src] | BlackBishopFlag
#knight
for dst in [l(u(u(src))), l(d(d(src))), r(u(u(src))), r(d(d(src))), l(l(u(src))), l(l(d(src))), r(r(u(src))), r(r(d(src)))]:
if dst in range(90):
MoveFlags[dst][src] = MoveFlags[dst][src] | RedKnightFlag | BlackKnightFlag
#red pawn
if sf & RedPawnFlag:
for dst in [l(src), r(src), d(src)]:
if SquareFlags[dst] & RedPawnFlag:
MoveFlags[dst][src] = MoveFlags[dst][src] | RedPawnFlag
#black pawn
if sf & BlackPawnFlag:
for dst in [l(src), r(src), u(src)]:
if SquareFlags[dst] & BlackPawnFlag:
MoveFlags[dst][src] = MoveFlags[dst][src] | BlackPawnFlag
for dst in range(90):
df = SquareFlags[dst]
if sf & RedKingFlag and df & BlackKingFlag and src%9 == dst%9:
MoveFlags[dst][src] = MoveFlags[dst][src] | RedKingFlag
elif sf & BlackKingFlag and df & RedKingFlag and src%9 == dst%9:
MoveFlags[dst][src] = MoveFlags[dst][src] | BlackKingFlag
#rook cannon
if src != dst:
if src%9 == dst%9 or src/9 == dst/9:
MoveFlags[dst][src] = MoveFlags[dst][src] | RedRookFlag | RedCannonFlag | BlackRookFlag | BlackCannonFlag
return MoveFlags
MoveFlags=MoveFlags()
def KnightMoves():
KnightMoves = [[23130]*16 for i in range(91)]
for sq in range(90):
ls = KnightMoves[sq]
leg = u(sq)
for dst in [l(u(leg)),r(u(leg))]:
if dst != 90:
ls[ls.index(23130)] = (leg << 8) | dst
leg = d(sq)
for dst in [l(d(leg)),r(d(leg))]:
if dst != 90:
ls[ls.index(23130)] = (leg << 8) | dst
leg = l(sq)
for dst in [u(l(leg)),d(l(leg))]:
if dst != 90:
ls[ls.index(23130)] = (leg << 8) | dst
leg = r(sq)
for dst in [u(r(leg)),d(r(leg))]:
if dst != 90:
ls[ls.index(23130)] = (leg << 8) | dst
return KnightMoves
KnightMoves = KnightMoves()
def RedKingPawnMoves():
RedKingPawnMoves = [[90]*8 for i in range(91)]
for sq in range(90):
Moves = RedKingPawnMoves[sq]
flag = SquareFlags[sq]
sqs = []
if flag & RedKingFlag:
sqs = [i for i in [u(sq), d(sq), l(sq), r(sq)] if SquareFlags[i] & RedKingFlag]
elif flag & RedPawnFlag:
sqs = [i for i in [d(sq), l(sq), r(sq)] if SquareFlags[i] & RedPawnFlag]
for sq in sqs:
Moves[Moves.index(90)] = sq
return RedKingPawnMoves
RedKingPawnMoves = RedKingPawnMoves()
def BlackKingPawnMoves():
BlackKingPawnMoves = [[90]*8 for i in range(91)]
for sq in range(90):
Moves = BlackKingPawnMoves[sq]
flag = SquareFlags[sq]
sqs = []
if flag & BlackKingFlag:
sqs = [i for i in [u(sq), d(sq), l(sq), r(sq)] if SquareFlags[i] & BlackKingFlag]
elif flag & BlackPawnFlag:
sqs = [i for i in [u(sq), l(sq), r(sq)] if SquareFlags[i] & BlackPawnFlag]
for sq in sqs:
Moves[Moves.index(90)] = sq
return BlackKingPawnMoves
BlackKingPawnMoves = BlackKingPawnMoves()
def AdvisorBishopMoves():
AdvisorBishopMoves = [[90]*8 for i in range(91)]
for sq in range(90):
Moves = AdvisorBishopMoves[sq]
flag = SquareFlags[sq]
if flag & BishopFlag:
for square in [u(u(r(r(sq)))), u(u(l(l(sq)))), d(d(r(r(sq)))), d(d(l(l(sq))))]:
if SquareFlags[square] & BishopFlag:
Moves[Moves.index(90)] = square
elif flag & AdvisorFlag:
for square in [u(l(sq)), u(r(sq)), d(l(sq)), d(r(sq))]:
if SquareFlags[square] & AdvisorFlag:
Moves[Moves.index(90)] = square
return AdvisorBishopMoves
AdvisorBishopMoves = AdvisorBishopMoves()
def main():
dict = {}
dict['xs'] = d1a_str(Xs, u32)
dict['ys'] = d1a_str(Ys, u32)
dict['xys'] = d2a_str(XYs, u32)
dict['ups'] = d1a_str(SquareUps, u32)
dict['downs'] = d1a_str(SquareDowns, u32)
dict['lefts'] = d1a_str(SquareLefts, u32)
dict['rights'] = d1a_str(SquareRights, u32)
dict['square_flags'] = d1a_str(SquareFlags, u32)
dict ['ptypes'] = d1a_str(PT, u32)
dict ['pflags'] = d1a_str(PF, u32)
dict ['pcolors'] = d1a_str(PC, u32)
dict ['mf'] = d2a_str(MoveFlags, u32)
dict ['kl'] = d2a_str(KnightLegs, u32)
dict['nm'] = d2a_str(KnightMoves, u32)
dict['rkpm'] = d2a_str(RedKingPawnMoves, u32)
dict['bkpm'] = d2a_str(BlackKingPawnMoves, u32)
dict['abm'] = d2a_str(AdvisorBishopMoves, u32)
template = open(os.path.join(template_path, 'xq_data.cpp.tmpl'), 'rb').read()
template = string.Template(template)
path = os.path.join(folium_path, 'xq_data.cpp')
open(path, 'wb').write(str(template.safe_substitute(dict)))
if __name__ == "__main__":
main()
| Python |
import sys
cpp_path = [r'D:\toolbox\boost_1_35_0']
lib_path = ['#bin', r'D:\toolbox\boost_1_35_0\stage\lib']
BuildDir('build', 'src', duplicate=0)
env = Environment(CPPPATH=cpp_path, LIBPATH=lib_path)
if sys.platform == "win32":
if 1:
env.Tool('mingw')
ccflag = '-O3'
else:
env.Tool('icl')
ccflag = '/Ox /MD'
else:
ccflag = '-O3'
defines = {'NDEBUG':None}
src = ['build/engine_data.cpp',
'build/move_gen.cpp',
'build/xq_data.cpp',
'build/bitmap_data.cpp',
'build/generator.cpp',
'build/hash.cpp',
'build/search.cpp',
'build/engine.cpp',
'build/history_data.cpp',
'build/xq.cpp',
'build/move.cpp',
'build/qianhong/qianhong.cpp']
folium = env.Program(
'folium',
src,
LIBS=['boost_thread-mgw34-mt'],
CPPDEFINES = defines,
CCFLAGS = ccflag)
| Python |
import xq_data
xq_data.main()
import engine_data
engine_data.main()
import history_data
history_data.main()
import bitlines_data
bitlines_data.main()
| Python |
#!/usr/bin/env python
#coding=utf-8
import os
import string
from consts import *
from xq_data import *
RedKingPawnValues = [0]*91
BlackKingPawnValues = [0]*91
AdvisorBishopValues = [0]*91
RedRookValues = [0]*91
BlackRookValues = [0]*91
RedKnightValues = [0]*91
BlackKnightValues = [0]*91
RedCannonValues = [0]*91
BlackCannonValues = [0]*91
def value():
KingBaseValue = 5000
AdvisorBaseValue = 40
BishopBaseValue = 40
RookBaseValue = 200
KnightBaseValue = 88
CannonBaseValue = 96
PawnBaseValue = 9
RedKingPawnPositionValues = [
0, 0, 0, 1, 5, 1, 0, 0, 0,
0, 0, 0, -8, -8, -8, 0, 0, 0,
0, 0, 0, -9, -9, -9, 0, 0, 0,
-2, 0, -2, 0, 6, 0, -2, 0, -2,
3, 0, 4, 0, 7, 0, 4, 0, 3,
10, 18, 22, 35, 40, 35, 22, 18, 10,
20, 27, 30, 40, 42, 40, 35, 27, 20,
20, 30, 45, 55, 55, 55, 45, 30, 20,
20, 30, 50, 65, 70, 65, 50, 30, 20,
0, 0, 0, 2, 4, 2, 0, 0, 0,]
RedAdvisorBishopPositionValues = [
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 3, 0, 0, 0, 0,
-2, 0, 0, 0, 3, 0, 0, 0, -2,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,]
RedRookPositionValues = [
-6, 6, 4, 12, 0, 12, 4, 6, -6,
5, 8, 6, 12, 0, 12, 6, 8, 5,
-2, 8, 4, 12, 12, 12, 4, 8, -2,
4, 9, 4, 12, 14, 12, 4, 9, 4,
8, 12, 12, 14, 15, 14, 12, 12, 8,
8, 11, 11, 14, 15, 14, 11, 11, 8,
6, 13, 13, 16, 16, 16, 13, 13, 6,
6, 8, 7, 14, 16, 14, 7, 8, 6,
6, 12, 9, 16, 33, 16, 9, 12, 6,
6, 8, 7, 13, 14, 13, 7, 8, 6,]
RedKnightPositionValues = [
0, -3, 2, 0, 2, 0, 2, -3, 0,
-3, 2, 4, 5, -10, 5, 4, 2, -3,
5, 4, 6, 7, 4, 7, 6, 4, 5,
4, 6, 10, 7, 10, 7, 10, 6, 4,
2, 10, 13, 14, 15, 14, 13, 10, 2,
2, 12, 11, 15, 16, 15, 11, 12, 2,
5, 20, 12, 19, 12, 19, 12, 20, 5,
4, 10, 11, 15, 11, 15, 11, 10, 4,
2, 8, 15, 9, 6, 9, 15, 8, 2,
2, 2, 2, 8, 2, 8, 2, 2, 2,]
RedCannonPositionValues = [
0, 0, 1, 3, 3, 3, 1, 0, 0,
0, 1, 2, 2, 2, 2, 2, 1, 0,
1, 0, 4, 3, 5, 3, 4, 0, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0,
-1, 0, 3, 0, 4, 0, 3, 0, -1,
0, 0, 0, 0, 4, 0, 0, 0, 0,
0, 3, 3, 2, 4, 2, 3, 3, 0,
1, 1, 0, -5, -4, -5, 0, 1, 1,
2, 2, 0, -4, -7, -4, 0, 2, 2,
4, 4, 0, -5, -6, -5, 0, 4, 4,]
for sq in range(90):
flag = SquareFlags[sq]
if flag & RedKingFlag:
RedKingPawnValues[sq] = KingBaseValue + RedKingPawnPositionValues[sq]
BlackKingPawnValues[89 - sq] = -RedKingPawnValues[sq]
if flag & RedAdvisorFlag:
AdvisorBishopValues[sq] = AdvisorBaseValue + RedAdvisorBishopPositionValues[sq]
AdvisorBishopValues[89 - sq] = -AdvisorBishopValues[sq]
if flag & RedBishopFlag:
AdvisorBishopValues[sq] = BishopBaseValue + RedAdvisorBishopPositionValues[sq]
AdvisorBishopValues[89 - sq] = -AdvisorBishopValues[sq]
RedRookValues[sq] = RookBaseValue + RedRookPositionValues[sq]
BlackRookValues[89 - sq] = -RedRookValues[sq]
RedKnightValues[sq] = KnightBaseValue + RedKnightPositionValues[sq]
BlackKnightValues[89 - sq] = -RedKnightValues[sq]
RedCannonValues[sq] = CannonBaseValue + RedCannonPositionValues[sq]
BlackCannonValues[89 - sq] = -RedCannonValues[sq]
if flag & RedPawnFlag:
RedKingPawnValues[sq] = PawnBaseValue + RedKingPawnPositionValues[sq]
BlackKingPawnValues[89 - sq] = -RedKingPawnValues[sq]
value()
RedKingPawnLocks = [0]*91
BlackKingPawnLocks = [0]*91
AdvisorBishopLocks = [0]*91
RedRookLocks = [0]*91
BlackRookLocks = [0]*91
RedKnightLocks = [0]*91
BlackKnightLocks = [0]*91
RedCannonLocks = [0]*91
BlackCannonLocks = [0]*91
RedKingPawnKeys = [0]*91
BlackKingPawnKeys = [0]*91
AdvisorBishopKeys = [0]*91
RedRookKeys = [0]*91
BlackRookKeys = [0]*91
RedKnightKeys = [0]*91
BlackKnightKeys = [0]*91
RedCannonKeys = [0]*91
BlackCannonKeys = [0]*91
def hash():
from random import randint, seed
seed(51)
for sq in range(90):
flag = SquareFlags[sq]
if flag & RedKingPawnFlag:
RedKingPawnLocks[sq] = randint(0, 0x10000000000000000)
RedKingPawnKeys[sq] = randint(0, 0x100000000)
BlackKingPawnLocks[89 - sq] = randint(0, 0x10000000000000000)
BlackKingPawnKeys[89 - sq] = randint(0, 0x100000000)
if flag & AdvisorBishopFlag:
AdvisorBishopLocks[sq] = randint(0, 0x10000000000000000)
AdvisorBishopKeys[sq] = randint(0, 0x100000000)
RedRookLocks[sq] = randint(0, 0x10000000000000000)
RedRookKeys[sq] = randint(0, 0x100000000)
BlackRookLocks[sq] = randint(0, 0x10000000000000000)
BlackRookKeys[sq] = randint(0, 0x100000000)
RedKnightLocks[sq] = randint(0, 0x10000000000000000)
RedKnightKeys[sq] = randint(0, 0x100000000)
BlackKnightLocks[sq] = randint(0, 0x10000000000000000)
BlackKnightKeys[sq] = randint(0, 0x100000000)
RedCannonLocks[sq] = randint(0, 0x10000000000000000)
RedCannonKeys[sq] = randint(0, 0x100000000)
BlackCannonLocks[sq] = randint(0, 0x10000000000000000)
BlackCannonKeys[sq] = randint(0, 0x100000000)
file = open('hash.data')
for seq in [RedKingPawnLocks,BlackKingPawnLocks,AdvisorBishopLocks,RedRookLocks,BlackRookLocks,RedKnightLocks,BlackKnightLocks,RedCannonLocks,BlackCannonLocks]:
for i in range(90):
i1 = int(file.readline())
i2 = int(file.readline())
seq[i] = (i1<<32)|i2
for seq in [RedKingPawnKeys,BlackKingPawnKeys,AdvisorBishopKeys,RedRookKeys,BlackRookKeys,RedKnightKeys,BlackKnightKeys,RedCannonKeys,BlackCannonKeys]:
for i in range(90):
seq[i] = int(file.readline())
hash()
def main():
dict = {}
dict['rkpl'] = d1a_str(RedKingPawnLocks, u64)
dict['rkpk'] = d1a_str(RedKingPawnKeys, u32)
dict['rkpv'] = d1a_str(RedKingPawnValues, s32)
dict['bkpl'] = d1a_str(BlackKingPawnLocks, u64)
dict['bkpk'] = d1a_str(BlackKingPawnKeys, u32)
dict['bkpv'] = d1a_str(BlackKingPawnValues, s32)
dict['abl'] = d1a_str(AdvisorBishopLocks, u64)
dict['abk'] = d1a_str(AdvisorBishopKeys, u32)
dict['abv'] = d1a_str(AdvisorBishopValues, s32)
dict['rrl'] = d1a_str(RedRookLocks, u64)
dict['rrk'] = d1a_str(RedRookKeys, u32)
dict['rrv'] = d1a_str(RedRookValues, s32)
dict['brl'] = d1a_str(BlackRookLocks, u64)
dict['brk'] = d1a_str(BlackRookKeys, u32)
dict['brv'] = d1a_str(BlackRookValues, s32)
dict['rnl'] = d1a_str(RedKnightLocks, u64)
dict['rnk'] = d1a_str(RedKnightKeys, u32)
dict['rnv'] = d1a_str(RedKnightValues, s32)
dict['bnl'] = d1a_str(BlackKnightLocks, u64)
dict['bnk'] = d1a_str(BlackKnightKeys, u32)
dict['bnv'] = d1a_str(BlackKnightValues, s32)
dict['rcl'] = d1a_str(RedCannonLocks, u64)
dict['rck'] = d1a_str(RedCannonKeys, u32)
dict['rcv'] = d1a_str(RedCannonValues, s32)
dict['bcl'] = d1a_str(BlackCannonLocks, u64)
dict['bck'] = d1a_str(BlackCannonKeys, u32)
dict['bcv'] = d1a_str(BlackCannonValues, s32)
PF = [RedKingFlag]+[RedAdvisorFlag]*2+[RedBishopFlag]*2\
+[RedRookFlag]*2+[RedKnightFlag]*2+[RedCannonFlag]*2+[RedPawnFlag]*5\
+[BlackKingFlag]+[BlackAdvisorFlag]*2+[BlackBishopFlag]*2\
+[BlackRookFlag]*2+[BlackKnightFlag]*2+[BlackCannonFlag]*2+[BlackPawnFlag]*5\
+[EmptyFlag, InvaildFlag]
PT = [RedKing]+[RedAdvisor]*2+[RedBishop]*2+[RedRook]*2+[RedKnight]*2+[RedCannon]*2+[RedPawn]*5\
+[BlackKing]+[BlackAdvisor]*2+[BlackBishop]*2+[BlackRook]*2+[BlackKnight]*2+[BlackCannon]*2+[BlackPawn]*5\
+[EmptyType]+[InvalidType]
PC = [0]*16 + [1]*16 + [2] + [3]
PL = ['s_red_king_pawn_locks']+['s_advisor_bishop_locks']*4+['s_red_rook_locks']*2+['s_red_knight_locks']*2\
+['s_red_cannon_locks']*2+['s_red_king_pawn_locks']*5\
+['s_black_king_pawn_locks']+['s_advisor_bishop_locks']*4+['s_black_rook_locks']*2+['s_black_knight_locks']*2\
+['s_black_cannon_locks']*2+['s_black_king_pawn_locks']*5
PK = ['s_red_king_pawn_keys']+['s_advisor_bishop_keys']*4+['s_red_rook_keys']*2+['s_red_knight_keys']*2\
+['s_red_cannon_keys']*2+['s_red_king_pawn_keys']*5\
+['s_black_king_pawn_keys']+['s_advisor_bishop_keys']*4+['s_black_rook_keys']*2+['s_black_knight_keys']*2\
+['s_black_cannon_keys']*2+['s_black_king_pawn_keys']*5
PV = ['s_red_king_pawn_values']+['s_advisor_bishop_values']*4+['s_red_rook_values']*2+['s_red_knight_values']*2\
+['s_red_cannon_values']*2+['s_red_king_pawn_values']*5\
+['s_black_king_pawn_values']+['s_advisor_bishop_values']*4+['s_black_rook_values']*2+['s_black_knight_values']*2\
+['s_black_cannon_values']*2+['s_black_king_pawn_values']*5
dict['plocks'] = d1a_str(PL, lambda x: x)
dict['pkeys'] = d1a_str(PK, lambda x: x)
dict['pvalues'] = d1a_str(PV, lambda x: x)
TL = ['s_red_king_pawn_locks']+['s_advisor_bishop_locks']*2\
+['s_red_rook_locks','s_red_knight_locks','s_red_cannon_locks','s_red_king_pawn_locks']\
+['s_black_king_pawn_locks']+['s_advisor_bishop_locks']*2\
+['s_black_rook_locks','s_black_knight_locks','s_black_cannon_locks','s_black_king_pawn_locks']
TK = ['s_red_king_pawn_keys']+['s_advisor_bishop_keys']*2\
+['s_red_rook_keys','s_red_knight_keys','s_red_cannon_keys','s_red_king_pawn_keys']\
+['s_black_king_pawn_keys']+['s_advisor_bishop_keys']*2\
+['s_black_rook_keys','s_black_knight_keys','s_black_cannon_keys','s_black_king_pawn_keys']
TV = ['s_red_king_pawn_values']+['s_advisor_bishop_values']*2\
+['s_red_rook_values','s_red_knight_values','s_red_cannon_values','s_red_king_pawn_values']\
+['s_black_king_pawn_values']+['s_advisor_bishop_values']*2\
+['s_black_rook_values','s_black_knight_values','s_black_cannon_values','s_black_king_pawn_values']
dict['tlocks'] = d1a_str(TL, lambda x: x)
dict['tkeys'] = d1a_str(TK, lambda x: x)
dict['tvalues'] = d1a_str(TV, lambda x: x)
#template = string.Template(template)
template = open(os.path.join(template_path, 'engine_data.cpp.tmpl'), 'rb').read()
template = string.Template(template)
path = os.path.join(folium_path, 'engine_data.cpp')
open(path, 'wb').write(str(template.safe_substitute(dict)))
if __name__ == "__main__":
main() | Python |
#!/usr/bin/env python
#coding=utf-8
import os
import string
from consts import *
from xq_data import *
def capture_scores():
capture_scores = [[0]*32 for i in range(33)]
e = [10000, 1041, 1040, 2000, 1088, 1096, 1020]
m = [1000, 41, 40, 200, 88, 96, 20]
def level(src_type, dst_type): return levels[src_type][dst_type]
def color(piece): return PC[piece]
def type(piece):
t = PT[piece]
if t >= 7:
t -= 7
return t
for src_piece in range(32):
for dst_piece in range(32):
if color(src_piece) != color(dst_piece):
src_type = type(src_piece)
dst_type = type(dst_piece)
capture_scores[dst_piece][src_piece] = e[dst_type] - m[src_type] + 1 << 17
return capture_scores
capture_scores = capture_scores()
def main():
dict = {}
dict['scores'] = d2a_str(capture_scores, u32)
template = open(os.path.join(template_path, 'history_data.cpp.tmpl'), 'rb').read()
template = string.Template(template)
path = os.path.join(folium_path, 'history_data.cpp')
open(path, 'wb').write(str(template.safe_substitute(dict)))
if __name__ == "__main__":
main() | Python |
#!/usr/bin/env python
#coding=utf-8
import os
import string
from consts import *
def main():
line_infos = [[0]*1024 for i in range(10)]
for idx in range(10):
for flag in range(1024):
flag |= 0xFC00
p1 = (idx and [idx-1] or [0xF])[0]
while not flag & (1 << p1):
p1 = (p1 and [p1-1] or [0xF])[0]
p2 = (p1 and [p1-1] or [0xF])[0]
while not flag & (1 << p2):
p2 = (p2 and [p2-1] or [0xF])[0]
n1 = idx + 1
while not flag & (1 << n1):
n1 += 1
n2 = n1 + 1
while not flag & (1 << n2):
n2 += 1
line_infos[idx][flag & 1023] = p1 | (p2 << 4) | (n1 << 8) | (n2 << 12)
bits = [1 << i for i in range(10)]
bit_counts = [len([j for j in bits if i & j])for i in range(1024)]
distance_infos = [[(19 << 10 | 1023)]*128 for i in range(91)]
for src in range(90):
sy, sx = divmod(src, 9)
for dst in range(90):
if dst == src:
continue
dy, dx = divmod(dst, 9)
if dx == sx:
idx = dx+10
mask = sum(bits[i] for i in set(range(dy+1, sy)+range(sy+1, dy)) if i in range(10))
distance_infos[src][dst] = (idx << 10) | mask
elif dy == sy:
idx = dy
mask = sum(bits[i] for i in set(range(dx+1, sx)+range(sx+1, dx)) if i in range(10))
distance_infos[src][dst] = (idx << 10) | mask
dict = {}
dict['infos'] = d2a_str(line_infos, u32)
dict['counts'] = d1a_str(bit_counts, u32)
dict['distance'] = d2a_str(distance_infos, u32)
template = open(os.path.join(template_path, 'bitlines_data.cpp.tmpl'), 'rb').read()
template = string.Template(template)
path = os.path.join(folium_path, 'bitlines_data.cpp')
open(path, 'wb').write(str(template.safe_substitute(dict)))
if __name__ == "__main__":
main()
| Python |
RedKing = 0;
RedAdvisor = 1;
RedBishop = 2;
RedRook = 3;
RedKnight = 4;
RedCannon = 5;
RedPawn = 6;
BlackKing = 7;
BlackAdvisor = 8;
BlackBishop = 9;
BlackRook = 10;
BlackKnight = 11;
BlackCannon = 12;
BlackPawn = 13;
EmptyType = 14;
InvalidType = 15;
RedKingFlag = 1 << 0;
RedAdvisorFlag = 1 << 1;
RedBishopFlag = 1 << 2;
RedRookFlag = 1 << 3;
RedKnightFlag = 1 << 4;
RedCannonFlag = 1 << 5;
RedPawnFlag = 1 << 6;
BlackKingFlag = 1 << 7;
BlackAdvisorFlag = 1 << 8;
BlackBishopFlag = 1 << 9;
BlackRookFlag = 1 << 10;
BlackKnightFlag = 1 << 11;
BlackCannonFlag = 1 << 12;
BlackPawnFlag = 1 << 13;
EmptyFlag = 1 << 14;
InvaildFlag = 1 << 15;
AdvisorFlag = RedAdvisorFlag | BlackAdvisorFlag
BishopFlag = RedBishopFlag | BlackBishopFlag
RedKingPawnFlag = RedKingFlag | RedPawnFlag
AdvisorBishopFlag = RedAdvisorFlag | RedBishopFlag | BlackAdvisorFlag | BlackBishopFlag
RedKingSquares = [x + y * 9 for x, y in [(3, 0), (4, 0), (5, 0), (3, 1), (4, 1), (5, 1), (3, 2), (4, 2), (5, 2)]]
RedAdvisorSquares = [x + y * 9 for x, y in [(3,0), (5,0), (4, 1), (3,2), (5,2)]]
RedBishopSquares = [x + y * 9 for x, y in [(2, 0), (6, 0), (0, 2), (4, 2), (8, 2), (2, 4), (6, 4)]]
RedRookSquares = range(90)
RedKnightSquares = range(90)
RedCannonSquares = range(90)
RedPawnSquares = [x + y * 9 for x, y in [(0, 3), (2, 3), (4, 3), (6, 3), (8, 3), (0, 4), (2, 4), (4, 4), (6, 4), (8, 4)]]
RedPawnSquares.extend(range(45, 90))
BlackKingSquares = [89 - sq for sq in RedKingSquares]
BlackAdvisorSquares = [89 - sq for sq in RedAdvisorSquares]
BlackBishopSquares = [89 - sq for sq in RedBishopSquares]
BlackRookSquares = [89 - sq for sq in RedRookSquares]
BlackKnightSquares = [89 - sq for sq in RedKnightSquares]
BlackCannonSquares = [89 - sq for sq in RedCannonSquares]
BlackPawnSquares = [89 - sq for sq in RedPawnSquares]
def SquareFlags():
SquareFlags = [0]*91
for sq in RedKingSquares:
SquareFlags[sq] |= RedKingFlag
SquareFlags[89 - sq] |= BlackKingFlag
for sq in RedAdvisorSquares:
SquareFlags[sq] |= RedAdvisorFlag
SquareFlags[89 - sq] |= BlackAdvisorFlag
for sq in RedBishopSquares:
SquareFlags[sq] |= RedBishopFlag
SquareFlags[89 - sq] |= BlackBishopFlag
for sq in RedPawnSquares:
SquareFlags[sq] |= RedPawnFlag
SquareFlags[89 - sq] |= BlackPawnFlag
for sq in range(90):
SquareFlags[sq] |= RedRookFlag
SquareFlags[sq] |= RedKnightFlag
SquareFlags[sq] |= RedCannonFlag
SquareFlags[sq] |= BlackRookFlag
SquareFlags[sq] |= BlackKnightFlag
SquareFlags[sq] |= BlackCannonFlag
SquareFlags[sq] |= EmptyFlag
SquareFlags[90] |= InvaildFlag
return SquareFlags
SquareFlags = SquareFlags()
def u64(i):
return str(i)+'ULL'
def u32(i):
return str(i)+'UL'
def s32(i):
return str(i)+'L'
def d1a_str(array_1d, func):
array_1d = [func(i) for i in array_1d]
return ', '.join(array_1d)
def d2a_str(array_2d, func):
array_2d = ['{%s}'%d1a_str(array_1d, func) for array_1d in array_2d]
return ',\n'.join(array_2d)
import os
script_path = os.path.abspath(os.path.dirname(__file__))
work_path = os.path.dirname(script_path)
folium_path = os.path.join(work_path, 'src')
template_path = os.path.join(script_path, 'template')
if not os.path.exists(template_path):
os.mkdir(template_path)
if __name__ == "__main__":
print work_path
print script_path
print folium_path
| Python |
#!/usr/bin/env python
#coding=utf-8
import os
import string
from consts import *
def u(x): return SquareUps[x]
def d(x): return SquareDowns[x]
def l(x): return SquareLefts[x]
def r(x): return SquareRights[x]
SquareUps = [0]*91
SquareDowns = [0]*91
SquareLefts = [0]*91
SquareRights = [0]*91
Xs = [9]*91
Ys = [10]*91
XYs = [[90]*16 for i in range(16)]
KnightLegs = [[90]*128 for i in range(91)]
BishopEyes = [[90]*128 for i in range(91)]
def info():
def _(x, y):
if x < 0 or x >8 or y < 0 or y > 9:
return 90
return x + 9 * y
for sq in range(90):
#x, y = sq % 9, sq / 9
y, x = divmod(sq, 9)
SquareUps[sq] = _(x, y - 1)
SquareDowns[sq] = _(x, y + 1)
SquareLefts[sq] = _(x - 1, y)
SquareRights[sq] = _(x + 1, y)
Xs[sq] = x
Ys[sq] = y
XYs[y][x] = sq
SquareUps[90] = 90
SquareDowns[90] = 90
SquareLefts[90] = 90
SquareRights[90] = 90
info()
def leg():
u = lambda s:SquareUps[s]
d = lambda s:SquareDowns[s]
l = lambda s:SquareLefts[s]
r = lambda s:SquareRights[s]
for src in range(90):
leg = u(src)
dst = l(u(leg))
if dst != 90: KnightLegs[src][dst] = leg
dst = r(u(leg))
if dst != 90: KnightLegs[src][dst] = leg
leg = d(src)
dst = l(d(leg))
if dst != 90: KnightLegs[src][dst] = leg
dst = r(d(leg))
if dst != 90: KnightLegs[src][dst] = leg
leg = l(src)
dst = u(l(leg))
if dst != 90: KnightLegs[src][dst] = leg
dst = d(l(leg))
if dst != 90: KnightLegs[src][dst] = leg
leg = r(src)
dst = u(r(leg))
if dst != 90: KnightLegs[src][dst] = leg
dst = d(r(leg))
if dst != 90: KnightLegs[src][dst] = leg
leg()
def eye():
u = lambda s:SquareUps[s]
d = lambda s:SquareDowns[s]
l = lambda s:SquareLefts[s]
r = lambda s:SquareRights[s]
for src in range(90):
if not (SquareFlags[src] & BishopFlag):
continue
dst = u(u(l(l(src))))
if (SquareFlags[dst] & BishopFlag):BishopEyes[src][dst] = (src + dst)/2
dst = u(u(r(r(src))))
if (SquareFlags[dst] & BishopFlag):BishopEyes[src][dst] = (src + dst)/2
dst = d(d(l(l(src))))
if (SquareFlags[dst] & BishopFlag):BishopEyes[src][dst] = (src + dst)/2
dst = d(d(r(r(src))))
if (SquareFlags[dst] & BishopFlag):BishopEyes[src][dst] = (src + dst)/2
eye()
PF = [RedKingFlag]+[RedAdvisorFlag]*2+[RedBishopFlag]*2\
+[RedRookFlag]*2+[RedKnightFlag]*2+[RedCannonFlag]*2+[RedPawnFlag]*5\
+[BlackKingFlag]+[BlackAdvisorFlag]*2+[BlackBishopFlag]*2\
+[BlackRookFlag]*2+[BlackKnightFlag]*2+[BlackCannonFlag]*2+[BlackPawnFlag]*5\
+[EmptyFlag, InvaildFlag]
PT = [RedKing]+[RedAdvisor]*2+[RedBishop]*2+[RedRook]*2+[RedKnight]*2+[RedCannon]*2+[RedPawn]*5\
+[BlackKing]+[BlackAdvisor]*2+[BlackBishop]*2+[BlackRook]*2+[BlackKnight]*2+[BlackCannon]*2+[BlackPawn]*5\
+[EmptyType]+[InvalidType]
PC = [0]*16 + [1]*16 + [2] + [3]
def KnightMoves():
KnightMoves = [[23130]*16 for i in range(91)]
for sq in range(90):
ls = KnightMoves[sq]
leg = u(sq)
for dst in [l(u(leg)),r(u(leg))]:
if dst != 90:
ls[ls.index(23130)] = (leg << 8) | dst
leg = d(sq)
for dst in [l(d(leg)),r(d(leg))]:
if dst != 90:
ls[ls.index(23130)] = (leg << 8) | dst
leg = l(sq)
for dst in [u(l(leg)),d(l(leg))]:
if dst != 90:
ls[ls.index(23130)] = (leg << 8) | dst
leg = r(sq)
for dst in [u(r(leg)),d(r(leg))]:
if dst != 90:
ls[ls.index(23130)] = (leg << 8) | dst
return KnightMoves
KnightMoves = KnightMoves()
def RedKingPawnMoves():
RedKingPawnMoves = [[90]*8 for i in range(91)]
for sq in range(90):
Moves = RedKingPawnMoves[sq]
flag = SquareFlags[sq]
sqs = []
if flag & RedKingFlag:
sqs = [i for i in [u(sq), d(sq), l(sq), r(sq)] if SquareFlags[i] & RedKingFlag]
elif flag & RedPawnFlag:
sqs = [i for i in [d(sq), l(sq), r(sq)] if SquareFlags[i] & RedPawnFlag]
for sq in sqs:
Moves[Moves.index(90)] = sq
return RedKingPawnMoves
RedKingPawnMoves = RedKingPawnMoves()
def BlackKingPawnMoves():
BlackKingPawnMoves = [[90]*8 for i in range(91)]
for sq in range(90):
Moves = BlackKingPawnMoves[sq]
flag = SquareFlags[sq]
sqs = []
if flag & BlackKingFlag:
sqs = [i for i in [u(sq), d(sq), l(sq), r(sq)] if SquareFlags[i] & BlackKingFlag]
elif flag & BlackPawnFlag:
sqs = [i for i in [u(sq), l(sq), r(sq)] if SquareFlags[i] & BlackPawnFlag]
for sq in sqs:
Moves[Moves.index(90)] = sq
return BlackKingPawnMoves
BlackKingPawnMoves = BlackKingPawnMoves()
def AdvisorBishopMoves():
AdvisorBishopMoves = [[90]*8 for i in range(91)]
for sq in range(90):
Moves = AdvisorBishopMoves[sq]
flag = SquareFlags[sq]
if flag & BishopFlag:
for square in [u(u(r(r(sq)))), u(u(l(l(sq)))), d(d(r(r(sq)))), d(d(l(l(sq))))]:
if SquareFlags[square] & BishopFlag:
Moves[Moves.index(90)] = square
elif flag & AdvisorFlag:
for square in [u(l(sq)), u(r(sq)), d(l(sq)), d(r(sq))]:
if SquareFlags[square] & AdvisorFlag:
Moves[Moves.index(90)] = square
return AdvisorBishopMoves
AdvisorBishopMoves = AdvisorBishopMoves()
def main():
dict = {}
dict['xs'] = d1a_str(Xs, u32)
dict['ys'] = d1a_str(Ys, u32)
dict['xys'] = d2a_str(XYs, u32)
dict['ups'] = d1a_str(SquareUps, u32)
dict['downs'] = d1a_str(SquareDowns, u32)
dict['lefts'] = d1a_str(SquareLefts, u32)
dict['rights'] = d1a_str(SquareRights, u32)
dict['square_flags'] = d1a_str(SquareFlags, u32)
dict ['ptypes'] = d1a_str(PT, u32)
dict ['pflags'] = d1a_str(PF, u32)
dict ['pcolors'] = d1a_str(PC, u32)
dict ['kl'] = d2a_str(KnightLegs, u32)
dict ['be'] = d2a_str(BishopEyes, u32)
dict['nm'] = d2a_str(KnightMoves, u32)
dict['rkpm'] = d2a_str(RedKingPawnMoves, u32)
dict['bkpm'] = d2a_str(BlackKingPawnMoves, u32)
dict['abm'] = d2a_str(AdvisorBishopMoves, u32)
template = open(os.path.join(template_path, 'xq_data.cpp.tmpl'), 'rb').read()
template = string.Template(template)
path = os.path.join(folium_path, 'xq_data.cpp')
open(path, 'wb').write(str(template.safe_substitute(dict)))
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/env python
#coding=utf-8
import os
import string
from consts import *
def main():
line_infos = [[0]*1024 for i in range(10)]
for idx in range(10):
for flag in range(1024):
flag |= 0xFC00
p1 = (idx and [idx-1] or [0xF])[0]
while not flag & (1 << p1):
p1 = (p1 and [p1-1] or [0xF])[0]
p2 = (p1 and [p1-1] or [0xF])[0]
while not flag & (1 << p2):
p2 = (p2 and [p2-1] or [0xF])[0]
n1 = idx + 1
while not flag & (1 << n1):
n1 += 1
n2 = n1 + 1
while not flag & (1 << n2):
n2 += 1
line_infos[idx][flag & 1023] = p1 | (p2 << 4) | (n1 << 8) | (n2 << 12)
bits = [1 << i for i in range(10)]
bit_counts = [len([j for j in bits if i & j])for i in range(1024)]
distance_infos = [[(19 << 10 | 1023)]*128 for i in range(91)]
for src in range(90):
sy, sx = divmod(src, 9)
for dst in range(90):
if dst == src:
continue
dy, dx = divmod(dst, 9)
if dx == sx:
idx = dx+10
mask = sum(bits[i] for i in set(range(dy+1, sy)+range(sy+1, dy)) if i in range(10))
distance_infos[src][dst] = (idx << 10) | mask
elif dy == sy:
idx = dy
mask = sum(bits[i] for i in set(range(dx+1, sx)+range(sx+1, dx)) if i in range(10))
distance_infos[src][dst] = (idx << 10) | mask
dict = {}
dict['infos'] = d2a_str(line_infos, u32)
dict['counts'] = d1a_str(bit_counts, u32)
dict['distance'] = d2a_str(distance_infos, u32)
template = open(os.path.join(template_path, 'bitlines_data.cpp.tmpl'), 'rb').read()
template = string.Template(template)
path = os.path.join(folium_path, 'bitlines_data.cpp')
open(path, 'wb').write(str(template.safe_substitute(dict)))
if __name__ == "__main__":
main()
| Python |
import sys
cpp_path = ['#include']
lib_path = ['#bin']
env = Environment(CPPPATH=cpp_path, LIBPATH=lib_path)
if sys.platform == "win32":
env.Tool('mingw')
ccflag = '-O3'
ccflag = '-O3 -march=prescott'
defines = {'NDEBUG':None}
Export("env")
Export("ccflag")
Export("defines")
env.SConscript('src/sconscript', build_dir='build/folium', duplicate=0)
env.SConscript('qianhong/sconscript', build_dir='build/qianhong', duplicate=0)
| Python |
import xq_data
xq_data.main()
import engine_data
engine_data.main()
import history_data
history_data.main()
import bitlines_data
bitlines_data.main()
| Python |
#!/usr/bin/env python
#coding=utf-8
import os
import string
from consts import *
from xq_data import *
RedKingPawnValues = [0]*91
BlackKingPawnValues = [0]*91
AdvisorBishopValues = [0]*91
RedRookValues = [0]*91
BlackRookValues = [0]*91
RedKnightValues = [0]*91
BlackKnightValues = [0]*91
RedCannonValues = [0]*91
BlackCannonValues = [0]*91
def value():
KingBaseValue = 5000
AdvisorBaseValue = 40
BishopBaseValue = 40
RookBaseValue = 200
KnightBaseValue = 88
CannonBaseValue = 96
PawnBaseValue = 9
RedKingPawnPositionValues = [
0, 0, 0, 1, 5, 1, 0, 0, 0,
0, 0, 0, -8, -8, -8, 0, 0, 0,
0, 0, 0, -9, -9, -9, 0, 0, 0,
-2, 0, -2, 0, 6, 0, -2, 0, -2,
3, 0, 4, 0, 7, 0, 4, 0, 3,
10, 18, 22, 35, 40, 35, 22, 18, 10,
20, 27, 30, 40, 42, 40, 35, 27, 20,
20, 30, 45, 55, 55, 55, 45, 30, 20,
20, 30, 50, 65, 70, 65, 50, 30, 20,
0, 0, 0, 2, 4, 2, 0, 0, 0,]
RedAdvisorBishopPositionValues = [
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 3, 0, 0, 0, 0,
-2, 0, 0, 0, 3, 0, 0, 0, -2,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0,]
RedRookPositionValues = [
-6, 6, 4, 12, 0, 12, 4, 6, -6,
5, 8, 6, 12, 0, 12, 6, 8, 5,
-2, 8, 4, 12, 12, 12, 4, 8, -2,
4, 9, 4, 12, 14, 12, 4, 9, 4,
8, 12, 12, 14, 15, 14, 12, 12, 8,
8, 11, 11, 14, 15, 14, 11, 11, 8,
6, 13, 13, 16, 16, 16, 13, 13, 6,
6, 8, 7, 14, 16, 14, 7, 8, 6,
6, 12, 9, 16, 33, 16, 9, 12, 6,
6, 8, 7, 13, 14, 13, 7, 8, 6,]
RedKnightPositionValues = [
0, -3, 2, 0, 2, 0, 2, -3, 0,
-3, 2, 4, 5, -10, 5, 4, 2, -3,
5, 4, 6, 7, 4, 7, 6, 4, 5,
4, 6, 10, 7, 10, 7, 10, 6, 4,
2, 10, 13, 14, 15, 14, 13, 10, 2,
2, 12, 11, 15, 16, 15, 11, 12, 2,
5, 20, 12, 19, 12, 19, 12, 20, 5,
4, 10, 11, 15, 11, 15, 11, 10, 4,
2, 8, 15, 9, 6, 9, 15, 8, 2,
2, 2, 2, 8, 2, 8, 2, 2, 2,]
RedCannonPositionValues = [
0, 0, 1, 3, 3, 3, 1, 0, 0,
0, 1, 2, 2, 2, 2, 2, 1, 0,
1, 0, 4, 3, 5, 3, 4, 0, 1,
0, 0, 0, 0, 0, 0, 0, 0, 0,
-1, 0, 3, 0, 4, 0, 3, 0, -1,
0, 0, 0, 0, 4, 0, 0, 0, 0,
0, 3, 3, 2, 4, 2, 3, 3, 0,
1, 1, 0, -5, -4, -5, 0, 1, 1,
2, 2, 0, -4, -7, -4, 0, 2, 2,
4, 4, 0, -5, -6, -5, 0, 4, 4,]
for sq in range(90):
flag = SquareFlags[sq]
if flag & RedKingFlag:
RedKingPawnValues[sq] = KingBaseValue + RedKingPawnPositionValues[sq]
BlackKingPawnValues[89 - sq] = -RedKingPawnValues[sq]
if flag & RedAdvisorFlag:
AdvisorBishopValues[sq] = AdvisorBaseValue + RedAdvisorBishopPositionValues[sq]
AdvisorBishopValues[89 - sq] = -AdvisorBishopValues[sq]
if flag & RedBishopFlag:
AdvisorBishopValues[sq] = BishopBaseValue + RedAdvisorBishopPositionValues[sq]
AdvisorBishopValues[89 - sq] = -AdvisorBishopValues[sq]
RedRookValues[sq] = RookBaseValue + RedRookPositionValues[sq]
BlackRookValues[89 - sq] = -RedRookValues[sq]
RedKnightValues[sq] = KnightBaseValue + RedKnightPositionValues[sq]
BlackKnightValues[89 - sq] = -RedKnightValues[sq]
RedCannonValues[sq] = CannonBaseValue + RedCannonPositionValues[sq]
BlackCannonValues[89 - sq] = -RedCannonValues[sq]
if flag & RedPawnFlag:
RedKingPawnValues[sq] = PawnBaseValue + RedKingPawnPositionValues[sq]
BlackKingPawnValues[89 - sq] = -RedKingPawnValues[sq]
value()
RedKingPawnLocks = [0]*91
BlackKingPawnLocks = [0]*91
AdvisorBishopLocks = [0]*91
RedRookLocks = [0]*91
BlackRookLocks = [0]*91
RedKnightLocks = [0]*91
BlackKnightLocks = [0]*91
RedCannonLocks = [0]*91
BlackCannonLocks = [0]*91
RedKingPawnKeys = [0]*91
BlackKingPawnKeys = [0]*91
AdvisorBishopKeys = [0]*91
RedRookKeys = [0]*91
BlackRookKeys = [0]*91
RedKnightKeys = [0]*91
BlackKnightKeys = [0]*91
RedCannonKeys = [0]*91
BlackCannonKeys = [0]*91
def hash():
from random import randint, seed
seed(51)
for sq in range(90):
flag = SquareFlags[sq]
if flag & RedKingPawnFlag:
RedKingPawnLocks[sq] = randint(0, 0x10000000000000000)
RedKingPawnKeys[sq] = randint(0, 0x100000000)
BlackKingPawnLocks[89 - sq] = randint(0, 0x10000000000000000)
BlackKingPawnKeys[89 - sq] = randint(0, 0x100000000)
if flag & AdvisorBishopFlag:
AdvisorBishopLocks[sq] = randint(0, 0x10000000000000000)
AdvisorBishopKeys[sq] = randint(0, 0x100000000)
RedRookLocks[sq] = randint(0, 0x10000000000000000)
RedRookKeys[sq] = randint(0, 0x100000000)
BlackRookLocks[sq] = randint(0, 0x10000000000000000)
BlackRookKeys[sq] = randint(0, 0x100000000)
RedKnightLocks[sq] = randint(0, 0x10000000000000000)
RedKnightKeys[sq] = randint(0, 0x100000000)
BlackKnightLocks[sq] = randint(0, 0x10000000000000000)
BlackKnightKeys[sq] = randint(0, 0x100000000)
RedCannonLocks[sq] = randint(0, 0x10000000000000000)
RedCannonKeys[sq] = randint(0, 0x100000000)
BlackCannonLocks[sq] = randint(0, 0x10000000000000000)
BlackCannonKeys[sq] = randint(0, 0x100000000)
hash()
def main():
dict = {}
dict['rkpl'] = d1a_str(RedKingPawnLocks, u64)
dict['rkpk'] = d1a_str(RedKingPawnKeys, u32)
dict['rkpv'] = d1a_str(RedKingPawnValues, s32)
dict['bkpl'] = d1a_str(BlackKingPawnLocks, u64)
dict['bkpk'] = d1a_str(BlackKingPawnKeys, u32)
dict['bkpv'] = d1a_str(BlackKingPawnValues, s32)
dict['abl'] = d1a_str(AdvisorBishopLocks, u64)
dict['abk'] = d1a_str(AdvisorBishopKeys, u32)
dict['abv'] = d1a_str(AdvisorBishopValues, s32)
dict['rrl'] = d1a_str(RedRookLocks, u64)
dict['rrk'] = d1a_str(RedRookKeys, u32)
dict['rrv'] = d1a_str(RedRookValues, s32)
dict['brl'] = d1a_str(BlackRookLocks, u64)
dict['brk'] = d1a_str(BlackRookKeys, u32)
dict['brv'] = d1a_str(BlackRookValues, s32)
dict['rnl'] = d1a_str(RedKnightLocks, u64)
dict['rnk'] = d1a_str(RedKnightKeys, u32)
dict['rnv'] = d1a_str(RedKnightValues, s32)
dict['bnl'] = d1a_str(BlackKnightLocks, u64)
dict['bnk'] = d1a_str(BlackKnightKeys, u32)
dict['bnv'] = d1a_str(BlackKnightValues, s32)
dict['rcl'] = d1a_str(RedCannonLocks, u64)
dict['rck'] = d1a_str(RedCannonKeys, u32)
dict['rcv'] = d1a_str(RedCannonValues, s32)
dict['bcl'] = d1a_str(BlackCannonLocks, u64)
dict['bck'] = d1a_str(BlackCannonKeys, u32)
dict['bcv'] = d1a_str(BlackCannonValues, s32)
PF = [RedKingFlag]+[RedAdvisorFlag]*2+[RedBishopFlag]*2\
+[RedRookFlag]*2+[RedKnightFlag]*2+[RedCannonFlag]*2+[RedPawnFlag]*5\
+[BlackKingFlag]+[BlackAdvisorFlag]*2+[BlackBishopFlag]*2\
+[BlackRookFlag]*2+[BlackKnightFlag]*2+[BlackCannonFlag]*2+[BlackPawnFlag]*5\
+[EmptyFlag, InvaildFlag]
PT = [RedKing]+[RedAdvisor]*2+[RedBishop]*2+[RedRook]*2+[RedKnight]*2+[RedCannon]*2+[RedPawn]*5\
+[BlackKing]+[BlackAdvisor]*2+[BlackBishop]*2+[BlackRook]*2+[BlackKnight]*2+[BlackCannon]*2+[BlackPawn]*5\
+[EmptyType]+[InvalidType]
PC = [0]*16 + [1]*16 + [2] + [3]
PL = ['s_red_king_pawn_locks']+['s_advisor_bishop_locks']*4+['s_red_rook_locks']*2+['s_red_knight_locks']*2\
+['s_red_cannon_locks']*2+['s_red_king_pawn_locks']*5\
+['s_black_king_pawn_locks']+['s_advisor_bishop_locks']*4+['s_black_rook_locks']*2+['s_black_knight_locks']*2\
+['s_black_cannon_locks']*2+['s_black_king_pawn_locks']*5
PK = ['s_red_king_pawn_keys']+['s_advisor_bishop_keys']*4+['s_red_rook_keys']*2+['s_red_knight_keys']*2\
+['s_red_cannon_keys']*2+['s_red_king_pawn_keys']*5\
+['s_black_king_pawn_keys']+['s_advisor_bishop_keys']*4+['s_black_rook_keys']*2+['s_black_knight_keys']*2\
+['s_black_cannon_keys']*2+['s_black_king_pawn_keys']*5
PV = ['s_red_king_pawn_values']+['s_advisor_bishop_values']*4+['s_red_rook_values']*2+['s_red_knight_values']*2\
+['s_red_cannon_values']*2+['s_red_king_pawn_values']*5\
+['s_black_king_pawn_values']+['s_advisor_bishop_values']*4+['s_black_rook_values']*2+['s_black_knight_values']*2\
+['s_black_cannon_values']*2+['s_black_king_pawn_values']*5
dict['plocks'] = d1a_str(PL, lambda x: x)
dict['pkeys'] = d1a_str(PK, lambda x: x)
dict['pvalues'] = d1a_str(PV, lambda x: x)
TL = ['s_red_king_pawn_locks']+['s_advisor_bishop_locks']*2\
+['s_red_rook_locks','s_red_knight_locks','s_red_cannon_locks','s_red_king_pawn_locks']\
+['s_black_king_pawn_locks']+['s_advisor_bishop_locks']*2\
+['s_black_rook_locks','s_black_knight_locks','s_black_cannon_locks','s_black_king_pawn_locks']
TK = ['s_red_king_pawn_keys']+['s_advisor_bishop_keys']*2\
+['s_red_rook_keys','s_red_knight_keys','s_red_cannon_keys','s_red_king_pawn_keys']\
+['s_black_king_pawn_keys']+['s_advisor_bishop_keys']*2\
+['s_black_rook_keys','s_black_knight_keys','s_black_cannon_keys','s_black_king_pawn_keys']
TV = ['s_red_king_pawn_values']+['s_advisor_bishop_values']*2\
+['s_red_rook_values','s_red_knight_values','s_red_cannon_values','s_red_king_pawn_values']\
+['s_black_king_pawn_values']+['s_advisor_bishop_values']*2\
+['s_black_rook_values','s_black_knight_values','s_black_cannon_values','s_black_king_pawn_values']
dict['tlocks'] = d1a_str(TL, lambda x: x)
dict['tkeys'] = d1a_str(TK, lambda x: x)
dict['tvalues'] = d1a_str(TV, lambda x: x)
#template = string.Template(template)
template = open(os.path.join(template_path, 'engine_data.cpp.tmpl'), 'rb').read()
template = string.Template(template)
path = os.path.join(folium_path, 'engine_data.cpp')
open(path, 'wb').write(str(template.safe_substitute(dict)))
if __name__ == "__main__":
main() | Python |
#!/usr/bin/env python
#coding=utf-8
import os
import string
from consts import *
from xq_data import *
def capture_scores():
capture_scores = [[0]*32 for i in range(32)]
e = [10000, 1041, 1040, 2000, 1088, 1096, 1020]
m = [1000, 41, 40, 200, 88, 96, 20]
def level(src_type, dst_type): return levels[src_type][dst_type]
def color(piece): return PC[piece]
def type(piece):
t = PT[piece]
if t >= 7:
t -= 7
return t
for src_piece in range(32):
for dst_piece in range(32):
if color(src_piece) != color(dst_piece):
src_type = type(src_piece)
dst_type = type(dst_piece)
capture_scores[src_piece][dst_piece] = e[dst_type] - m[src_type]
return capture_scores
capture_scores = capture_scores()
def main():
dict = {}
dict['scores'] = d2a_str(capture_scores, u32)
template = open(os.path.join(template_path, 'history_data.cpp.tmpl'), 'rb').read()
template = string.Template(template)
path = os.path.join(folium_path, 'history_data.cpp')
open(path, 'wb').write(str(template.safe_substitute(dict)))
if __name__ == "__main__":
main() | Python |
#!/usr/bin/env python
#coding=utf-8
import os
import string
from consts import *
def main():
line_infos = [[0]*1024 for i in range(10)]
for idx in range(10):
for flag in range(1024):
flag |= 0xFC00
p1 = (idx and [idx-1] or [0xF])[0]
while not flag & (1 << p1):
p1 = (p1 and [p1-1] or [0xF])[0]
p2 = (p1 and [p1-1] or [0xF])[0]
while not flag & (1 << p2):
p2 = (p2 and [p2-1] or [0xF])[0]
n1 = idx + 1
while not flag & (1 << n1):
n1 += 1
n2 = n1 + 1
while not flag & (1 << n2):
n2 += 1
line_infos[idx][flag & 1023] = p1 | (p2 << 8) | (n1 << 16) | (n2 << 24)
dict = {}
dict['infos'] = d2a_str(line_infos, u32)
template = open(os.path.join(template_path, 'bitlines_data.cpp.tmpl'), 'rb').read()
template = string.Template(template)
path = os.path.join(folium_path, 'bitlines_data.cpp')
open(path, 'wb').write(str(template.safe_substitute(dict)))
if __name__ == "__main__":
main()
| Python |
RedKing = 0;
RedAdvisor = 1;
RedBishop = 2;
RedRook = 3;
RedKnight = 4;
RedCannon = 5;
RedPawn = 6;
BlackKing = 7;
BlackAdvisor = 8;
BlackBishop = 9;
BlackRook = 10;
BlackKnight = 11;
BlackCannon = 12;
BlackPawn = 13;
EmptyType = 14;
InvalidType = 15;
RedKingFlag = 1 << 0;
RedAdvisorFlag = 1 << 1;
RedBishopFlag = 1 << 2;
RedRookFlag = 1 << 3;
RedKnightFlag = 1 << 4;
RedCannonFlag = 1 << 5;
RedPawnFlag = 1 << 6;
BlackKingFlag = 1 << 7;
BlackAdvisorFlag = 1 << 8;
BlackBishopFlag = 1 << 9;
BlackRookFlag = 1 << 10;
BlackKnightFlag = 1 << 11;
BlackCannonFlag = 1 << 12;
BlackPawnFlag = 1 << 13;
EmptyFlag = 1 << 14;
InvaildFlag = 1 << 15;
AdvisorFlag = RedAdvisorFlag | BlackAdvisorFlag
BishopFlag = RedBishopFlag | BlackBishopFlag
RedKingPawnFlag = RedKingFlag | RedPawnFlag
AdvisorBishopFlag = RedAdvisorFlag | RedBishopFlag | BlackAdvisorFlag | BlackBishopFlag
RedKingSquares = [x + y * 9 for x, y in [(3, 0), (4, 0), (5, 0), (3, 1), (4, 1), (5, 1), (3, 2), (4, 2), (5, 2)]]
RedAdvisorSquares = [x + y * 9 for x, y in [(3,0), (5,0), (4, 1), (3,2), (5,2)]]
RedBishopSquares = [x + y * 9 for x, y in [(2, 0), (6, 0), (0, 2), (4, 2), (8, 2), (2, 4), (6, 4)]]
RedRookSquares = range(90)
RedKnightSquares = range(90)
RedCannonSquares = range(90)
RedPawnSquares = [x + y * 9 for x, y in [(0, 3), (2, 3), (4, 3), (6, 3), (8, 3), (0, 4), (2, 4), (4, 4), (6, 4), (8, 4)]]
RedPawnSquares.extend(range(45, 90))
BlackKingSquares = [89 - sq for sq in RedKingSquares]
BlackAdvisorSquares = [89 - sq for sq in RedAdvisorSquares]
BlackBishopSquares = [89 - sq for sq in RedBishopSquares]
BlackRookSquares = [89 - sq for sq in RedRookSquares]
BlackKnightSquares = [89 - sq for sq in RedKnightSquares]
BlackCannonSquares = [89 - sq for sq in RedCannonSquares]
BlackPawnSquares = [89 - sq for sq in RedPawnSquares]
def SquareFlags():
SquareFlags = [0]*91
for sq in RedKingSquares:
SquareFlags[sq] |= RedKingFlag
SquareFlags[89 - sq] |= BlackKingFlag
for sq in RedAdvisorSquares:
SquareFlags[sq] |= RedAdvisorFlag
SquareFlags[89 - sq] |= BlackAdvisorFlag
for sq in RedBishopSquares:
SquareFlags[sq] |= RedBishopFlag
SquareFlags[89 - sq] |= BlackBishopFlag
for sq in RedPawnSquares:
SquareFlags[sq] |= RedPawnFlag
SquareFlags[89 - sq] |= BlackPawnFlag
for sq in range(90):
SquareFlags[sq] |= RedRookFlag
SquareFlags[sq] |= RedKnightFlag
SquareFlags[sq] |= RedCannonFlag
SquareFlags[sq] |= BlackRookFlag
SquareFlags[sq] |= BlackKnightFlag
SquareFlags[sq] |= BlackCannonFlag
SquareFlags[sq] |= EmptyFlag
SquareFlags[90] |= InvaildFlag
return SquareFlags
SquareFlags = SquareFlags()
def u64(i):
return str(i)+'ULL'
def u32(i):
return str(i)+'UL'
def s32(i):
return str(i)+'L'
def d1a_str(array_1d, func):
array_1d = [func(i) for i in array_1d]
return ', '.join(array_1d)
def d2a_str(array_2d, func):
array_2d = ['{%s}'%d1a_str(array_1d, func) for array_1d in array_2d]
return ',\n'.join(array_2d)
import os
script_path = os.path.abspath(os.path.dirname(__file__))
work_path = os.path.dirname(script_path)
folium_path = os.path.join(work_path, 'src')
template_path = os.path.join(script_path, 'template')
if not os.path.exists(template_path):
os.mkdir(template_path)
if __name__ == "__main__":
print work_path
print script_path
print folium_path
| Python |
#!/usr/bin/env python
#coding=utf-8
import os
import string
from consts import *
def u(x): return SquareUps[x]
def d(x): return SquareDowns[x]
def l(x): return SquareLefts[x]
def r(x): return SquareRights[x]
SquareUps = [0]*91
SquareDowns = [0]*91
SquareLefts = [0]*91
SquareRights = [0]*91
Xs = [9]*91
Ys = [10]*91
XYs = [[90]*16 for i in range(16)]
KnightLegs = [[90]*128 for i in range(91)]
BishopEyes = [[90]*128 for i in range(91)]
def info():
def _(x, y):
if x < 0 or x >8 or y < 0 or y > 9:
return 90
return x + 9 * y
for sq in range(90):
#x, y = sq % 9, sq / 9
y, x = divmod(sq, 9)
SquareUps[sq] = _(x, y - 1)
SquareDowns[sq] = _(x, y + 1)
SquareLefts[sq] = _(x - 1, y)
SquareRights[sq] = _(x + 1, y)
Xs[sq] = x
Ys[sq] = y
XYs[y][x] = sq
SquareUps[90] = 90
SquareDowns[90] = 90
SquareLefts[90] = 90
SquareRights[90] = 90
info()
def leg():
u = lambda s:SquareUps[s]
d = lambda s:SquareDowns[s]
l = lambda s:SquareLefts[s]
r = lambda s:SquareRights[s]
for src in range(90):
leg = u(src)
dst = l(u(leg))
if dst != 90: KnightLegs[src][dst] = leg
dst = r(u(leg))
if dst != 90: KnightLegs[src][dst] = leg
leg = d(src)
dst = l(d(leg))
if dst != 90: KnightLegs[src][dst] = leg
dst = r(d(leg))
if dst != 90: KnightLegs[src][dst] = leg
leg = l(src)
dst = u(l(leg))
if dst != 90: KnightLegs[src][dst] = leg
dst = d(l(leg))
if dst != 90: KnightLegs[src][dst] = leg
leg = r(src)
dst = u(r(leg))
if dst != 90: KnightLegs[src][dst] = leg
dst = d(r(leg))
if dst != 90: KnightLegs[src][dst] = leg
leg()
def eye():
u = lambda s:SquareUps[s]
d = lambda s:SquareDowns[s]
l = lambda s:SquareLefts[s]
r = lambda s:SquareRights[s]
for src in range(90):
if not (SquareFlags[src] & BishopFlag):
continue
dst = u(u(l(l(src))))
if (SquareFlags[dst] & BishopFlag):BishopEyes[src][dst] = (src + dst)/2
dst = u(u(r(r(src))))
if (SquareFlags[dst] & BishopFlag):BishopEyes[src][dst] = (src + dst)/2
dst = d(d(l(l(src))))
if (SquareFlags[dst] & BishopFlag):BishopEyes[src][dst] = (src + dst)/2
dst = d(d(r(r(src))))
if (SquareFlags[dst] & BishopFlag):BishopEyes[src][dst] = (src + dst)/2
eye()
PF = [RedKingFlag]+[RedAdvisorFlag]*2+[RedBishopFlag]*2\
+[RedRookFlag]*2+[RedKnightFlag]*2+[RedCannonFlag]*2+[RedPawnFlag]*5\
+[BlackKingFlag]+[BlackAdvisorFlag]*2+[BlackBishopFlag]*2\
+[BlackRookFlag]*2+[BlackKnightFlag]*2+[BlackCannonFlag]*2+[BlackPawnFlag]*5\
+[EmptyFlag, InvaildFlag]
PT = [RedKing]+[RedAdvisor]*2+[RedBishop]*2+[RedRook]*2+[RedKnight]*2+[RedCannon]*2+[RedPawn]*5\
+[BlackKing]+[BlackAdvisor]*2+[BlackBishop]*2+[BlackRook]*2+[BlackKnight]*2+[BlackCannon]*2+[BlackPawn]*5\
+[EmptyType]+[InvalidType]
PC = [0]*16 + [1]*16 + [2] + [3]
def KnightMoves():
KnightMoves = [[23130]*16 for i in range(91)]
for sq in range(90):
ls = KnightMoves[sq]
leg = u(sq)
for dst in [l(u(leg)),r(u(leg))]:
if dst != 90:
ls[ls.index(23130)] = (leg << 8) | dst
leg = d(sq)
for dst in [l(d(leg)),r(d(leg))]:
if dst != 90:
ls[ls.index(23130)] = (leg << 8) | dst
leg = l(sq)
for dst in [u(l(leg)),d(l(leg))]:
if dst != 90:
ls[ls.index(23130)] = (leg << 8) | dst
leg = r(sq)
for dst in [u(r(leg)),d(r(leg))]:
if dst != 90:
ls[ls.index(23130)] = (leg << 8) | dst
return KnightMoves
KnightMoves = KnightMoves()
def RedKingPawnMoves():
RedKingPawnMoves = [[90]*8 for i in range(91)]
for sq in range(90):
Moves = RedKingPawnMoves[sq]
flag = SquareFlags[sq]
sqs = []
if flag & RedKingFlag:
sqs = [i for i in [u(sq), d(sq), l(sq), r(sq)] if SquareFlags[i] & RedKingFlag]
elif flag & RedPawnFlag:
sqs = [i for i in [d(sq), l(sq), r(sq)] if SquareFlags[i] & RedPawnFlag]
for sq in sqs:
Moves[Moves.index(90)] = sq
return RedKingPawnMoves
RedKingPawnMoves = RedKingPawnMoves()
def BlackKingPawnMoves():
BlackKingPawnMoves = [[90]*8 for i in range(91)]
for sq in range(90):
Moves = BlackKingPawnMoves[sq]
flag = SquareFlags[sq]
sqs = []
if flag & BlackKingFlag:
sqs = [i for i in [u(sq), d(sq), l(sq), r(sq)] if SquareFlags[i] & BlackKingFlag]
elif flag & BlackPawnFlag:
sqs = [i for i in [u(sq), l(sq), r(sq)] if SquareFlags[i] & BlackPawnFlag]
for sq in sqs:
Moves[Moves.index(90)] = sq
return BlackKingPawnMoves
BlackKingPawnMoves = BlackKingPawnMoves()
def AdvisorBishopMoves():
AdvisorBishopMoves = [[90]*8 for i in range(91)]
for sq in range(90):
Moves = AdvisorBishopMoves[sq]
flag = SquareFlags[sq]
if flag & BishopFlag:
for square in [u(u(r(r(sq)))), u(u(l(l(sq)))), d(d(r(r(sq)))), d(d(l(l(sq))))]:
if SquareFlags[square] & BishopFlag:
Moves[Moves.index(90)] = square
elif flag & AdvisorFlag:
for square in [u(l(sq)), u(r(sq)), d(l(sq)), d(r(sq))]:
if SquareFlags[square] & AdvisorFlag:
Moves[Moves.index(90)] = square
return AdvisorBishopMoves
AdvisorBishopMoves = AdvisorBishopMoves()
def main():
dict = {}
dict['xs'] = d1a_str(Xs, u32)
dict['ys'] = d1a_str(Ys, u32)
dict['xys'] = d2a_str(XYs, u32)
dict['ups'] = d1a_str(SquareUps, u32)
dict['downs'] = d1a_str(SquareDowns, u32)
dict['lefts'] = d1a_str(SquareLefts, u32)
dict['rights'] = d1a_str(SquareRights, u32)
dict['square_flags'] = d1a_str(SquareFlags, u32)
dict ['ptypes'] = d1a_str(PT, u32)
dict ['pflags'] = d1a_str(PF, u32)
dict ['pcolors'] = d1a_str(PC, u32)
dict ['kl'] = d2a_str(KnightLegs, u32)
dict ['be'] = d2a_str(BishopEyes, u32)
dict['nm'] = d2a_str(KnightMoves, u32)
dict['rkpm'] = d2a_str(RedKingPawnMoves, u32)
dict['bkpm'] = d2a_str(BlackKingPawnMoves, u32)
dict['abm'] = d2a_str(AdvisorBishopMoves, u32)
template = open(os.path.join(template_path, 'xq_data.cpp.tmpl'), 'rb').read()
template = string.Template(template)
path = os.path.join(folium_path, 'xq_data.cpp')
open(path, 'wb').write(str(template.safe_substitute(dict)))
if __name__ == "__main__":
main()
| Python |
#!/usr/bin/env python
#coding=utf-8
import os
import string
from consts import *
def main():
line_infos = [[0]*1024 for i in range(10)]
for idx in range(10):
for flag in range(1024):
flag |= 0xFC00
p1 = (idx and [idx-1] or [0xF])[0]
while not flag & (1 << p1):
p1 = (p1 and [p1-1] or [0xF])[0]
p2 = (p1 and [p1-1] or [0xF])[0]
while not flag & (1 << p2):
p2 = (p2 and [p2-1] or [0xF])[0]
n1 = idx + 1
while not flag & (1 << n1):
n1 += 1
n2 = n1 + 1
while not flag & (1 << n2):
n2 += 1
line_infos[idx][flag & 1023] = p1 | (p2 << 8) | (n1 << 16) | (n2 << 24)
dict = {}
dict['infos'] = d2a_str(line_infos, u32)
template = open(os.path.join(template_path, 'bitlines_data.cpp.tmpl'), 'rb').read()
template = string.Template(template)
path = os.path.join(folium_path, 'bitlines_data.cpp')
open(path, 'wb').write(str(template.safe_substitute(dict)))
if __name__ == "__main__":
main()
| Python |
import random
import _xq
class Book(object):
def readflag(self, fen):
_ = []
for flag in range(4):
new= _xq.mirror4fen(fen, flag)
if not new.endswith('b'):
_.append([new, flag])
_.sort()
return _[0] if _[0][0] >= _[1][0] else _[1]
def search(self, fen, bans):
fen, flag = self.readflag(fen)
moves = self.readmoves(fen)
moves = [(_xq.mirror4uccimove(move, flag), moves[move]) for move in moves]
moves = [(move, score) for move, score in moves if move not in bans]
scores = sum(score for move, score in moves)
if scores == 0:
return
idx = random.randint(0, scores-1)
for move, score in moves:
if score > idx:
return move
idx = idx - score
def addflag(self, fen, move):
_ = []
for flag in range(4):
nf, nm = _xq.mirror4fen(fen, flag), _xq.mirror4uccimove(move, flag)
if not nf.endswith('b'):
_.append([nf, nm, flag])
return sorted(_)[1]
| Python |
import os
import sys
import book
class dictbook(book.Book):
def __init__(self):
book.Book.__init__(self)
self.load()
def load(self):
bookfile = os.path.join(os.path.dirname(sys.argv[0]), 'book.dict')
self.dict = {}
for line in open(bookfile):
_ = line.split('_')
fen = _[0]
for s in _[1:]:
move, score = s.split(':')
self.add(fen, move, score)
def add(self, fen, move, score):
fen, move, flag = self.addflag(fen, move)
moves = self.dict.setdefault(fen, {})
moves[move] = moves.get(move, 0) + int(score)
def readmoves(self, fen):
return self.dict.get(fen, {}) | Python |
import time
import _xq
import snake.book.dictbook
class Engine(_xq.Engine):
def __init__(self):
_xq.Engine.__init__(self)
self.book = snake.book.dictbook.dictbook()
def run(self):
while not self.readable():
pass
line = self.readline()
if line == 'ucci':
self.ucci()
elif line == 'perft':
self.perft()
def perft(self):
def _():
self.writeline(str(xq))
for index, count in enumerate(perfts):
t1 = _xq.currenttime()
assert(xq.perft(index) == count)
t2 = _xq.currenttime()
if t2 - t1 > 0.1:
self.writeline("ply:%d\tcount:%d\tnode:%d"%(index+1, count, int(count/(t2-t1))))
xq = _xq.XQ("r1ba1a3/4kn3/2n1b4/pNp1p1p1p/4c4/6P2/P1P2R2P/1CcC5/9/2BAKAB2 r")
perfts = [38, 1128, 43929, 1339047, 53112976]
_()
xq = _xq.XQ("r2akab1r/3n5/4b3n/p1p1pRp1p/9/2P3P2/P3P3c/N2C3C1/4A4/1RBAK1B2 r")
perfts = [58, 1651, 90744, 2605437, 140822416]
_()
xq = _xq.XQ("rnbakabnr/9/1c5c1/p1p1p1p1p/9/9/P1P1P1P1P/1C5C1/9/RNBAKABNR r")
perfts = [44, 1920, 79666, 3290240, 133312995, 5392831844]
#_()
def ucci(self):
self.writeline('id name folium')
self.writeline('id author Wangmao Lin')
self.writeline('id user engine tester')
self.writeline('option usemillisec type check default true')
self.usemillisec = True
self.writeline('ucciok')
self.bans = []
self.loop()
def loop(self):
while True:
while not self.readable():
time.sleep(0.001)
line = self.readline()
if line == 'isready':
self.writeline('readyok')
elif line == 'quit' or line == 'exit':
self.writeline('bye')
return
elif line.startswith('setoption '):
self.setoption(line[10:])
elif line.startswith('position '):
self.position(line[9:])
elif line.startswith('banmoves '):
self.banmoves(line[9:])
elif line.startswith('go'):
self.go(line)
elif line.startswith('probe'):
self.probe(line)
def position(self, position):
if " moves " in position:
position, moves = position.split(" moves ")
moves = moves.split()
else:
moves = []
if position.startswith("fen "):
fen = position[4:]
elif position == "startpos":
fen = "rnbakabnr/9/1c5c1/p1p1p1p1p/9/9/P1P1P1P1P/1C5C1/9/RNBAKABNR r"
self.load(fen)
for move in moves:
move = _xq.ucci2move(move)
self.makemove(move)
self.bans = []
def setoption(self, option):
return
if option.startswith('usemillisec '):
self.usemillisec = (option[12:] == 'true')
elif option.startswith('debug'):
pass
def banmoves(self, moves):
self.bans = moves.split()
def go(self, line):
self.stop = False
self.ponder = False
self.draw = False
self.depth = 255
self.starttime = _xq.currenttime()
self.mintime = self.maxtime = self.starttime + 24*60*60
move = self.book.search(str(self), self.bans) if self.book else None
if move:
self.writeline("info book move: %s" % move)
self.writeline("info book search time: %f" % (_xq.currenttime() - self.starttime))
self.writeline("bestmove %s" % move)
return
if line.startswith("go ponder "):
self.ponder = True
line = line[10:]
elif line.startswith("go draw "):
self.draw = True
line = line[8:]
else:
line = line[2:]
if self.usemillisec:
propertime = limittime = float(24*3600*1000)
else:
propertime = limittime = float(24*3600)
parameters = line.split()
if parameters:
parameter = parameters[0]
if parameter == "depth":
self.ponder = False
parameter = parameters[1]
if parameter != "infinite":
self.depth = int(parameter)
elif parameter == "time":
propertime = limittime = totaltime = float(parameters[1])
parameters = parameters[2:]
while parameters:
parameter = parameters[0]
if parameter == "movestogo":
count = int(parameters[1])
propertime = totaltime/count
limittime = totaltime
elif parameter == "increment":
increment = int(parameters[1])
propertime = totaltime*0.05+increment
limittime = totaltime*0.5
parameters = parameters[2:]
limittime = min(propertime*1.618, limittime)
propertime = propertime*0.618
if self.usemillisec:
propertime = propertime * 0.001
limittime = limittime * 0.001
self.mintime = self.starttime + propertime
self.maxtime = self.starttime + limittime
move = self.search([_xq.ucci2move(move) for move in self.bans])
if move:
self.writeline("bestmove %s" % _xq.move2ucci(move))
else:
self.writeline("nobestmove") | Python |
from distutils.core import setup
import py2exe
setup(
console = ["main.py"],
)
| Python |
#!/usr/bin/env python
#coding=utf-8
def main():
import sys
if len(sys.argv) == 1:
import snake.protocol
engine = snake.protocol.Engine()
engine.run()
if __name__ == "__main__":
main() | Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.